From 7e966914050e66219689001ff4ab601a49eef0ac Mon Sep 17 00:00:00 2001 From: Instrumental Date: Fri, 7 Sep 2018 13:43:23 -0500 Subject: Mass whitespace changes (Style Warnings) Issue-ID: AAF-473 Change-Id: Ia1b3825a527bd56299949b5962bb9354dffbeef8 Signed-off-by: Instrumental --- .../src/main/java/org/onap/aaf/auth/Batch.java | 18 +- .../src/main/java/org/onap/aaf/auth/CassBatch.java | 8 +- .../java/org/onap/aaf/auth/actions/ActionDAO.java | 2 +- .../org/onap/aaf/auth/actions/ActionPuntDAO.java | 4 +- .../java/org/onap/aaf/auth/actions/CacheTouch.java | 2 +- .../java/org/onap/aaf/auth/actions/CredDelete.java | 2 +- .../java/org/onap/aaf/auth/actions/CredPunt.java | 10 +- .../main/java/org/onap/aaf/auth/actions/Email.java | 34 +- .../java/org/onap/aaf/auth/actions/EmailPrint.java | 16 +- .../java/org/onap/aaf/auth/actions/Message.java | 4 +- .../java/org/onap/aaf/auth/actions/NSACreate.java | 4 +- .../java/org/onap/aaf/auth/actions/NSADelete.java | 4 +- .../org/onap/aaf/auth/actions/NSDescUpdate.java | 4 +- .../java/org/onap/aaf/auth/actions/PermCreate.java | 4 +- .../java/org/onap/aaf/auth/actions/PermDelete.java | 4 +- .../java/org/onap/aaf/auth/actions/PermModify.java | 28 +- .../java/org/onap/aaf/auth/actions/RoleCreate.java | 4 +- .../java/org/onap/aaf/auth/actions/RoleDelete.java | 4 +- .../java/org/onap/aaf/auth/actions/RoleModify.java | 40 +- .../main/java/org/onap/aaf/auth/actions/URAdd.java | 2 +- .../java/org/onap/aaf/auth/actions/URDelete.java | 4 +- .../org/onap/aaf/auth/actions/URFutureApprove.java | 12 +- .../onap/aaf/auth/actions/URFutureApproveExec.java | 14 +- .../java/org/onap/aaf/auth/actions/URModify.java | 12 +- .../java/org/onap/aaf/auth/actions/URPunt.java | 8 +- .../java/org/onap/aaf/auth/helpers/Approval.java | 44 +- .../org/onap/aaf/auth/helpers/CacheChange.java | 4 +- .../java/org/onap/aaf/auth/helpers/Creator.java | 2 +- .../main/java/org/onap/aaf/auth/helpers/Cred.java | 50 +- .../java/org/onap/aaf/auth/helpers/Future.java | 18 +- .../java/org/onap/aaf/auth/helpers/History.java | 6 +- .../org/onap/aaf/auth/helpers/InputIterator.java | 2 +- .../java/org/onap/aaf/auth/helpers/MiscID.java | 14 +- .../java/org/onap/aaf/auth/helpers/MonthData.java | 16 +- .../main/java/org/onap/aaf/auth/helpers/NS.java | 8 +- .../org/onap/aaf/auth/helpers/Notification.java | 28 +- .../java/org/onap/aaf/auth/helpers/NsAttrib.java | 6 +- .../main/java/org/onap/aaf/auth/helpers/Perm.java | 10 +- .../main/java/org/onap/aaf/auth/helpers/Role.java | 8 +- .../java/org/onap/aaf/auth/helpers/UserRole.java | 20 +- .../java/org/onap/aaf/auth/javax/JavaxMailer.java | 2 +- .../org/onap/aaf/auth/reports/ExpiringNext.java | 32 +- .../java/org/onap/aaf/auth/update/Expiring.java | 124 ++-- .../java/org/onap/aaf/auth/update/ExpiringP2.java | 16 +- .../org/onap/aaf/auth/update/NotifyApprovals.java | 44 +- .../onap/aaf/auth/update/NotifyCredExpiring.java | 64 +- .../aaf/auth/helpers/test/JU_InputIterator.java | 2 +- .../onap/aaf/auth/helpers/test/JU_MonthData.java | 4 +- .../java/org/onap/aaf/auth/dao/AbsCassDAO.java | 60 +- .../main/java/org/onap/aaf/auth/dao/Cached.java | 32 +- .../main/java/org/onap/aaf/auth/dao/CachedDAO.java | 34 +- .../java/org/onap/aaf/auth/dao/CassAccess.java | 54 +- .../java/org/onap/aaf/auth/dao/CassDAOImpl.java | 72 +- .../main/java/org/onap/aaf/auth/dao/Loader.java | 32 +- .../onap/aaf/auth/dao/cached/CachedCredDAO.java | 2 +- .../onap/aaf/auth/dao/cached/CachedPermDAO.java | 12 +- .../onap/aaf/auth/dao/cached/CachedRoleDAO.java | 8 +- .../aaf/auth/dao/cached/CachedUserRoleDAO.java | 18 +- .../org/onap/aaf/auth/dao/cass/ApprovalDAO.java | 16 +- .../java/org/onap/aaf/auth/dao/cass/ArtiDAO.java | 16 +- .../org/onap/aaf/auth/dao/cass/CacheInfoDAO.java | 70 +- .../java/org/onap/aaf/auth/dao/cass/CertDAO.java | 16 +- .../java/org/onap/aaf/auth/dao/cass/CredDAO.java | 16 +- .../java/org/onap/aaf/auth/dao/cass/FutureDAO.java | 6 +- .../org/onap/aaf/auth/dao/cass/HistoryDAO.java | 14 +- .../java/org/onap/aaf/auth/dao/cass/LocateDAO.java | 8 +- .../java/org/onap/aaf/auth/dao/cass/Namespace.java | 10 +- .../java/org/onap/aaf/auth/dao/cass/NsDAO.java | 54 +- .../java/org/onap/aaf/auth/dao/cass/NsSplit.java | 6 +- .../java/org/onap/aaf/auth/dao/cass/NsType.java | 10 +- .../java/org/onap/aaf/auth/dao/cass/PermDAO.java | 20 +- .../java/org/onap/aaf/auth/dao/cass/RoleDAO.java | 16 +- .../org/onap/aaf/auth/dao/cass/UserRoleDAO.java | 8 +- .../org/onap/aaf/auth/dao/hl/CassExecutor.java | 4 +- .../java/org/onap/aaf/auth/dao/hl/Function.java | 120 ++-- .../java/org/onap/aaf/auth/dao/hl/PermLookup.java | 28 +- .../java/org/onap/aaf/auth/dao/hl/Question.java | 122 ++-- .../org/onap/aaf/auth/direct/DirectAAFLocator.java | 20 +- .../org/onap/aaf/auth/direct/DirectAAFLur.java | 32 +- .../onap/aaf/auth/direct/DirectAAFUserPass.java | 6 +- .../onap/aaf/auth/direct/DirectCertIdentity.java | 6 +- .../onap/aaf/auth/direct/DirectLocatorCreator.java | 2 +- .../org/onap/aaf/auth/direct/DirectRegistrar.java | 18 +- .../test/java/org/onap/aaf/auth/dao/JU_Cached.java | 6 +- .../org/onap/aaf/auth/dao/aaf/test/AbsJUCass.java | 16 +- .../aaf/auth/dao/aaf/test/JU_Bytification.java | 16 +- .../org/onap/aaf/auth/dao/aaf/test/JU_NsType.java | 2 +- .../src/main/java/org/onap/aaf/auth/cm/AAF_CM.java | 18 +- .../org/onap/aaf/auth/cm/api/API_Artifact.java | 12 +- .../java/org/onap/aaf/auth/cm/api/API_Cert.java | 12 +- .../src/main/java/org/onap/aaf/auth/cm/ca/CA.java | 44 +- .../main/java/org/onap/aaf/auth/cm/ca/JscepCA.java | 34 +- .../main/java/org/onap/aaf/auth/cm/ca/LocalCA.java | 32 +- .../onap/aaf/auth/cm/ca/X509ChainWithIssuer.java | 16 +- .../java/org/onap/aaf/auth/cm/ca/X509andChain.java | 2 +- .../java/org/onap/aaf/auth/cm/cert/BCFactory.java | 14 +- .../java/org/onap/aaf/auth/cm/cert/CSRMeta.java | 26 +- .../main/java/org/onap/aaf/auth/cm/cert/RDN.java | 14 +- .../org/onap/aaf/auth/cm/facade/FacadeImpl.java | 48 +- .../org/onap/aaf/auth/cm/mapper/Mapper1_0.java | 48 +- .../org/onap/aaf/auth/cm/mapper/Mapper2_0.java | 40 +- .../org/onap/aaf/auth/cm/service/CMService.java | 6 +- .../aaf/auth/cm/validation/CertmanValidator.java | 22 +- .../org/onap/aaf/auth/cm/test/CertmanTest.java | 10 +- .../main/java/org/onap/aaf/auth/cmd/AAFcli.java | 38 +- .../main/java/org/onap/aaf/auth/cmd/BaseCmd.java | 10 +- .../src/main/java/org/onap/aaf/auth/cmd/Cmd.java | 98 +-- .../src/main/java/org/onap/aaf/auth/cmd/Help.java | 14 +- .../java/org/onap/aaf/auth/cmd/mgmt/Clear.java | 6 +- .../main/java/org/onap/aaf/auth/cmd/mgmt/Deny.java | 8 +- .../main/java/org/onap/aaf/auth/cmd/mgmt/Log.java | 10 +- .../java/org/onap/aaf/auth/cmd/mgmt/SessClear.java | 4 +- .../main/java/org/onap/aaf/auth/cmd/ns/Admin.java | 4 +- .../main/java/org/onap/aaf/auth/cmd/ns/Attrib.java | 8 +- .../main/java/org/onap/aaf/auth/cmd/ns/Create.java | 10 +- .../main/java/org/onap/aaf/auth/cmd/ns/Delete.java | 2 +- .../java/org/onap/aaf/auth/cmd/ns/Describe.java | 4 +- .../main/java/org/onap/aaf/auth/cmd/ns/List.java | 38 +- .../org/onap/aaf/auth/cmd/ns/ListActivity.java | 2 +- .../onap/aaf/auth/cmd/ns/ListAdminResponsible.java | 4 +- .../java/org/onap/aaf/auth/cmd/ns/ListByName.java | 18 +- .../org/onap/aaf/auth/cmd/ns/ListChildren.java | 6 +- .../onap/aaf/auth/cmd/ns/ListNsKeysByAttrib.java | 6 +- .../org/onap/aaf/auth/cmd/ns/ListUsersContact.java | 26 +- .../org/onap/aaf/auth/cmd/ns/ListUsersInRole.java | 26 +- .../onap/aaf/auth/cmd/ns/ListUsersWithPerm.java | 26 +- .../main/java/org/onap/aaf/auth/cmd/ns/Owner.java | 4 +- .../java/org/onap/aaf/auth/cmd/perm/Create.java | 18 +- .../java/org/onap/aaf/auth/cmd/perm/Delete.java | 4 +- .../java/org/onap/aaf/auth/cmd/perm/Describe.java | 4 +- .../java/org/onap/aaf/auth/cmd/perm/Grant.java | 8 +- .../main/java/org/onap/aaf/auth/cmd/perm/List.java | 14 +- .../org/onap/aaf/auth/cmd/perm/ListActivity.java | 2 +- .../org/onap/aaf/auth/cmd/perm/ListByUser.java | 6 +- .../java/org/onap/aaf/auth/cmd/perm/Rename.java | 4 +- .../org/onap/aaf/auth/cmd/role/CreateDelete.java | 12 +- .../java/org/onap/aaf/auth/cmd/role/Describe.java | 4 +- .../main/java/org/onap/aaf/auth/cmd/role/List.java | 46 +- .../org/onap/aaf/auth/cmd/role/ListActivity.java | 2 +- .../org/onap/aaf/auth/cmd/role/ListByUser.java | 4 +- .../main/java/org/onap/aaf/auth/cmd/role/User.java | 8 +- .../main/java/org/onap/aaf/auth/cmd/user/Cred.java | 18 +- .../main/java/org/onap/aaf/auth/cmd/user/Delg.java | 6 +- .../main/java/org/onap/aaf/auth/cmd/user/List.java | 14 +- .../org/onap/aaf/auth/cmd/user/ListActivity.java | 2 +- .../org/onap/aaf/auth/cmd/user/ListApprovals.java | 4 +- .../org/onap/aaf/auth/cmd/user/ListDelegates.java | 4 +- .../org/onap/aaf/auth/cmd/user/ListForCreds.java | 4 +- .../onap/aaf/auth/cmd/user/ListForPermission.java | 8 +- .../org/onap/aaf/auth/cmd/user/ListForRoles.java | 4 +- .../main/java/org/onap/aaf/auth/cmd/user/Role.java | 2 +- .../main/java/org/onap/aaf/auth/cache/Cache.java | 18 +- .../main/java/org/onap/aaf/auth/common/Define.java | 14 +- .../main/java/org/onap/aaf/auth/env/AuthzEnv.java | 20 +- .../org/onap/aaf/auth/env/AuthzTransFilter.java | 24 +- .../java/org/onap/aaf/auth/env/AuthzTransImpl.java | 18 +- .../onap/aaf/auth/env/AuthzTransOnlyFilter.java | 2 +- .../main/java/org/onap/aaf/auth/env/NullTrans.java | 2 +- .../main/java/org/onap/aaf/auth/layer/Result.java | 10 +- .../main/java/org/onap/aaf/auth/local/AbsData.java | 14 +- .../java/org/onap/aaf/auth/local/DataFile.java | 34 +- .../java/org/onap/aaf/auth/local/TextIndex.java | 36 +- .../java/org/onap/aaf/auth/org/Organization.java | 4 +- .../org/onap/aaf/auth/org/OrganizationFactory.java | 32 +- .../java/org/onap/aaf/auth/rserv/Acceptor.java | 46 +- .../org/onap/aaf/auth/rserv/CachingFileAccess.java | 70 +- .../main/java/org/onap/aaf/auth/rserv/Content.java | 12 +- .../java/org/onap/aaf/auth/rserv/HttpCode.java | 18 +- .../main/java/org/onap/aaf/auth/rserv/Match.java | 60 +- .../java/org/onap/aaf/auth/rserv/RServlet.java | 8 +- .../main/java/org/onap/aaf/auth/rserv/Route.java | 8 +- .../main/java/org/onap/aaf/auth/rserv/Routes.java | 14 +- .../java/org/onap/aaf/auth/rserv/TransFilter.java | 16 +- .../java/org/onap/aaf/auth/rserv/TypedCode.java | 50 +- .../main/java/org/onap/aaf/auth/rserv/Version.java | 18 +- .../java/org/onap/aaf/auth/server/AbsService.java | 28 +- .../onap/aaf/auth/server/AbsServiceStarter.java | 10 +- .../onap/aaf/auth/server/JettyServiceStarter.java | 28 +- .../java/org/onap/aaf/auth/server/Log4JLogIt.java | 12 +- .../org/onap/aaf/auth/validation/Validator.java | 44 +- .../org/onap/aaf/auth/local/test/JU_AbsData.java | 2 +- .../org/onap/aaf/auth/local/test/JU_DataFile.java | 4 +- .../org/onap/aaf/auth/local/test/JU_TextIndex.java | 2 +- .../aaf/auth/request/test/NSAttribCompare.java | 12 +- .../org/onap/aaf/auth/request/test/NSCompare.java | 4 +- .../aaf/auth/validation/test/JU_Validator.java | 2 +- .../src/main/java/org/onap/aaf/org/DefaultOrg.java | 72 +- .../java/org/onap/aaf/org/DefaultOrgIdentity.java | 12 +- .../src/main/java/org/onap/aaf/org/Identities.java | 2 +- .../java/org/onap/aaf/org/test/JU_Identities.java | 4 +- .../src/main/java/org/onap/aaf/auth/fs/AAF_FS.java | 2 +- .../java/org/onap/aaf/auth/fs/test/JU_AAF_FS.java | 4 +- .../src/main/java/org/onap/aaf/auth/cui/CUI.java | 2 +- .../main/java/org/onap/aaf/auth/gui/AAF_GUI.java | 4 +- .../java/org/onap/aaf/auth/gui/BreadCrumbs.java | 10 +- .../main/java/org/onap/aaf/auth/gui/Display.java | 24 +- .../src/main/java/org/onap/aaf/auth/gui/Form.java | 2 +- .../main/java/org/onap/aaf/auth/gui/NamedCode.java | 2 +- .../org/onap/aaf/auth/gui/OrgLookupFilter.java | 6 +- .../src/main/java/org/onap/aaf/auth/gui/Page.java | 38 +- .../main/java/org/onap/aaf/auth/gui/SlotCode.java | 4 +- .../src/main/java/org/onap/aaf/auth/gui/Table.java | 26 +- .../java/org/onap/aaf/auth/gui/XFrameFilter.java | 2 +- .../java/org/onap/aaf/auth/gui/pages/ApiDocs.java | 44 +- .../org/onap/aaf/auth/gui/pages/ApiExample.java | 10 +- .../onap/aaf/auth/gui/pages/ApprovalAction.java | 12 +- .../org/onap/aaf/auth/gui/pages/ApprovalForm.java | 20 +- .../aaf/auth/gui/pages/CMArtiChangeAction.java | 44 +- .../onap/aaf/auth/gui/pages/CMArtiChangeForm.java | 24 +- .../onap/aaf/auth/gui/pages/CMArtifactShow.java | 22 +- .../org/onap/aaf/auth/gui/pages/CredDetail.java | 48 +- .../org/onap/aaf/auth/gui/pages/LoginLanding.java | 6 +- .../java/org/onap/aaf/auth/gui/pages/NsDetail.java | 14 +- .../org/onap/aaf/auth/gui/pages/NsHistory.java | 2 +- .../org/onap/aaf/auth/gui/pages/NsInfoAction.java | 14 +- .../org/onap/aaf/auth/gui/pages/NsInfoForm.java | 18 +- .../java/org/onap/aaf/auth/gui/pages/NssShow.java | 12 +- .../onap/aaf/auth/gui/pages/PassChangeAction.java | 34 +- .../onap/aaf/auth/gui/pages/PassChangeForm.java | 30 +- .../onap/aaf/auth/gui/pages/PassDeleteAction.java | 4 +- .../aaf/auth/gui/pages/PendingRequestsShow.java | 6 +- .../org/onap/aaf/auth/gui/pages/PermDetail.java | 10 +- .../onap/aaf/auth/gui/pages/PermGrantAction.java | 2 +- .../org/onap/aaf/auth/gui/pages/PermGrantForm.java | 4 +- .../org/onap/aaf/auth/gui/pages/PermHistory.java | 2 +- .../org/onap/aaf/auth/gui/pages/PermsShow.java | 6 +- .../org/onap/aaf/auth/gui/pages/RequestDetail.java | 4 +- .../org/onap/aaf/auth/gui/pages/RoleDetail.java | 30 +- .../onap/aaf/auth/gui/pages/RoleDetailAction.java | 18 +- .../org/onap/aaf/auth/gui/pages/RoleHistory.java | 2 +- .../org/onap/aaf/auth/gui/pages/RolesShow.java | 2 +- .../onap/aaf/auth/gui/pages/UserRoleExtend.java | 2 +- .../onap/aaf/auth/gui/pages/UserRoleRemove.java | 2 +- .../java/org/onap/aaf/auth/gui/table/RefCell.java | 2 +- .../java/org/onap/aaf/auth/hello/AAF_Hello.java | 2 +- .../java/org/onap/aaf/auth/hello/API_Hello.java | 14 +- .../org/onap/aaf/auth/hello/test/HelloTester.java | 6 +- .../java/org/onap/aaf/auth/locate/AAF_Locate.java | 10 +- .../org/onap/aaf/auth/locate/BasicAuthCode.java | 8 +- .../onap/aaf/auth/locate/api/API_AAFAccess.java | 12 +- .../org/onap/aaf/auth/locate/api/API_Find.java | 2 +- .../org/onap/aaf/auth/locate/api/API_Proxy.java | 4 +- .../aaf/auth/locate/facade/LocateFacadeImpl.java | 30 +- .../onap/aaf/auth/locate/mapper/Mapper_1_1.java | 22 +- .../aaf/auth/locate/service/LocateServiceImpl.java | 24 +- .../auth/locate/validation/LocateValidator.java | 32 +- .../java/org/onap/aaf/auth/oauth/AAF_OAuth.java | 12 +- .../org/onap/aaf/auth/oauth/DirectOAuthTAF.java | 40 +- .../java/org/onap/aaf/auth/oauth/OAuth2Filter.java | 8 +- .../org/onap/aaf/auth/oauth/api/API_Token.java | 4 +- .../auth/oauth/facade/DirectIntrospectImpl.java | 4 +- .../onap/aaf/auth/oauth/facade/OAFacadeImpl.java | 32 +- .../org/onap/aaf/auth/oauth/mapper/Mapper1_0.java | 32 +- .../aaf/auth/oauth/mapper/MapperIntrospect1_0.java | 12 +- .../auth/oauth/service/JSONPermLoaderFactory.java | 16 +- .../onap/aaf/auth/oauth/service/OAuthService.java | 60 +- .../org/onap/aaf/auth/service/AAF_Service.java | 12 +- .../aaf/auth/service/AuthzCassServiceImpl.java | 782 ++++++++++----------- .../org/onap/aaf/auth/service/api/API_Api.java | 4 +- .../onap/aaf/auth/service/api/API_Approval.java | 8 +- .../org/onap/aaf/auth/service/api/API_Creds.java | 28 +- .../org/onap/aaf/auth/service/api/API_History.java | 28 +- .../org/onap/aaf/auth/service/api/API_Mgmt.java | 28 +- .../org/onap/aaf/auth/service/api/API_Perms.java | 2 +- .../aaf/auth/service/facade/AuthzFacadeImpl.java | 204 +++--- .../onap/aaf/auth/service/mapper/Mapper_2_0.java | 116 +-- .../auth/service/validation/ServiceValidator.java | 64 +- .../aaf/authz/service/mapper/JU_Mapper_2_0.java | 4 +- .../java/org/onap/aaf/cadi/aaf/AAFPermission.java | 14 +- .../main/java/org/onap/aaf/cadi/aaf/PermEval.java | 46 +- .../org/onap/aaf/cadi/aaf/TestConnectivity.java | 54 +- .../aaf/cadi/aaf/cert/AAFListedCertIdentity.java | 34 +- .../org/onap/aaf/cadi/aaf/client/ErrMessage.java | 2 +- .../org/onap/aaf/cadi/aaf/client/Examples.java | 34 +- .../java/org/onap/aaf/cadi/aaf/v2_0/AAFAuthn.java | 10 +- .../java/org/onap/aaf/cadi/aaf/v2_0/AAFCon.java | 42 +- .../org/onap/aaf/cadi/aaf/v2_0/AAFConHttp.java | 6 +- .../org/onap/aaf/cadi/aaf/v2_0/AAFLocator.java | 14 +- .../org/onap/aaf/cadi/aaf/v2_0/AAFLurPerm.java | 20 +- .../java/org/onap/aaf/cadi/aaf/v2_0/AAFTaf.java | 22 +- .../onap/aaf/cadi/aaf/v2_0/AAFTrustChecker.java | 8 +- .../org/onap/aaf/cadi/aaf/v2_0/AbsAAFLocator.java | 92 +-- .../java/org/onap/aaf/cadi/aaf/v2_0/AbsAAFLur.java | 84 +-- .../java/org/onap/aaf/cadi/configure/Agent.java | 230 +++--- .../org/onap/aaf/cadi/configure/ArtifactDir.java | 54 +- .../java/org/onap/aaf/cadi/configure/Factory.java | 46 +- .../cadi/configure/PlaceArtifactInKeystore.java | 12 +- .../aaf/cadi/configure/PlaceArtifactOnStream.java | 4 +- .../aaf/cadi/configure/PlaceArtifactScripts.java | 6 +- .../java/org/onap/aaf/cadi/oauth/AAFToken.java | 14 +- .../java/org/onap/aaf/cadi/oauth/AbsOTafLur.java | 10 +- .../org/onap/aaf/cadi/oauth/HRenewingTokenSS.java | 10 +- .../org/onap/aaf/cadi/oauth/OAuth2HttpTaf.java | 6 +- .../java/org/onap/aaf/cadi/oauth/OAuth2Lur.java | 14 +- .../java/org/onap/aaf/cadi/oauth/TokenClient.java | 72 +- .../onap/aaf/cadi/oauth/TokenClientFactory.java | 24 +- .../java/org/onap/aaf/cadi/oauth/TokenMgr.java | 18 +- .../java/org/onap/aaf/cadi/oauth/TokenPerm.java | 20 +- .../java/org/onap/aaf/cadi/oauth/TzHClient.java | 4 +- .../org/onap/aaf/cadi/obasic/OBasicHttpTaf.java | 30 +- .../src/main/java/org/onap/aaf/cadi/olur/OLur.java | 18 +- .../java/org/onap/aaf/cadi/persist/Persist.java | 46 +- .../org/onap/aaf/cadi/persist/PersistFile.java | 40 +- .../java/org/onap/aaf/cadi/persist/Persisting.java | 12 +- .../java/org/onap/aaf/cadi/register/Registrar.java | 12 +- .../onap/aaf/cadi/register/RemoteRegistrant.java | 24 +- .../main/java/org/onap/aaf/cadi/sso/AAFSSO.java | 54 +- .../org/onap/aaf/cadi/aaf/test/TestHClient.java | 8 +- .../org/onap/aaf/cadi/cm/test/JU_ArtifactDir.java | 4 +- .../java/org/onap/aaf/cadi/cm/test/JU_Factory.java | 4 +- .../cadi/cm/test/JU_PlaceArtifactInKeystore.java | 4 +- .../org/onap/aaf/cadi/oauth/test/JU_AAFToken.java | 2 +- .../org/onap/aaf/cadi/oauth/test/JU_OAuthTest.java | 32 +- .../java/org/onap/aaf/client/sample/Sample.java | 14 +- .../onap/aaf/cadi/client/AbsAuthentication.java | 12 +- .../org/onap/aaf/cadi/client/AbsTransferSS.java | 2 +- .../main/java/org/onap/aaf/cadi/client/Rcli.java | 38 +- .../main/java/org/onap/aaf/cadi/client/Result.java | 2 +- .../onap/aaf/cadi/http/HAuthorizationHeader.java | 4 +- .../java/org/onap/aaf/cadi/http/HBasicAuthSS.java | 4 +- .../main/java/org/onap/aaf/cadi/http/HClient.java | 30 +- .../main/java/org/onap/aaf/cadi/http/HMangr.java | 40 +- .../java/org/onap/aaf/cadi/http/HNoAuthSS.java | 2 +- .../main/java/org/onap/aaf/cadi/http/HRcli.java | 4 +- .../org/onap/aaf/cadi/http/HSecurityInfoInit.java | 4 +- .../java/org/onap/aaf/cadi/http/HTransferSS.java | 6 +- .../main/java/org/onap/aaf/cadi/http/HX509SS.java | 18 +- .../java/org/onap/aaf/cadi/locator/DNSLocator.java | 30 +- .../org/onap/aaf/cadi/locator/HotPeerLocator.java | 64 +- .../org/onap/aaf/cadi/locator/PropertyLocator.java | 54 +- .../aaf/cadi/locator/SingleEndpointLocator.java | 4 +- .../org/onap/aaf/cadi/routing/GreatCircle.java | 4 +- .../aaf/cadi/locator/test/JU_PropertyLocator.java | 2 +- cadi/core/src/main/java/org/onap/aaf/cadi/AES.java | 4 +- .../main/java/org/onap/aaf/cadi/AbsUserCache.java | 60 +- .../src/main/java/org/onap/aaf/cadi/Access.java | 6 +- .../onap/aaf/cadi/BufferedServletInputStream.java | 24 +- .../src/main/java/org/onap/aaf/cadi/CadiWrap.java | 10 +- .../src/main/java/org/onap/aaf/cadi/Capacitor.java | 48 +- .../src/main/java/org/onap/aaf/cadi/CmdLine.java | 84 +-- .../core/src/main/java/org/onap/aaf/cadi/Hash.java | 34 +- .../main/java/org/onap/aaf/cadi/PropAccess.java | 70 +- .../org/onap/aaf/cadi/ServletContextAccess.java | 4 +- .../core/src/main/java/org/onap/aaf/cadi/Symm.java | 94 +-- .../core/src/main/java/org/onap/aaf/cadi/User.java | 6 +- .../main/java/org/onap/aaf/cadi/config/Config.java | 152 ++-- .../main/java/org/onap/aaf/cadi/config/Get.java | 6 +- .../java/org/onap/aaf/cadi/config/GetAccess.java | 2 +- .../java/org/onap/aaf/cadi/config/MultiGet.java | 4 +- .../org/onap/aaf/cadi/config/SecurityInfoC.java | 4 +- .../java/org/onap/aaf/cadi/config/UsersDump.java | 28 +- .../java/org/onap/aaf/cadi/filter/CadiFilter.java | 56 +- .../org/onap/aaf/cadi/filter/CadiHTTPManip.java | 24 +- .../main/java/org/onap/aaf/cadi/filter/FCGet.java | 10 +- .../org/onap/aaf/cadi/lur/ConfigPrincipal.java | 4 +- .../main/java/org/onap/aaf/cadi/lur/EpiLur.java | 34 +- .../main/java/org/onap/aaf/cadi/lur/LocalLur.java | 4 +- .../onap/aaf/cadi/principal/BasicPrincipal.java | 10 +- .../aaf/cadi/principal/CachedBasicPrincipal.java | 2 +- .../java/org/onap/aaf/cadi/principal/Kind.java | 8 +- .../aaf/cadi/principal/OAuth2FormPrincipal.java | 2 +- .../onap/aaf/cadi/principal/TaggedPrincipal.java | 2 +- .../onap/aaf/cadi/principal/TrustPrincipal.java | 4 +- .../org/onap/aaf/cadi/principal/X509Principal.java | 10 +- .../main/java/org/onap/aaf/cadi/taf/EpiTaf.java | 6 +- .../java/org/onap/aaf/cadi/taf/HttpEpiTaf.java | 2 +- .../org/onap/aaf/cadi/taf/basic/BasicHttpTaf.java | 32 +- .../java/org/onap/aaf/cadi/taf/cert/X509Taf.java | 52 +- .../onap/aaf/cadi/taf/dos/DenialOfServiceTaf.java | 76 +- .../src/main/java/org/onap/aaf/cadi/util/FQI.java | 6 +- .../org/onap/aaf/cadi/util/JsonOutputStream.java | 10 +- .../main/java/org/onap/aaf/cadi/util/NetMask.java | 12 +- .../main/java/org/onap/aaf/cadi/util/Split.java | 24 +- .../org/onap/aaf/cadi/util/SubStandardConsole.java | 2 +- .../java/org/onap/aaf/cadi/util/TheConsole.java | 2 +- .../org/onap/aaf/cadi/util/UserChainManip.java | 18 +- .../src/main/java/org/onap/aaf/cadi/util/Vars.java | 30 +- .../main/java/org/onap/aaf/cadi/wsse/Match.java | 20 +- .../main/java/org/onap/aaf/cadi/wsse/XReader.java | 70 +- .../onap/aaf/cadi/filter/test/JU_AUTHZServlet.java | 2 +- .../aaf/cadi/principal/test/JU_X509Principal.java | 6 +- .../cadi/taf/dos/test/JU_DenialOfServiceTaf.java | 2 +- .../test/java/org/onap/aaf/cadi/test/JU_AES.java | 2 +- .../cadi/test/JU_BufferedServletInputStream.java | 8 +- .../java/org/onap/aaf/cadi/test/JU_Capacitor.java | 16 +- .../java/org/onap/aaf/cadi/test/JU_CmdLine.java | 2 +- .../java/org/onap/aaf/cadi/test/JU_PropAccess.java | 2 +- .../aaf/cadi/test/JU_ServletContextAccess.java | 2 +- .../org/onap/aaf/cadi/wsse/test/JU_WSSEParser.java | 4 +- .../onap/aaf/cadi/enduser/SimpleRESTClient.java | 34 +- .../onap/aaf/cadi/enduser/test/OAuthExample.java | 12 +- .../aaf/cadi/enduser/test/OnapClientExample.java | 10 +- .../cadi/enduser/test/SimpleRestClientExample.java | 10 +- .../java/org/onap/aaf/sample/cadi/MyServlet.java | 14 +- .../aaf/sample/cadi/jetty/JettyServletServer.java | 4 +- .../onap/aaf/sample/cadi/jetty/MiniJASPIWrap.java | 16 +- .../aaf/sample/cadi/tomcate/TomcatEmbedded.java | 4 +- .../org/onap/aaf/misc/env/BaseDataFactory.java | 16 +- .../main/java/org/onap/aaf/misc/env/LogTarget.java | 10 +- .../main/java/org/onap/aaf/misc/env/StoreImpl.java | 38 +- .../java/org/onap/aaf/misc/env/impl/AbsTrans.java | 36 +- .../java/org/onap/aaf/misc/env/impl/BasicEnv.java | 56 +- .../onap/aaf/misc/env/impl/JavaUtilLogTarget.java | 16 +- .../org/onap/aaf/misc/env/impl/Log4JLogTarget.java | 6 +- .../java/org/onap/aaf/misc/env/jaxb/JAXBDF.java | 2 +- .../java/org/onap/aaf/misc/env/jaxb/JAXBData.java | 20 +- .../java/org/onap/aaf/misc/env/jaxb/JAXBmar.java | 14 +- .../java/org/onap/aaf/misc/env/jaxb/JAXBumar.java | 6 +- .../java/org/onap/aaf/misc/env/util/Chrono.java | 18 +- .../onap/aaf/misc/env/util/DoubleOutputStream.java | 12 +- .../aaf/misc/env/util/RefreshableThreadObject.java | 6 +- .../java/org/onap/aaf/misc/env/util/Split.java | 22 +- .../misc/env/util/StringBuilderOutputStream.java | 2 +- .../aaf/misc/env/impl/JU_Log4JLogTargetTest.java | 2 +- .../java/org/onap/aaf/misc/rosetta/InJson.java | 24 +- .../main/java/org/onap/aaf/misc/rosetta/InXML.java | 120 ++-- .../java/org/onap/aaf/misc/rosetta/JaxInfo.java | 52 +- .../java/org/onap/aaf/misc/rosetta/JaxSet.java | 6 +- .../java/org/onap/aaf/misc/rosetta/Ladder.java | 6 +- .../java/org/onap/aaf/misc/rosetta/Marshal.java | 2 +- .../java/org/onap/aaf/misc/rosetta/OutJax.java | 4 +- .../java/org/onap/aaf/misc/rosetta/OutJson.java | 52 +- .../java/org/onap/aaf/misc/rosetta/OutRaw.java | 2 +- .../java/org/onap/aaf/misc/rosetta/OutXML.java | 60 +- .../java/org/onap/aaf/misc/rosetta/Parsed.java | 8 +- .../main/java/org/onap/aaf/misc/rosetta/Prop.java | 2 +- .../main/java/org/onap/aaf/misc/rosetta/Saved.java | 36 +- .../java/org/onap/aaf/misc/rosetta/XmlEscape.java | 24 +- .../org/onap/aaf/misc/rosetta/env/RosettaDF.java | 6 +- .../org/onap/aaf/misc/rosetta/env/RosettaData.java | 22 +- .../onap/aaf/misc/rosetta/marshal/DataWriter.java | 2 +- .../onap/aaf/misc/rosetta/marshal/DocMarshal.java | 8 +- .../onap/aaf/misc/rosetta/marshal/FieldArray.java | 16 +- .../onap/aaf/misc/rosetta/marshal/ObjArray.java | 16 +- .../onap/aaf/misc/rosetta/marshal/ObjMarshal.java | 22 +- .../onap/aaf/misc/rosetta/test/JU_FromJSON.java | 12 +- .../org/onap/aaf/misc/rosetta/test/JU_FromXML.java | 14 +- .../org/onap/aaf/misc/rosetta/test/JU_JSON.java | 2 +- .../org/onap/aaf/misc/rosetta/test/JU_Ladder.java | 12 +- .../onap/aaf/misc/rosetta/test/JU_RosettaDF.java | 4 +- .../org/onap/aaf/misc/rosetta/test/JU_Saved.java | 2 +- .../org/onap/aaf/misc/rosetta/test/JU_Struct.java | 2 +- .../org/onap/aaf/misc/rosetta/test/JU_Types.java | 22 +- .../org/onap/aaf/misc/rosetta/test/OutDump.java | 6 +- .../org/onap/aaf/misc/rosetta/test/Report.java | 4 +- .../main/java/org/onap/aaf/misc/xgen/CacheGen.java | 8 +- .../src/main/java/org/onap/aaf/misc/xgen/XGen.java | 38 +- .../java/org/onap/aaf/misc/xgen/html/HTML4Gen.java | 4 +- .../java/org/onap/aaf/misc/xgen/html/HTML5Gen.java | 4 +- .../java/org/onap/aaf/misc/xgen/html/HTMLGen.java | 24 +- .../java/org/onap/aaf/misc/xgen/html/Imports.java | 6 +- .../java/org/onap/aaf/misc/xgen/html/JSGen.java | 54 +- 452 files changed, 4873 insertions(+), 4873 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 559e3c51..5670ac95 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 @@ -98,11 +98,11 @@ public abstract class Batch { // load extra properties, i.e. // PERF.cassandra.clusters=.... batchEnv = env.getProperty(CASS_ENV); - if(batchEnv != null) { + if (batchEnv != null) { batchEnv = batchEnv.trim(); env.info().log("Redirecting to ",batchEnv,"environment"); String str; - for(String key : new String[]{ + for (String key : new String[]{ CassAccess.CASSANDRA_CLUSTERS, CassAccess.CASSANDRA_CLUSTERS_PORT, CassAccess.CASSANDRA_CLUSTERS_USER_NAME, @@ -111,7 +111,7 @@ public abstract class Batch { LOG_DIR, "SPECIAL_NAMES" }) { - if((str = env.getProperty(batchEnv+'.'+key))!=null) { + if ((str = env.getProperty(batchEnv+'.'+key))!=null) { env.setProperty(key, str); } } @@ -319,8 +319,8 @@ public abstract class Batch { private static void transferVMProps(AuthzEnv env, String ... props) { String value; - for(String key : props) { - if((value = System.getProperty(key))!=null) { + for (String key : props) { + if ((value = System.getProperty(key))!=null) { env.setProperty(key, value); } } @@ -357,8 +357,8 @@ public abstract class Batch { 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 + if (ld==null) { + if (batchEnv==null) { // Deployed Batch doesn't use different ENVs, and a common logdir ld = "logs/"; } else { ld = "logs/"+batchEnv; @@ -367,11 +367,11 @@ public abstract class Batch { return ld; } protected int count(String str, char c) { - if(str==null || str.isEmpty()) { + 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)) { + for (int i=str.indexOf(c);i>=0;i=str.indexOf(c,i+1)) { ++count; } return count; 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 cb2b158f..e80eada1 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 @@ -59,14 +59,14 @@ public abstract class CassBatch extends Batch { } public ResultSet executeQuery(String cql, String extra) { - if(isDryRun() && !cql.startsWith("SELECT")) { - if(extra!=null)env.info().log("Would query" + extra + ": " + cql); + 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); + if (extra!=null)env.info().log("query" + extra + ": " + cql); try { return session.execute(cql); } catch (InvalidQueryException e) { - if(extra==null) { + if (extra==null) { env.info().log("query: " + cql); } throw e; 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 af636d65..5275cf93 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 @@ -65,7 +65,7 @@ public abstract class ActionDAO implements Action { } public void close(AuthzTrans trans) { - if(clean) { + 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 95b35fdb..707425ca 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 @@ -58,9 +58,9 @@ public abstract class ActionPuntDAO extends ActionDAO { * 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) { + if (range>0) { int forward = Math.abs(random.nextInt()%range); - if(forward>1) { + if (forward>1) { temp.add(GregorianCalendar.MONTH, forward); temp.add(GregorianCalendar.DAY_OF_MONTH, (random.nextInt()%30)-15); } 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 e0fa4be5..269edc77 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 @@ -41,7 +41,7 @@ public class CacheTouch extends ActionDAO { @Override public Result exec(AuthzTrans trans, String table, String text) { - if(dryRun) { + if (dryRun) { trans.info().printf("Would mark %s cache in DB for clearing: %s",table, text); return Result.ok(); } else { 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 b4b7d0b3..ceb0453b 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 @@ -43,7 +43,7 @@ public class CredDelete extends ActionDAO { @Override public Result exec(AuthzTrans trans, CredDAO.Data cred, String text) { - if(dryRun) { + if (dryRun) { trans.info().log("Would Delete:",text,cred.id,CredPrint.type(cred.type),Chrono.dateOnlyStamp(cred.expires)); return Result.ok(); } else { 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 a2c9ecf6..33151d9f 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 @@ -46,14 +46,14 @@ public class CredPunt extends ActionPuntDAO { 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) { + if (read.isOKhasData()) { + for (CredDAO.Data data : read.value) { Date from = data.expires; data.expires = puntDate(from); - if(data.expires.compareTo(from)<=0) { + if (data.expires.compareTo(from)<=0) { trans.debug().printf("Error: %s is before %s", Chrono.dateOnlyStamp(data.expires), Chrono.dateOnlyStamp(from)); } else { - if(dryRun) { + 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)); @@ -62,7 +62,7 @@ public class CredPunt extends ActionPuntDAO { } } } - if(rv==null) { + if (rv==null) { rv=Result.err(read); } return rv; 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 0ac8f61d..f40eeb58 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 @@ -55,7 +55,7 @@ public class Email implements Action{ public Email clear() { toList.clear(); ccList.clear(); - for(String s: defaultCC) { + for (String s: defaultCC) { ccList.add(s); } return this; @@ -71,35 +71,35 @@ public class Email implements Action{ } public Email addTo(Identity id) { - if(id!=null && !toList.contains(id.email())) { + if (id!=null && !toList.contains(id.email())) { toList.add(id.email()); } return this; } public Email addTo(Collection users) { - for(String u : users) { + for (String u : users) { addTo(u); } return this; } public Email addTo(String email) { - if(!toList.contains(email)) { + if (!toList.contains(email)) { toList.add(email); } return this; } public Email addCC(Identity id) { - if(id!=null && !ccList.contains(id.email())) { + if (id!=null && !ccList.contains(id.email())) { ccList.add(id.email()); } return this; } public Email addCC(String email) { - if(!ccList.contains(email)) { + if (!ccList.contains(email)) { ccList.add(email); } return this; @@ -108,7 +108,7 @@ public class Email implements Action{ public Email add(Identity id, boolean toSuper) throws OrganizationException { Identity responsible = id.responsibleTo(); - if(toSuper) { + if (toSuper) { addTo(responsible.email()); addCC(id.email()); } else { @@ -119,7 +119,7 @@ public class Email implements Action{ } public Email subject(String format, Object ... args) { - if(format.contains("%s")) { + if (format.contains("%s")) { subject = String.format(format, args); } else { subject = format; @@ -140,18 +140,18 @@ public class Email implements Action{ @Override public Result exec(AuthzTrans trans, Organization org, String text) { StringBuilder sb = new StringBuilder(); - if(preamble!=null) { + if (preamble!=null) { sb.append(lineIndent); sb.append(preamble); sb.append("\n\n"); } - if(msg!=null) { + if (msg!=null) { msg.msg(sb,lineIndent); sb.append("\n"); } - if(sig!=null) { + if (sig!=null) { sb.append(sig); sb.append("\n"); } @@ -159,7 +159,7 @@ public class Email implements Action{ long ct = System.currentTimeMillis(); long wait = ct-lastSent; lastSent = ct; - if(wait < 100) { // 10 per second + if (wait < 100) { // 10 per second try { Thread.sleep(wait); } catch (InterruptedException e) { @@ -188,8 +188,8 @@ public class Email implements Action{ public void log(PrintStream ps, String text) { ps.print(Chrono.dateTime()); boolean first = true; - for(String s : toList) { - if(first) { + for (String s : toList) { + if (first) { first = false; ps.print(": "); } else { @@ -197,10 +197,10 @@ public class Email implements Action{ } ps.print(s); } - if(!ccList.isEmpty()) { + if (!ccList.isEmpty()) { first=true; - for(String s : ccList) { - if(first) { + for (String s : ccList) { + if (first) { first = false; ps.print(" ["); } else { 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 5fdc15b1..141e382f 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 @@ -43,8 +43,8 @@ public class EmailPrint extends Email { PrintStream out = System.out; boolean first = true; out.print("To: "); - for(String s: toList) { - if(first) {first = false;} + for (String s: toList) { + if (first) {first = false;} else {out.print(',');} out.print(s); } @@ -52,8 +52,8 @@ public class EmailPrint extends Email { first = true; out.print("CC: "); - for(String s: ccList) { - if(first) {first = false;} + for (String s: ccList) { + if (first) {first = false;} else {out.print(',');} out.print(s); } @@ -64,7 +64,7 @@ public class EmailPrint extends Email { out.println(); boolean go = true; - for(int start=0, end=LINE_LENGTH;go;start=end,end=Math.min(msg.length(), start+LINE_LENGTH)) { + 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: @@ -75,13 +75,13 @@ public class EmailPrint extends Email { out.println(); break; default: - if(retstart && retstart && ret { @Override public Result exec(AuthzTrans trans, NsAttrib nsa, String text) { - if(dryRun) { + 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()) { + 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); 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 4bed8687..c8a1c82c 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 @@ -41,12 +41,12 @@ public class NSADelete extends ActionDAO { @Override public Result exec(AuthzTrans trans, NsAttrib nsa, String text) { - if(dryRun) { + 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()) { + 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); 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 98fad0ab..d5d93b38 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 @@ -41,12 +41,12 @@ public class NSDescUpdate extends ActionDAO { @Override public Result exec(AuthzTrans trans, NS ns, String desc) { - if(dryRun) { + 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()) { + 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); 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 c32234d7..a6c02f2c 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 @@ -52,12 +52,12 @@ public class PermCreate extends ActionDAO { pdd.description = p.description; pdd.roles = p.roles; - if(dryRun) { + 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()) { + if (rv.isOK()) { trans.info().log("Created Perm:",text,p.fullType()); } else { trans.error().log("Error Creating Role -",rv.details,":",p.fullType()); 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 c5b79185..db549948 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 @@ -47,12 +47,12 @@ public class PermDelete extends ActionDAO { pdd.type = p.type; pdd.instance = p.instance; pdd.action = p.action; - if(dryRun) { + 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()) { + if (rv.isOK()) { trans.info().log("Deleted Perm:",text,p.fullType()); } else { trans.error().log("Error Deleting Perm -",rv.details,":",p.fullType()); 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 bc6f70ca..a3d4bb6d 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 @@ -48,35 +48,35 @@ public class PermModify extends ActionDAO { @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()) { + 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) { + 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)) { + 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)) { + 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)) { + 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) { + for (String r : d.roles) { Role role = Role.keys.get(r); - if(role.perms.contains(p.encode())) { + if (role.perms.contains(p.encode())) { modify.roleModify().exec(trans, role, new RoleModify.Modify() { @Override public PermModify permModify() { @@ -93,7 +93,7 @@ public class PermModify extends ActionDAO { } rv = q.permDAO.create(trans, d); - if(rv.isOK()) { + if (rv.isOK()) { PermDAO.Data pdd = new PermDAO.Data(); pdd.ns = p.ns; pdd.type = p.type; @@ -112,7 +112,7 @@ public class PermModify extends ActionDAO { } else { rv = Result.err(rr); } - if(rv==null) { + if (rv==null) { rv = Result.err(Status.ERR_General,"Never get to this code"); } @@ -126,7 +126,7 @@ public class PermModify extends ActionDAO { } public Result delete(AuthzTrans trans, Perm p) { - if(dryRun) { + if (dryRun) { return Result.ok(); } else { PermDAO.Data data = new PermDAO.Data(); 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 5353166c..cdbe92b4 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 @@ -49,12 +49,12 @@ public class RoleCreate extends ActionDAO { rdd.description = r.description; rdd.perms = r.perms; - if(dryRun) { + 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()) { + if (rv.isOK()) { trans.info().log("Created Role:",text,r.fullName()); } else { trans.error().log("Error Creating Role -",rv.details,":",r.fullName()); 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 1a663c99..67491b5b 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 @@ -42,7 +42,7 @@ public class RoleDelete extends ActionDAO { @Override public Result exec(AuthzTrans trans, Role r,String text) { - if(dryRun) { + if (dryRun) { trans.info().log("Would Delete Role:",text,r.fullName()); return Result.ok(); } else { @@ -50,7 +50,7 @@ public class RoleDelete extends ActionDAO { rdd.ns = r.ns; rdd.name = r.name; Result rv = q.roleDAO.delete(trans, rdd, true); // need to read for undelete - if(rv.isOK()) { + if (rv.isOK()) { trans.info().log("Deleted Role:",text,r.fullName()); } else { trans.error().log("Error Deleting Role -",rv.details,":",r.fullName()); 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 87e2e027..75937ef7 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 @@ -48,42 +48,42 @@ public class RoleModify extends ActionDAO { @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()) { + 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) { + if (rr.isOKhasData()) { + for (final Data d : rr.value) { modify.change(d); - if(d.ns.equals(r.ns) && d.name.equals(r.name)) { + 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)) { + for (String p : d.perms) { + if (!r.perms.contains(p)) { Result rpdd = PermDAO.Data.decode(trans, q, p); - if(rpdd.isOKhasData()) { + if (rpdd.isOKhasData()) { q.roleDAO.dao().addPerm(trans, d, rpdd.value); } } } - for(String p : r.perms) { - if(!d.perms.contains(p)) { + for (String p : r.perms) { + if (!d.perms.contains(p)) { Result rpdd = PermDAO.Data.decode(trans, q, p); - if(rpdd.isOKhasData()) { + if (rpdd.isOKhasData()) { q.roleDAO.dao().delPerm(trans, d, rpdd.value); } } } rv = Result.ok(d); } else { - for(String p : d.perms) { + for (String p : d.perms) { Perm perm = Perm.keys.get(p); - if(perm!=null) { - if(perm.roles.contains(r.encode())) { + if (perm!=null) { + if (perm.roles.contains(r.encode())) { modify.permModify().exec(trans, perm, new PermModify.Modify() { @Override public RoleModify roleModify() { @@ -100,11 +100,11 @@ public class RoleModify extends ActionDAO { } } Result> preexist = q.roleDAO.read(trans, d); - if(preexist.isOKhasData()) { + if (preexist.isOKhasData()) { Data rdd = preexist.value.get(0); - for(String p : d.perms) { + for (String p : d.perms) { Result perm = PermDAO.Data.decode(trans, q, p); - if(perm.isOKhasData()) { + if (perm.isOKhasData()) { q.roleDAO.dao().addPerm(trans,rdd, perm.value); } } @@ -112,7 +112,7 @@ public class RoleModify extends ActionDAO { } else { rv = q.roleDAO.create(trans, d); } - if(rv.isOK()) { + 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; @@ -127,7 +127,7 @@ public class RoleModify extends ActionDAO { } else { rv = Result.err(rr); } - if(rv==null) { + if (rv==null) { rv = Result.err(Status.ERR_General,"Never get to this code"); } return rv; @@ -140,7 +140,7 @@ public class RoleModify extends ActionDAO { } public Result delete(AuthzTrans trans, Role r) { - if(dryRun) { + if (dryRun) { return Result.ok(); } else { RoleDAO.Data data = new RoleDAO.Data(); 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 b6baea6c..4538c56b 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 @@ -44,7 +44,7 @@ public class URAdd extends ActionDAO { @Override public Result exec(AuthzTrans trans, UserRole ur, String text) { - if(dryRun) { + if (dryRun) { trans.info().log("Would Add:",text,ur.role(),ur.user(),"on",Chrono.dateOnlyStamp(ur.expires())); return Result.ok(ur.urdd()); } else { 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 d54b7805..cf519f6f 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 @@ -42,12 +42,12 @@ public class URDelete extends ActionDAO { @Override public Result exec(AuthzTrans trans, UserRole ur,String text) { - if(dryRun) { + 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()) { + 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()) ); 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 8590714f..36b476e1 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 @@ -59,11 +59,11 @@ public class URFutureApprove extends ActionDAO implemen @Override public Result exec(AuthzTrans trans, UserRole ur,String text) { - if(dryRun) { + if (dryRun) { return Result.ok(text); } else { Result rns = q.deriveNs(trans, ur.ns()); - if(rns.isOK()) { + if (rns.isOK()) { FutureDAO.Data data = new FutureDAO.Data(); data.id=null; // let Create function assign UUID @@ -78,7 +78,7 @@ public class URFutureApprove extends ActionDAO implemen return Result.err(e); } Result rfuture = f.createFuture(trans, data, Function.FOP_USER_ROLE, ur.user(), rns.value, FUTURE_OP.A); - if(rfuture.isOK()) { + if (rfuture.isOK()) { trans.info().log(rfuture.value, text, ur.user(), data.memo); } else { trans.error().log(rfuture.details, text); @@ -93,15 +93,15 @@ public class URFutureApprove extends ActionDAO implemen @Override public String key(UserRole ur) { String expire; - if(expires.before(start)) { + if (expires.before(start)) { expire = "' - EXPIRED "; } else { expire = "' - expiring "; } - if(Question.OWNER.equals(ur.rname())) { + 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())) { + } 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()); 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 fcba2364..75bbd813 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 @@ -52,16 +52,16 @@ public class URFutureApproveExec extends ActionDAO, OP_STATUS, Fu @Override public Result exec(AuthzTrans trans, List app, Future future) { - if(dryRun) { + 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) { + for (Approval a : app) { apprs.add(a.add); UserRole ur = UserRole.get(a.add.user, future.role); - if(ur!=null) { + if (ur!=null) { urs.add(ur.urdd()); } } @@ -76,9 +76,9 @@ public class URFutureApproveExec extends ActionDAO, OP_STATUS, Fu @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])) { + if (lur!=null) { + for (UserRole ur : lur) { + if (ur.role().equals(keys[1])) { return ur.urdd(); } } @@ -86,7 +86,7 @@ public class URFutureApproveExec extends ActionDAO, OP_STATUS, Fu return null; } }); - if(rv.isOK()) { + if (rv.isOK()) { switch(rv.value) { case D: trans.info().printf("Denied %s on %s", future.memo(),future.fdd.target); 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 a7d420e3..12460c97 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 @@ -45,22 +45,22 @@ public class URModify extends ActionDAO { @Override public Result exec(AuthzTrans trans, UserRole ur,Modify modify) { - if(dryRun) { + 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()) { + if (rr.notOKorIsEmpty()) { return Result.err(rr); } - for(Data d : rr.value) { + for (Data d : rr.value) { modify.change(d); - if(!(ur.expires().equals(d.expires))) { + if (!(ur.expires().equals(d.expires))) { ur.expires(d.expires); } - if(ur.user().equals(d.user) && ur.role().equals(d.role)){ + if (ur.user().equals(d.user) && ur.role().equals(d.role)){ Result rv = q.userRoleDAO.update(trans, d); - if(rv.isOK()) { + if (rv.isOK()) { trans.info().printf("Updated %s %s to %s", ur.user(), ur.role(), d.toString()); } else { trans.info().log(rv.errorString()); 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 856c89dc..6371ebb5 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 @@ -45,16 +45,16 @@ public class URPunt extends ActionPuntDAO { } public Result exec(AuthzTrans trans, UserRole ur, String text) { - if(dryRun) { + 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) { + if (read.isOK()) { + for (UserRoleDAO.Data data : read.value) { Date from = data.expires; data.expires = puntDate(from); - if(data.expires.compareTo(from)<=0) { + 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); 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 94c709b3..a4c4efbc 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 @@ -70,19 +70,19 @@ public class Approval implements CacheChange.Data { } public static String roleFromMemo(String memo) { - if(memo==null) { + if (memo==null) { return null; } int first = memo.indexOf('\''); - if(first>=0) { + if (first>=0) { int second = memo.indexOf('\'', ++first); - if(second>=0) { + if (second>=0) { String role = memo.substring(first, second); - if(memo.startsWith(RE_VALIDATE_ADMIN)) { + if (memo.startsWith(RE_VALIDATE_ADMIN)) { return role + ".admin"; - } else if(memo.startsWith(RE_VALIDATE_OWNER)) { + } else if (memo.startsWith(RE_VALIDATE_OWNER)) { return role + ".owner"; - } else if(memo.startsWith(RE_APPROVAL_IN_ROLE)) { + } else if (memo.startsWith(RE_APPROVAL_IN_ROLE)) { return role; } } @@ -106,14 +106,14 @@ public class Approval implements CacheChange.Data { try { List ln; - for(Row row : results.all()) { + for (Row row : results.all()) { ++count; try { Approval app = creator.create(row); String person = app.getApprover(); - if(person!=null) { + if (person!=null) { ln = byApprover.get(person); - if(ln==null) { + if (ln==null) { ln = new ArrayList<>(); byApprover.put(app.getApprover(), ln); } @@ -122,18 +122,18 @@ public class Approval implements CacheChange.Data { person = app.getUser(); - if(person!=null) { + if (person!=null) { ln = byUser.get(person); - if(ln==null) { + if (ln==null) { ln = new ArrayList<>(); byUser.put(app.getUser(), ln); } ln.add(app); } UUID ticket = app.getTicket(); - if(ticket!=null) { + if (ticket!=null) { ln = byTicket.get(ticket); - if(ln==null) { + if (ln==null) { ln = new ArrayList<>(); byTicket.put(app.getTicket(), ln); } @@ -152,25 +152,25 @@ public class Approval implements CacheChange.Data { @Override public void expunge() { List la = byApprover.get(getApprover()); - if(la!=null) { + if (la!=null) { la.remove(this); } la = byUser.get(getUser()); - if(la!=null) { + if (la!=null) { la.remove(this); } UUID ticket = this.add==null?null:this.add.ticket; - if(ticket!=null) { + if (ticket!=null) { la = byTicket.get(this.add.ticket); - if(la!=null) { + if (la!=null) { la.remove(this); } } } public void update(AuthzTrans trans, ApprovalDAO apprDAO, boolean dryRun) { - if(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); @@ -272,11 +272,11 @@ public class Approval implements CacheChange.Data { } public void delayDelete(AuthzTrans trans, ApprovalDAO ad, boolean dryRun, String text) { - if(dryRun) { + 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()) { + if (rv.isOK()) { trans.info().log(text,"- Deleted: Approval",getId(),"on ticket",getTicket(),"for",getApprover()); cache.delayedDelete(this); } else { @@ -295,8 +295,8 @@ public class Approval implements CacheChange.Data { } public static void delayDelete(AuthzTrans noAvg, ApprovalDAO apprDAO, boolean dryRun, List list, String text) { - if(list!=null) { - for(Approval a : list) { + if (list!=null) { + for (Approval a : list) { a.delayDelete(noAvg, apprDAO, dryRun,text); } } 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 1adc3d08..1407bdd0 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 @@ -44,10 +44,10 @@ public class CacheChange { } public final void resetLocalData() { - if(removed==null || removed.isEmpty()) { + if (removed==null || removed.isEmpty()) { return; } - for(T t : removed) { + for (T t : removed) { t.expunge(); } removed.clear(); 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 11580b80..a3eb8363 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 @@ -29,7 +29,7 @@ public abstract class Creator { public String query(String where) { StringBuilder sb = new StringBuilder(select()); - if(where!=null) { + if (where!=null) { sb.append(" WHERE "); sb.append(where); } 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 4013f193..2f6ed415 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 @@ -71,20 +71,20 @@ public class Cred { public Date last(final int ... types) { Date last = null; - for(Instance i : instances) { - if(types.length>0) { // filter by types, if requested + for (Instance i : instances) { + if (types.length>0) { // filter by types, if requested boolean quit = true; - for(int t : types) { - if(t==i.type) { + for (int t : types) { + if (t==i.type) { quit=false; break; } } - if(quit) { + if (quit) { continue; } } - if(last==null || i.expires.after(last)) { + if (last==null || i.expires.after(last)) { last = i.expires; } } @@ -94,7 +94,7 @@ public class Cred { public Set types() { Set types = new HashSet<>(); - for(Instance i : instances) { + for (Instance i : instances) { types.add(i.type); } return types; @@ -129,42 +129,42 @@ public class Cred { String id; tt = trans.start("Load Credentials", Env.SUB); try { - while(iter.hasNext()) { + while (iter.hasNext()) { ++count; row = iter.next(); id = row.getString(0); type = row.getInt(1); - if(types.length>0) { // filter by types, if requested + if (types.length>0) { // filter by types, if requested boolean quit = true; - for(int t : types) { - if(t==type) { + for (int t : types) { + if (t==type) { quit=false; break; } } - if(quit) { + if (quit) { continue; } } Cred cred = data.get(id); - if(cred==null) { + 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) { + if (lscd==null) { byNS.put(cred.ns, (lscd=new ArrayList<>())); } boolean found = false; - for(Cred c : lscd) { - if(c.id.equals(cred.id)) { + for (Cred c : lscd) { + if (c.id.equals(cred.id)) { found=true; break; } } - if(!found) { + if (!found) { lscd.add(cred); } } @@ -184,7 +184,7 @@ public class Cred { */ public static CredCount count(int numbuckets) { CredCount cc = new CredCount(numbuckets); - for(Cred c : data.values()) { + for (Cred c : data.values()) { for (Instance ci : c.instances) { cc.inc(ci.type,ci.written, ci.expires); } @@ -228,7 +228,7 @@ public class Cred { gc.set(GregorianCalendar.SECOND,0); gc.set(GregorianCalendar.MILLISECOND,0); gc.add(GregorianCalendar.MILLISECOND, -1); // last milli of month - for(int i=1;i { int count = 0; tt = trans.start("Process Futures", Env.SUB); try { - for(Row row : results.all()) { + for (Row row : results.all()) { ++count; Future f = creator.create(row); data.put(f.fdd.id,f); - if(f.role==null) { + if (f.role==null) { continue; } List lf = byRole.get(f.role); - if(lf==null) { + if (lf==null) { lf = new ArrayList<>(); byRole.put(f.role,lf); } @@ -148,16 +148,16 @@ public class Future implements CacheChange.Data, Comparable { public Result delayedDelete(AuthzTrans trans, FutureDAO fd, boolean dryRun, String text) { Result rv; - if(dryRun) { + 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()) { + 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) { + if (rv.status!=6) { trans.info().log(text,"- Failed to Delete Future", fdd.id); } } @@ -171,9 +171,9 @@ public class Future implements CacheChange.Data, Comparable { @Override public void expunge() { data.remove(fdd.id); - if(role!=null) { + if (role!=null) { List lf = byRole.get(role); - if(lf!=null) { + if (lf!=null) { lf.remove(this); } } @@ -181,7 +181,7 @@ public class Future implements CacheChange.Data, Comparable { @Override public int compareTo(Future o) { - if(o==null) { + if (o==null) { return -1; } return fdd.id.compareTo(o.fdd.id); 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 c0841590..cffb55a5 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 @@ -84,7 +84,7 @@ public class History { Row row; tt = trans.start("Load History", Env.SUB); try { - while(iter.hasNext()) { + while (iter.hasNext()) { ++count; row = iter.next(); loader.exec(creator.create(row)); @@ -151,9 +151,9 @@ public class History { ByteBuffer bb = row.getBytes(3); sb.setLength(0); - if(bb!=null && bb.hasRemaining()) { + if (bb!=null && bb.hasRemaining()) { sb.append("0x"); - while(bb.hasRemaining()) { + while (bb.hasRemaining()) { sb.append(String.format("%02x",bb.get())); } bb.flip(); 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 60b34af9..5fb3e5dc 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 @@ -58,7 +58,7 @@ public class InputIterator implements Iterable { @Override public String next() { - if(!hasNext()) { + if (!hasNext()) { throw new NoSuchElementException(); } return input; 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 afa68c08..8eecb656 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 @@ -64,7 +64,7 @@ public class MiscID { * @throws IllegalArgumentException */ public void set(String row []) throws BatchException { - if(row.length<4) {throw new BatchException("Row of MiscID_XRef is too short");} + if (row.length<4) {throw new BatchException("Row of MiscID_XRef is too short");} id = row[0]; sponsor = row[1]; created = row[2]; @@ -106,7 +106,7 @@ public class MiscID { try { tt = trans.start("Load Map", Env.SUB); try { - for( Row row : results.all()) { + for ( Row row : results.all()) { MiscID miscID = new MiscID(); miscID.set(row); data.put(miscID.id,miscID); @@ -133,7 +133,7 @@ public class MiscID { */ @Override public boolean equals(Object obj) { - if(obj!=null && obj instanceof MiscID) { + if (obj!=null && obj instanceof MiscID) { return id.equals(((MiscID)obj).id); } return false; @@ -156,12 +156,12 @@ public class MiscID { public StringBuilder updateStmt(MiscID source) { StringBuilder sb = null; - if(id.equals(source.id)) { + 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) { + if (sb!=null) { sb.append(" WHERE id='"); sb.append(id); sb.append('\''); @@ -170,8 +170,8 @@ public class MiscID { } private StringBuilder addField(StringBuilder sb, String name, String a, String b) { - if(!a.equals(b)) { - if(sb==null) { + if (!a.equals(b)) { + if (sb==null) { sb = new StringBuilder("UPDATE authz.miscid SET "); } else { sb.append(','); 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 e9321f5f..e15a6bc2 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 @@ -42,15 +42,15 @@ public class MonthData { public MonthData(String env) throws IOException { f = new File("Monthly"+env+".dat"); - if(f.exists()) { + if (f.exists()) { BufferedReader br = new BufferedReader(new FileReader(f)); try { String line; String[] split; - while((line=br.readLine())!=null) { - if(!line.startsWith("#")) { + while ((line=br.readLine())!=null) { + if (!line.startsWith("#")) { split = Split.split(',', line); - if(split.length==5) { + if (split.length==5) { add(Integer.parseInt(split[0]),split[1], Integer.parseInt(split[2]), Integer.parseInt(split[3]), @@ -67,7 +67,7 @@ public class MonthData { public void add(int yr_mon, String target, long total, long adds, long drops) { Set row = data.get(yr_mon); - if(row==null) { + if (row==null) { data.put(yr_mon, (row=new HashSet<>())); } row.add(new Row(target,total,adds,drops)); @@ -101,14 +101,14 @@ public class MonthData { } public void write() throws IOException { - if(f.exists()) { + 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()) { + 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); } } 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 a2833e55..5692d116 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 @@ -81,7 +81,7 @@ public class NS implements Comparable { Row row; tt = trans.start("Load Namespaces", Env.SUB); try { - while(iter.hasNext()) { + while (iter.hasNext()) { row = iter.next(); NS ns = creator.create(row); data.put(ns.name,ns); @@ -143,9 +143,9 @@ public class NS implements Comparable { } } 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) { + 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); } } 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 abfd1ca4..b178c377 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 @@ -61,8 +61,8 @@ public class Notification { } public static TYPE get(int idx) { - for(TYPE nt : TYPE.values()) { - if(idx==nt.type) { + for (TYPE nt : TYPE.values()) { + if (idx==nt.type) { return nt; } } @@ -107,12 +107,12 @@ public class Notification { tt = trans.start("Process Notify", Env.SUB); try { - for(Row row : results.all()) { + for (Row row : results.all()) { ++count; try { Notification not = creator.create(row); List ln = data.get(not.user); - if(ln==null) { + if (ln==null) { ln = new ArrayList<>(); data.put(not.user, ln); } @@ -129,9 +129,9 @@ public class Notification { 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)) { + if (ln!=null) { + for (Notification n : ln) { + if (type.equals(n.type)) { return n; } } @@ -148,7 +148,7 @@ public class Notification { public Notification create(Row row) { int idx =row.getInt(1); TYPE type = TYPE.get(idx); - if(type==null) { + if (type==null) { return null; } return new Notification(row.getString(0), type, row.getTimestamp(2), row.getInt(3)); @@ -166,11 +166,11 @@ public class Notification { } public int checksum() { - if(msg==null) { + if (msg==null) { current=0; - } else if(current==0) { - for(String l : msg.lines) { - for(byte b : l.getBytes()) { + } else if (current==0) { + for (String l : msg.lines) { + for (byte b : l.getBytes()) { current+=b; } } @@ -180,7 +180,7 @@ public class Notification { public boolean update(AuthzTrans trans, Session session, boolean dryRun) { checksum(); - if(last==null || current==0 || current!=checksum) { + if (last==null || current==0 || current!=checksum) { last = now; current = checksum(); String update = "UPDATE authz.notify SET " + @@ -192,7 +192,7 @@ public class Notification { "' AND type=" + type.idx() + ";"; - if(dryRun) { + if (dryRun) { trans.info().log("Would",update); } else { session.execute(update); 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 d980bcc2..a3354f38 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 @@ -76,20 +76,20 @@ public class NsAttrib { tt = trans.start("Process NsAttributes", Env.SUB); try { - for(Row row : results.all()) { + for (Row row : results.all()) { ++count; NsAttrib ur = creator.create(row); data.add(ur); List lna = byKey.get(ur.key); - if(lna==null) { + if (lna==null) { lna = new ArrayList<>(); byKey.put(ur.key, lna); } lna.add(ur); lna = byNS.get(ur.ns); - if(lna==null) { + if (lna==null) { lna = new ArrayList<>(); byNS.put(ur.ns, lna); } 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 799ce4df..ce22724b 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 @@ -47,21 +47,21 @@ public class Perm implements Comparable { public final Set roles; public String encode() { - if(encode == null) { + if (encode == null) { encode = ns + '|' + type + '|' + instance + '|' + action; } return encode; } public String fullType() { - if(fullType==null) { + if (fullType==null) { fullType = ns + '.' + type; } return fullType; } public String fullPerm() { - if(fullPerm==null) { + if (fullPerm==null) { fullPerm = ns + '.' + type + '|' + instance + '|' + action; } return fullPerm; @@ -104,7 +104,7 @@ public class Perm implements Comparable { Row row; tt = trans.start("Load Perms", Env.SUB); try { - while(iter.hasNext()) { + while (iter.hasNext()) { row = iter.next(); Perm pk = new Perm( row.getString(0),row.getString(1),row.getString(2), @@ -164,7 +164,7 @@ public class Perm implements Comparable { } public static void executeRemove() { - for(Perm p : deletePerms) { + for (Perm p : deletePerms) { keys.remove(p.encode); data.remove(p); } 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 46d3cced..04a5dceb 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 @@ -64,14 +64,14 @@ public class Role implements Comparable { } public String encode() { - if(encode==null) { + if (encode==null) { encode = ns + '|' + name; } return encode; } public String fullName() { - if(full==null) { + if (full==null) { full = ns + '.' + name; } return full; @@ -102,7 +102,7 @@ public class Role implements Comparable { Row row; tt = trans.start("Load Roles", Env.SUB); try { - while(iter.hasNext()) { + 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); @@ -165,7 +165,7 @@ public class Role implements Comparable { } public static void executeRemove() { - for(Role p : deleteRoles) { + for (Role p : deleteRoles) { keys.remove(p.encode); data.remove(p); } 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 fab9233d..762f6c66 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 @@ -143,21 +143,21 @@ public class UserRole implements Cloneable, CacheChange.Data { private static void iterateResults(Creator creator, Iterator iter ) { Row row; - while(iter.hasNext()) { + 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) { + if (lur==null) { lur = new ArrayList<>(); byUser.put(ur.urdd.user, lur); } lur.add(ur); lur = byRole.get(ur.urdd.role); - if(lur==null) { + if (lur==null) { lur = new ArrayList<>(); byRole.put(ur.urdd.role, lur); } @@ -178,12 +178,12 @@ public class UserRole implements Cloneable, CacheChange.Data { data.remove(this); List lur = byUser.get(urdd.user); - if(lur!=null) { + if (lur!=null) { lur.remove(this); } lur = byRole.get(urdd.role); - if(lur!=null) { + if (lur!=null) { lur.remove(this); } } @@ -245,10 +245,10 @@ public class UserRole implements Cloneable, CacheChange.Data { public static UserRole get(String u, String r) { List lur = byUser.get(u); - if(lur!=null) { - for(UserRole ur : lur) { + if (lur!=null) { + for (UserRole ur : lur) { - if(ur.urdd.role.equals(r)) { + if (ur.urdd.role.equals(r)) { return ur; } } @@ -260,7 +260,7 @@ public class UserRole implements Cloneable, CacheChange.Data { // 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) { + 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); @@ -289,7 +289,7 @@ public class UserRole implements Cloneable, CacheChange.Data { } public static void actuateDeletionNow(AuthzTrans trans, URDelete directDel) { - for(UserRole ur : cache.getRemoved()) { + for (UserRole ur : cache.getRemoved()) { directDel.exec(trans, ur, "Actuating UserRole Deletion"); } cache.getRemoved().clear(); 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 4555857a..f4a0f37c 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 @@ -150,7 +150,7 @@ public class JavaxMailer implements Mailer { try{ addressArray[count] = new InternetAddress(addr); count++; - }catch(Exception e){ + } catch (Exception e){ throw new OrganizationException("Failed to parse the email address "+ addr +": "+e.getMessage()); } } 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 886bd56a..d34f9248 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 @@ -76,20 +76,20 @@ 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)) { + 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)) { + if (ur.expires().before(earliestUR)) { earliestUR = ur.expires(); } } } - if(expiring.size()>0) { + if (expiring.size()>0) { Collections.sort(expiring,Collections.reverseOrder()); - for(String s : expiring) { + for (String s : expiring) { System.err.print('\t'); System.err.println(s); } @@ -101,30 +101,30 @@ public class ExpiringNext extends Batch { expiring.clear(); trans.info().log("Checking for Expired Credentials"); - for( Cred creds : Cred.data.values()) { + 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)) { + 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)) { + 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)) { + if (lastInstance.expires.before(earliestCred)) { earliestCred = lastInstance.expires; } } } - if(expiring.size()>0) { + if (expiring.size()>0) { Collections.sort(expiring,Collections.reverseOrder()); - for(String s : expiring) { + for (String s : expiring) { System.err.print('\t'); System.err.println(s); } 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 868811a3..e9f0e726 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 @@ -117,7 +117,7 @@ public class Expiring extends Batch { } File data_dir = new File(env.getProperty("aaf_data_dir")); - if(!data_dir.exists() || !data_dir.canWrite() || !data_dir.canRead()) { + 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( @@ -137,7 +137,7 @@ public class Expiring extends Batch { 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) { + if (address==null) { throw new APIException("ALERT_TO_ADDRESS property is required"); } email.addTo(address); @@ -169,30 +169,30 @@ public class Expiring extends Batch { // Clean out Approvals UserRoles are fixed up. String memo; - for(List la : Approval.byUser.values()) { - for(Approval a : la ) { + for (List la : Approval.byUser.values()) { + for (Approval a : la ) { memo = a.getMemo(); - if(memo!=null && (memo.contains("Re-Approval") || memo.contains("Re-Validate"))) { + if (memo!=null && (memo.contains("Re-Approval") || memo.contains("Re-Validate"))) { String role = a.getRole(); - if(role!=null) { + 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 + 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)) { + 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)) { + if (tkt !=null && Future.data.containsKey(tkt)) { f = Future.data.get(a.getTicket()); } } - if(f!=null) { + if (f!=null) { f.delayedDelete(noAvg, futureDAO, dryRun, "Approvals removed"); } } @@ -212,12 +212,12 @@ public class Expiring extends Batch { 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")) { + 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) { + if (la!=null) { Result ruf = urFutureApproveExec.exec(noAvg,la,f); - if(ruf.isOK()) { + if (ruf.isOK()) { switch(ruf.value) { case P: break; @@ -246,11 +246,11 @@ public class Expiring extends Batch { String expiredBeforeNow = "Expired before " + tooLate; String expiredAfterFuture = "Expired after " + future; try { - for(Future f : Future.data.values()) { - if(f.expires().before(tooLate)) { + 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)) { + } else if (f.expires().after(future)) { f.delayedDelete(noAvg,futureDAO,dryRun, expiredAfterFuture); Approval.delayDelete(noAvg,apprDAO,dryRun, Approval.byTicket.get(f.id()), expiredAfterFuture); } @@ -268,19 +268,19 @@ public class Expiring extends Batch { 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) { + for (List lapp : Approval.byTicket.values()) { + for (Approval app : lapp) { Future f; - if(app.getTicket()==null) { + if (app.getTicket()==null) { f = null; } else { f = Future.data.get(app.getTicket()); - if(Future.pendingDelete(f)) { + if (Future.pendingDelete(f)) { f=null; } } String msg; - if(f!=null && app.getRole()!=null && Role.byName.get(app.getRole())==null) { + 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; @@ -288,7 +288,7 @@ public class Expiring extends Batch { switch(app.getStatus()) { case "pending": - if(f==null) { + if (f==null) { app.delayDelete(noAvg,apprDAO, isDryRun(), "ticketDeleted"); continue; } @@ -296,19 +296,19 @@ public class Expiring extends Batch { case "owner": boolean anOwner=false; String approle = app.getRole(); - if(approle!=null) { + if (approle!=null) { Role role = Role.byName.get(approle); - if(role==null) { + 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)) { + if (Role.byName.containsKey(owner)) { List lur = UserRole.getByRole().get(owner); - if(lur != null) { - for(UserRole ur : lur) { - if(ur.user().equals(app.getApprover())) { + if (lur != null) { + for (UserRole ur : lur) { + if (ur.user().equals(app.getApprover())) { anOwner = true; break; } @@ -316,7 +316,7 @@ public class Expiring extends Batch { } } } - if(!anOwner) { + if (!anOwner) { app.delayDelete(noAvg, apprDAO, dryRun, "No longer Owner"); } @@ -325,14 +325,14 @@ public class Expiring extends Batch { case "supervisor": try { Identity identity = org.getIdentity(noAvg, app.getUser()); - if(identity==null) { - if(f!=null) { + 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) { + 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); } @@ -360,9 +360,9 @@ public class Expiring extends Batch { // 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())) { + 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); @@ -370,16 +370,16 @@ public class Expiring extends Batch { ++delayedURDeletes; } } else { - if(NS.data.get(ur.ns())==null) { + 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())) { + } 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 + } 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. @@ -387,16 +387,16 @@ public class Expiring extends Batch { ++deleted; } //trans.logAuditTrail(trans.info()); - } else if(ur.expires().before(future) && ur.expires().after(now)) { + } 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) { + 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) { + 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; } @@ -404,7 +404,7 @@ public class Expiring extends Batch { } } } - if(needNew) { + if (needNew) { urFutureApprove.exec(noAvg, ur,""); } } @@ -418,10 +418,10 @@ public class Expiring extends Batch { } // Actualize UR Deletes, or send Email - if(UserRole.sizeForDeletion()>0) { + if (UserRole.sizeForDeletion()>0) { count+=UserRole.sizeForDeletion(); double onePercent = 0.01; - if(((double)UserRole.sizeForDeletion())/UserRole.getData().size() > onePercent) { + 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", @@ -448,7 +448,7 @@ public class Expiring extends Batch { } } } - if(count>0) { + if (count>0) { String str = String.format("%d UserRoles modified or deleted", count); cacheTouch.exec(trans, "user_role", str); } @@ -460,20 +460,20 @@ public class Expiring extends Batch { try { CredDAO.Data crd = new CredDAO.Data(); Date last = null; - for( Cred creds : Cred.data.values()) { + for ( Cred creds : Cred.data.values()) { crd.id = creds.id; - for(int type : creds.types()) { + for (int type : creds.types()) { crd.type = type; - for( Instance inst : creds.instances) { - if(inst.expires.before(tooLate)) { + 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)) { + } else if (last==null || inst.expires.after(last)) { last = inst.expires; } } - if(last!=null) { - if(last.before(future)) { + if (last!=null) { + if (last.before(future)) { crd.expires = last; crPrint.exec(noAvg, crd,""); ++count; @@ -483,7 +483,7 @@ public class Expiring extends Batch { } } finally { String str = String.format("Found %d current creds expiring before %s", count, Chrono.dateOnlyStamp(future)); - if(count>0) { + if (count>0) { cacheTouch.exec(trans, "cred", str); } } @@ -493,8 +493,8 @@ public class Expiring extends Batch { @Override protected void _close(AuthzTrans trans) { aspr.info("End " + this.getClass().getSimpleName() + " processing" ); - for(Action action : new Action[] {crDelete}) { - if(action instanceof ActionDAO) { + for (Action action : new Action[] {crDelete}) { + if (action instanceof ActionDAO) { ((ActionDAO)action).close(trans); } } 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 f9797c86..cab612eb 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 @@ -70,7 +70,7 @@ public class ExpiringP2 extends Batch { 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()) { + 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"))); @@ -92,10 +92,10 @@ public class ExpiringP2 extends Batch { Map tally = new HashMap<>(); int count=0; try { - while((line=urDeleteF.readLine())!=null) { - if(line.startsWith("#")) { + while ((line=urDeleteF.readLine())!=null) { + if (line.startsWith("#")) { Count cnt = tally.get(line); - if(cnt==null) { + if (cnt==null) { tally.put(line, cnt=new Count()); } cnt.inc(); @@ -114,11 +114,11 @@ public class ExpiringP2 extends Batch { } System.out.println("Tallies of UserRole Deletions"); - for(Entry es : tally.entrySet()) { + for (Entry es : tally.entrySet()) { System.out.printf(" %6d\t%20s\n", es.getValue().cnt,es.getKey()); } } finally { - if(cacheTouch!=null && count>0) { + if (cacheTouch!=null && count>0) { cacheTouch.exec(trans, "user_roles", "Removing UserRoles"); } } @@ -142,8 +142,8 @@ public class ExpiringP2 extends Batch { @Override protected void _close(AuthzTrans trans) { aspr.info("End " + this.getClass().getSimpleName() + " processing" ); - for(Action action : new Action[] {urDelete,cacheTouch}) { - if(action instanceof ActionDAO) { + for (Action action : new Action[] {urDelete,cacheTouch}) { + if (action instanceof ActionDAO) { ((ActionDAO)action).close(trans); } } 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 8b12399d..50c6dc21 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 @@ -69,7 +69,7 @@ public class NotifyApprovals extends Batch { session = historyDAO.getSession(trans); apprDAO = new ApprovalDAO(trans, historyDAO); futureDAO = new FutureDAO(trans, historyDAO); - if(isDryRun()) { + if (isDryRun()) { email = new EmailPrint(); maxEmails=3; } else { @@ -105,10 +105,10 @@ public class NotifyApprovals extends Batch { int emailCount = 0; List pending = new ArrayList<>(); boolean isOwner,isSupervisor; - for(Entry> es : Approval.byApprover.entrySet()) { + for (Entry> es : Approval.byApprover.entrySet()) { isOwner = isSupervisor = false; String approver = es.getKey(); - if(approver.indexOf('@')<0) { + if (approver.indexOf('@')<0) { approver += org.getRealm(); } Date latestNotify=null, soonestExpire=null; @@ -116,28 +116,28 @@ public class NotifyApprovals extends Batch { GregorianCalendar soonest=new GregorianCalendar(); pending.clear(); - for(Approval app : es.getValue()) { + 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. + if (f==null) { // only Ticketed Approvals are valid.. the others are records. // Approvals without Tickets are no longer valid. - if("pending".equals(app.getStatus())) { + 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()))) { + 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) { + if ("pending".equals(app.getStatus())) { + if (!isOwner) { isOwner = "owner".equals(app.getType()); } - if(!isSupervisor) { + 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()))) { + 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); @@ -145,29 +145,29 @@ public class NotifyApprovals extends Batch { } } - if(!pending.isEmpty()) { + if (!pending.isEmpty()) { boolean go = false; - if(latestNotify==null) { // never notified... make it so + if (latestNotify==null) { // never notified... make it so go=true; } else { - if(!today.equals(Chrono.dateOnlyStamp(latest))) { // already notified today + 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. + if (days<7) { // If Expirations get within a Week (or expired), notify everytime. go = true; } } } - if(go) { - if(maxEmails>emailCount++) { + if (go) { + if (maxEmails>emailCount++) { try { Organization org = OrganizationFactory.obtain(env, approver); Identity user = org.getIdentity(noAvg, approver); - if(user==null) { + if (user==null) { ps.printf("Invalid Identity: %s\n", approver); } else { email.clear(); @@ -175,7 +175,7 @@ public class NotifyApprovals extends Batch { email.addTo(user.email()); msg.line(LINE); msg.line("Why are you receiving this Notification?\n"); - if(isSupervisor) { + 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 " @@ -183,7 +183,7 @@ public class NotifyApprovals extends Batch { 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) { + 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) ":""); @@ -208,9 +208,9 @@ public class NotifyApprovals extends Batch { email.msg(msg); email.exec(noAvg, org,""); - if(!isDryRun()) { + if (!isDryRun()) { email.log(ps,"NotifyApprovals"); - for(Approval app : pending) { + for (Approval app : pending) { app.setLastNotified(now); app.update(noAvg, apprDAO, dryRun); } 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 ab386c56..b4631f66 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 @@ -87,10 +87,10 @@ public class NotifyCredExpiring extends Batch { noAvg = env.newTransNoAvg(); noAvg.setUser(new BatchPrincipal("batch:NotifyCredExpiring")); - if((supportEmailAddr = env.getProperty("mailFromUserId"))==null) { + if ((supportEmailAddr = env.getProperty("mailFromUserId"))==null) { throw new APIException("mailFromUserId property must be set"); } - if(isDryRun()) { + if (isDryRun()) { email = new EmailPrint(); maxEmails=3; maxEmails = Integer.parseInt(trans.getProperty("MAX_EMAILS","3")); @@ -137,17 +137,17 @@ public class NotifyCredExpiring extends Batch { ownerCreds.put(UNKNOWN_ID,noOwner); // Get a list of ONLY the ones needing email by Owner - for(Entry> es : Cred.byNS.entrySet()) { + for (Entry> es : Cred.byNS.entrySet()) { lastCred.clear(); - for(Cred c : es.getValue()) { + for (Cred c : es.getValue()) { last = c.last(CredDAO.BASIC_AUTH,CredDAO.BASIC_AUTH_SHA256); - if(last!=null && last.after(tooLate) && last.before(early)) { + if (last!=null && last.after(tooLate) && last.before(early)) { List ownerURList = UserRole.getByRole().get(es.getKey()+".owner"); - if(ownerURList!=null) { - for(UserRole ur:ownerURList) { + if (ownerURList!=null) { + for (UserRole ur:ownerURList) { String owner = ur.user(); List llc = ownerCreds.get(owner); - if(llc==null) { + if (llc==null) { ownerCreds.put(owner, (llc=new ArrayList<>())); } llc.add(new LastCred(c,last)); @@ -164,39 +164,39 @@ public class NotifyCredExpiring extends Batch { Message msg = new Message(); Notification ownNotf; StringBuilder logMessage = new StringBuilder(); - for(Entry> es : ownerCreds.entrySet()) { + 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) { + if (!UNKNOWN_ID.equals(owner) && user==null) { ps.printf("Invalid Identity: %s\n", owner); } else { logMessage.setLength(0); - if(maxEmails>emailCount) { + 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) { + 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()) { + 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) && + for (LastCred lc : es.getValue()) { + if (lc.last.after(must) && lc.last.before(early) && (ownNotf.last==null || ownNotf.last.before(withinLastWeek))) { - if(!bEarly && header) { + 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); @@ -204,19 +204,19 @@ public class NotifyCredExpiring extends Batch { header = false; } bEarly = true; - } else if(lc.last.after(critical) && lc.last.before(must) && + } else if (lc.last.after(critical) && lc.last.before(must) && (ownNotf.last==null || ownNotf.last.before(withinLastWeek))) { - if(!bNormal) { + if (!bNormal) { boolean last2wks = lc.last.before(within2Weeks); - if(last2wks) { + if (last2wks) { try { Identity supvsr = user.responsibleTo(); email.addCC(supvsr.email()); - } catch(OrganizationException e) { + } catch (OrganizationException e) { trans.error().log(e, "Supervisor cannot be looked up"); } } - if(header) { + 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); @@ -225,8 +225,8 @@ public class NotifyCredExpiring extends Batch { header = false; } bNormal=true; - } else if(lc.last.after(tooLate) && lc.last.before(critical)) { // Email Every Day, with Supervisor - if(!bCritical && header) { + } 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); @@ -235,22 +235,22 @@ public class NotifyCredExpiring extends Batch { } bCritical = true; try { - if(user!=null) { + if (user!=null) { Identity supvsr = user.responsibleTo(); - if(supvsr!=null) { + if (supvsr!=null) { email.addCC(supvsr.email()); supvsr = supvsr.responsibleTo(); - if(supvsr!=null) { + if (supvsr!=null) { email.addCC(supvsr.email()); } } } - } catch(OrganizationException e) { + } catch (OrganizationException e) { trans.error().log(e, "Supervisor cannot be looked up"); } } - if(bEarly || bNormal || bCritical) { - if(logMessage.length()==0) { + if (bEarly || bNormal || bCritical) { + if (logMessage.length()==0) { logMessage.append("NotifyCredExpiring"); } logMessage.append("\n\t"); @@ -261,7 +261,7 @@ public class NotifyCredExpiring extends Batch { } } - if(bEarly || bNormal || bCritical) { + 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 " @@ -271,9 +271,9 @@ public class NotifyCredExpiring extends Batch { msg.line(" %s/ns\n\n",env.getProperty(GUI_URL)); email.msg(msg); Result rv = email.exec(trans, org,""); - if(rv.isOK()) { + if (rv.isOK()) { ++emailCount; - if(!isDryRun()) { + if (!isDryRun()) { ownNotf.update(noAvg, session, false); // SET LastNotification } 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 c0a9a3cd..07fd65f0 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 @@ -69,7 +69,7 @@ public class JU_InputIterator { @After public void cleanUp() { - if(f.exists()) { + if (f.exists()) { f.delete(); } } 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 cef81ded..97b6c56b 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 @@ -94,10 +94,10 @@ public class JU_MonthData { @After public void cleanUp() { File g = new File("Monthlyenv.dat.bak"); - if(f.exists()) { + if (f.exists()) { f.delete(); } - if(g.exists()) { + if (g.exists()) { g.delete(); } } 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 f24c7c9f..d0e4eaab 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 @@ -128,18 +128,18 @@ public abstract class AbsCassDAO { psinfos.add(this); cql = theCQL.trim().toUpperCase(); - if(cql.startsWith("INSERT")) { + if (cql.startsWith("INSERT")) { crud = CRUD.create; - } else if(cql.startsWith("UPDATE")) { + } else if (cql.startsWith("UPDATE")) { crud = CRUD.update; - } else if(cql.startsWith("DELETE")) { + } else if (cql.startsWith("DELETE")) { crud = CRUD.delete; } else { crud = CRUD.read; } int idx = 0, count=0; - while((idx=cql.indexOf('?',idx))>=0) { + while ((idx=cql.indexOf('?',idx))>=0) { ++idx; ++count; } @@ -155,7 +155,7 @@ public abstract class AbsCassDAO { 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) { + if (ps==null) { TimeTaken tt = trans.start("Preparing PSInfo " + crud.toString().toUpperCase() + " on " + name,Env.SUB); try { ps = getSession(trans).prepare(cql); @@ -287,7 +287,7 @@ public abstract class AbsCassDAO { rs = getSession(trans).execute(key==null?ps(trans):ps(trans).bind(key)); /// TEST CODE for Exception // boolean force = true; -// if(force) { +// 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")); @@ -334,19 +334,19 @@ public abstract class AbsCassDAO { @SuppressWarnings("unchecked") protected final Result> extract(Loader loader, ResultSet rs, List indata, Accept accept) { List rows = rs.all(); - if(rows.isEmpty()) { + 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) { + for (Row row : rows) { try { d = loader.load(dataClass.newInstance(),row); - if(accept.ok(d)) { + if (accept.ok(d)) { data.add(d); } - } catch(Exception e) { + } catch (Exception e) { return Result.err(e); } } @@ -372,8 +372,8 @@ public abstract class AbsCassDAO { public static final void primePSIs(TransStore trans) throws APIException, IOException { - for(AbsCassDAO.PSInfo psi : psinfos) { - if(psi.ps==null) { + for (AbsCassDAO.PSInfo psi : psinfos) { + if (psi.ps==null) { psi.ps(trans); } } @@ -382,28 +382,28 @@ public abstract class AbsCassDAO { 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 +// if (sessionSlot!=null) { // try to get from Trans // Session sess = trans.get(sessionSlot, null); -// if(sess!=null) { +// if (sess!=null) { // return sess; // } // } // If there's an owning DAO, use it's session - if(owningDAO!=null) { + if (owningDAO!=null) { return owningDAO.getSession(trans); } // OK, nothing else works... get our own. - if(session==null || resetTrigger) { + 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) { + for (ResetRequest r : resetDeque) { + if (r.session == session) { + if (r.timestamp>nextAvailableReset) { reset=true; nextAvailableReset = System.currentTimeMillis() + 60000; tempCluster = cluster; @@ -415,22 +415,22 @@ public abstract class AbsCassDAO { } } - if(reset || session == null) { + 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) { + if (reset) { + for (AbsCassDAO.PSInfo psi : psinfos) { psi.reset(); } } - if(reset || cluster==null) { + if (reset || cluster==null) { cluster = CassAccess.cluster(trans, keyspace); trans.warn().log(NEW_CASSANDRA_CLUSTER_OBJECT_CREATED); } - if(reset || session==null) { + if (reset || session==null) { session = cluster.connect(keyspace); trans.warn().log(NEW_CASSANDRA_SESSION_CREATED); } @@ -445,10 +445,10 @@ public abstract class AbsCassDAO { try { resetDeque.clear(); // Not clearing Session/Cluster appears to kill off FileHandles - if(tempSession!=null && !tempSession.isClosed()) { + if (tempSession!=null && !tempSession.isClosed()) { tempSession.close(); } - if(tempCluster!=null && !tempCluster.isClosed()) { + if (tempCluster!=null && !tempCluster.isClosed()) { tempCluster.close(); } } finally { @@ -460,11 +460,11 @@ public abstract class AbsCassDAO { } public final boolean reportPerhapsReset(TransStore trans, Exception e) { - if(owningDAO!=null) { + if (owningDAO!=null) { return owningDAO.reportPerhapsReset(trans, e); } else { boolean rv = false; - if(CassAccess.isResetException(e)) { + 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; @@ -475,8 +475,8 @@ public abstract class AbsCassDAO { } public void close(TransStore trans) { - if(owningDAO==null) { - if(session!=null) { + if (owningDAO==null) { + if (session!=null) { TimeTaken tt = trans.start("Cassandra Session Close", Env.SUB); try { session.close(); 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 3f4bbb20..1bda405c 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 @@ -56,7 +56,7 @@ public class Cached extends Cache extends Cache extends Cache map = ((Map)cache[cacheIdx]); -// if(map.remove(key)!=null) // Not seeming to remove all the time - if(map!=null)map.clear(); +// 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)); + 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) { + if (map!=null) { map.clear(); } return Result.ok(); @@ -118,14 +118,14 @@ public class Cached extends Cache)cached.data; rld = Result.ok(ld); } else { rld = getter.get(); - if(rld.isOK()) { // only store valid lists + 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){ +// } else if (rld.status == Result.ERR_Backend){ // map.remove(key); } } @@ -138,8 +138,8 @@ public class Cached extends Cache ... dao) { - for(CachedDAO d : dao) { - for(int i=0;i d : dao) { + for (int i=0;i extends Cache void startRefresh(AuthzEnv env, CIDAO cidao) { - if(infoTimer==null) { + 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 @@ -156,7 +156,7 @@ public class Cached extends Cache extends Cache rv = cidao.check(trans); - if(rv.status!=Result.OK) { + if (rv.status!=Result.OK) { env.error().log("Error in CacheInfo Refresh",rv.details); } - if(env.debug().isLoggable()) { + 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 9375502c..cf410d0b 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 @@ -52,7 +52,7 @@ public class CachedDAO,DATA extend this.dao = dao; //read_str = "Cached READ for " + dao.table(); // dirty_str = "Cache DIRTY on " + dao.table(); - if(dao instanceof CassDAOImpl) { + if (dao instanceof CassDAOImpl) { ((CassDAOImpl)dao).cache = this; } } @@ -80,14 +80,14 @@ public class CachedDAO,DATA extend public static String keyFromObjs(Object ... objs) { String key; - if(objs.length==1 && objs[0] instanceof String) { + 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) { + for (Object o : objs) { + if (o!=null) { + if (first) { first =false; } else { sb.append('|'); @@ -102,7 +102,7 @@ public class CachedDAO,DATA extend public Result create(TRANS trans, DATA data) { Result d = dao.create(trans,data); - if(d.status==Status.OK) { + if (d.status==Status.OK) { add(d.value); } else { trans.error().log(d.errorString()); @@ -134,7 +134,7 @@ public class CachedDAO,DATA extend @Override public final Result> get() { return call(); -// if(result.isOKhasData()) { // Note, given above logic, could exist, but stale +// if (result.isOKhasData()) { // Note, given above logic, could exist, but stale // return result.value; // } else { // return null; @@ -146,11 +146,11 @@ public class CachedDAO,DATA extend 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) { +// if (ld!=null) { // return Result.ok(ld);//.emptyList(ld.isEmpty()); // } // // Result Result if exists -// if(getter.result==null) { +// if (getter.result==null) { // return Result.err(Status.ERR_NotFound, "No Cache or Lookup found on [%s]",dao.table()); // } // return getter.result; @@ -160,11 +160,11 @@ public class CachedDAO,DATA extend 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) { +// if (ld!=null) { // return Result.ok(ld);//.emptyList(ld.isEmpty()); // } // // Result Result if exists -// if(getter.result==null) { +// if (getter.result==null) { // return Result.err(Status.ERR_NotFound, "No Cache or Lookup found on [%s]",dao.table()); // } // return getter.result; @@ -176,7 +176,7 @@ public class CachedDAO,DATA extend } public Result update(TRANS trans, DATA data) { Result d = dao.update(trans, data); - if(d.status==Status.OK) { + if (d.status==Status.OK) { add(data); } else { trans.error().log(d.errorString()); @@ -185,14 +185,14 @@ public class CachedDAO,DATA extend } public Result delete(TRANS trans, DATA data, boolean reread) { - if(reread) { // If reread, get from Cache, if possible, not DB exclusively + if (reread) { // If reread, get from Cache, if possible, not DB exclusively Result> rd = read(trans,data); - if(rd.notOK()) { + if (rd.notOK()) { return Result.err(rd); // } else { // trans.error().log(rd.errorString()); } - if(rd.isEmpty()) { + if (rd.isEmpty()) { data.invalidate(this); return Result.err(Status.ERR_NotFound,"Not Found"); } @@ -205,7 +205,7 @@ public class CachedDAO,DATA extend @Override public void close(TRANS trans) { - if(dao!=null) { + if (dao!=null) { dao.close(trans); } } @@ -221,7 +221,7 @@ public class CachedDAO,DATA extend } public void invalidate(TRANS trans, DATA data) { - if(info.touch(trans, dao.table(),data.invalidate(this)).notOK()) { + if (info.touch(trans, dao.table(),data.invalidate(this)).notOK()) { 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 9b168a83..b8062fcd 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 @@ -64,9 +64,9 @@ public class CassAccess { // @SuppressWarnings("deprecation") public static synchronized Cluster cluster(Env env, String prefix) throws APIException, IOException { - if(cb == null) { + if (cb == null) { String pre; - if(prefix==null) { + if (prefix==null) { pre=""; } else { env.info().log("Cassandra Connection for ",prefix); @@ -74,19 +74,19 @@ public class CassAccess { } cb = Cluster.builder(); String str = env.getProperty(pre+CASSANDRA_CLUSTERS_PORT,env.getProperty(CASSANDRA_CLUSTERS_PORT,"9042")); - if(str!=null) { + 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) { + 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) { + 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) { + if (env instanceof AuthzEnv) { cb.withCredentials(str,((AuthzEnv)env).decrypt(epass,true)); } else { cb.withCredentials(str, env.decryptor().decrypt(epass)); @@ -94,9 +94,9 @@ public class CassAccess { } str = env.getProperty(pre+CASSANDRA_RESET_EXCEPTIONS,env.getProperty(CASSANDRA_RESET_EXCEPTIONS,null)); - if(str!=null) { + if (str!=null) { env.init().log("Cass ResetExceptions = ",str ); - for(String ex : Split.split(',', str)) { + for (String ex : Split.split(',', str)) { resetExceptions.add(new Resettable(env,ex)); } } @@ -105,7 +105,7 @@ public class CassAccess { 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) { + if (lat == null || lon == null) { throw new APIException(Config.CADI_LATITUDE + " and/or " + Config.CADI_LONGITUDE + " are not set"); } @@ -118,23 +118,23 @@ public class CassAccess { String bestDC = null; int numInBestDC = 1; double mlat, mlon,temp,distance = Double.MAX_VALUE; - for(int i=0;i0) { + if (minfo.length>0) { cpoints[i]=minfo[0]; } - if(minfo.length>3) { - if(minfo[1].equals(bestDC)) { + 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) { + if ((temp=GreatCircle.calc(lat, lon, mlat, mlon)) < distance) { distance = temp; - if(bestDC==null || !bestDC.equals(minfo[1])) { + if (bestDC==null || !bestDC.equals(minfo[1])) { bestDC = minfo[1]; numInBestDC = 1; } @@ -145,7 +145,7 @@ public class CassAccess { cb.addContactPoints(cpoints); - if(bestDC!=null) { + 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 @@ -171,18 +171,18 @@ public class CassAccess { @SuppressWarnings("unchecked") public Resettable(Env env, String propData) throws APIException { - if(propData!=null && propData.length()>1) { + if (propData!=null && propData.length()>1) { String[] split = Split.split(':', propData); - if(split.length>0) { + 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) { + if (split.length>1) { messages=new ArrayList<>(); - for(int i=1;i extends AbsCassDAO0) { - for(int i=0;i0) { + if (keylimit>0) { + for (int i=0;i0) { sbfc.append(','); sbq.append(','); - if(i=keylimit) { - if(i>keylimit) { + if (i>=keylimit) { + if (i>keylimit) { sbup.append(','); } sbup.append(fields[i].getName()); sbup.append("=?"); } - if(i extends AbsCassDAO extends AbsCassDAO create(TRANS trans, DATA data) { - if(createPS==null) { + if (createPS==null) { return Result.err(Result.ERR_NotImplemented,"Create is disabled for %s",getClass().getSimpleName()); } - if(async) /*ResultSetFuture */ { + if (async) /*ResultSetFuture */ { Result rs = createPS.execAsync(trans, C_TEXT, data); - if(rs.notOK()) { + if (rs.notOK()) { return Result.err(rs); } } else { Result rs = createPS.exec(trans, C_TEXT, data); - if(rs.notOK()) { + if (rs.notOK()) { return Result.err(rs); } } @@ -206,26 +206,26 @@ public class CassDAOImpl extends AbsCassDAO> read(TRANS trans, DATA data) { - if(readPS==null) { + 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) { + 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) { + 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()) { + if (rld.isOK()) { + if (rld.isEmpty()) { return Result.err(Result.ERR_NotFound,rld.details); } else { return Result.ok(rld.value.get(0)); @@ -240,17 +240,17 @@ public class CassDAOImpl extends AbsCassDAO update(TRANS trans, DATA data, boolean async) { - if(updatePS==null) { + if (updatePS==null) { return Result.err(Result.ERR_NotImplemented,"Update is disabled for %s",getClass().getSimpleName()); } - if(async)/* ResultSet rs =*/ { + if (async)/* ResultSet rs =*/ { Result rs = updatePS.execAsync(trans, U_TEXT, data); - if(rs.notOK()) { + if (rs.notOK()) { return Result.err(rs); } } else { Result rs = updatePS.exec(trans, U_TEXT, data); - if(rs.notOK()) { + if (rs.notOK()) { return Result.err(rs); } } @@ -261,41 +261,41 @@ public class CassDAOImpl extends AbsCassDAO delete(TRANS trans, DATA data, boolean reread) { - if(deletePS==null) { + 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) { + if (reread) { Result> rd = read(trans,data); - if(rd.notOK()) { + if (rd.notOK()) { return Result.err(rd); } - if(rd.isEmpty()) { + if (rd.isEmpty()) { return Result.err(Status.ERR_NotFound,"Not Found"); } - for(DATA d : rd.value) { - if(async) { + for (DATA d : rd.value) { + if (async) { Result rs = deletePS.execAsync(trans, D_TEXT, d); - if(rs.notOK()) { + if (rs.notOK()) { return Result.err(rs); } } else { Result rs = deletePS.exec(trans, D_TEXT, d); - if(rs.notOK()) { + if (rs.notOK()) { return Result.err(rs); } } wasModified(trans, CRUD.delete, d); } } else { - if(async)/* ResultSet rs =*/ { + if (async)/* ResultSet rs =*/ { Result rs = deletePS.execAsync(trans, D_TEXT, data); - if(rs.notOK()) { + if (rs.notOK()) { return Result.err(rs); } } else { Result rs = deletePS.exec(trans, D_TEXT, data); - if(rs.notOK()) { + if (rs.notOK()) { return Result.err(rs); } } @@ -317,9 +317,9 @@ public class CassDAOImpl extends AbsCassDAO extends AbsCassDAO { rv = new Object[size]; body(data,0,rv); int body = size-keylimit(); - if(body>0) { + if (body>0) { key(data,body,rv); } break; default: rv = new Object[size]; key(data,0,rv); - if(size>keylimit()) { + if (size>keylimit()) { body(data,keylimit(),rv); } break; @@ -76,7 +76,7 @@ public abstract class Loader { } public static void writeString(DataOutputStream os, String s) throws IOException { - if(s==null) { + if (s==null) { os.writeInt(-1); } else { switch(s.length()) { @@ -108,7 +108,7 @@ public abstract class Loader { case 0: return ""; default: // Cover case where there is a large string, without always allocating a large buffer. - if(l>buff.length) { + if (l>buff.length) { buff = new byte[l]; } is.read(buff,0,l); @@ -127,11 +127,11 @@ public abstract class Loader { * @throws IOException */ public static void writeStringSet(DataOutputStream os, Collection set) throws IOException { - if(set==null) { + if (set==null) { os.writeInt(-1); } else { os.writeInt(set.size()); - for(String s : set) { + for (String s : set) { writeString(os, s); } } @@ -140,11 +140,11 @@ public abstract class Loader { public static Set readStringSet(DataInputStream is, byte[] buff) throws IOException { int l = is.readInt(); - if(l<0) { + if (l<0) { return null; } Set set = new HashSet<>(l); - for(int i=0;i { public static List readStringList(DataInputStream is, byte[] buff) throws IOException { int l = is.readInt(); - if(l<0) { + if (l<0) { return null; } List list = new ArrayList<>(l); - for(int i=0;i { * @throws IOException */ public static void writeStringMap(DataOutputStream os, Map map) throws IOException { - if(map==null) { + if (map==null) { os.writeInt(-1); } else { Set> es = map.entrySet(); os.writeInt(es.size()); - for(Entry e : es) { + for (Entry e : es) { writeString(os, e.getKey()); writeString(os, e.getValue()); } @@ -184,11 +184,11 @@ public abstract class Loader { public static Map readStringMap(DataInputStream is, byte[] buff) throws IOException { int l = is.readInt(); - if(l<0) { + if (l<0) { return null; } Map map = new HashMap<>(l); - for(int i=0;i { } public static int readHeader(DataInputStream is, final int magic, final int version) throws IOException { - if(is.readInt()!=magic) { + if (is.readInt()!=magic) { throw new IOException("Corrupted Data Stream"); } int v = is.readInt(); - if(version<0 || v>version) { + if (version<0 || v>version) { throw new IOException("Unsupported Data Version: " + v); } return v; 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 eb5885f0..106999d3 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 @@ -57,7 +57,7 @@ public class CachedCredDAO extends CachedDAO }; Result> lurd = get(trans, id, getter); - if(lurd.isOK() && lurd.isEmpty()) { + 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/CachedPermDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedPermDAO.java index a18e6a67..13180ab1 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 @@ -46,13 +46,13 @@ public class CachedPermDAO extends CachedDAO { }; Result> lurd = get(trans, ns, getter); - if(lurd.isOKhasData()) { + if (lurd.isOKhasData()) { return lurd; } else { } -// if(getter.result==null) { -// if(lurd==null) { +// if (getter.result==null) { +// if (lurd==null) { return Result.err(Status.ERR_PermissionNotFound,"No Permission found - " + lurd.details); // } else { // return Result.ok(lurd); @@ -81,7 +81,7 @@ public class CachedPermDAO extends CachedDAO { // 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()) { + if (lurd.isOK() && lurd.isEmpty()) { return Result.err(Status.ERR_PermissionNotFound,"No Permission found"); } return lurd; @@ -106,7 +106,7 @@ public class CachedPermDAO extends CachedDAO { public Result addRole(AuthzTrans trans, PermDAO.Data perm, RoleDAO.Data role) { Result rv = dao().addRole(trans,perm,role.encode()); - if(trans.debug().isLoggable()) + if (trans.debug().isLoggable()) trans.debug().log("Adding",role.encode(),"to", perm, "with CachedPermDAO.addRole"); invalidate(trans,perm); return rv; @@ -114,7 +114,7 @@ public class CachedPermDAO extends CachedDAO { public Result delRole(AuthzTrans trans, Data perm, RoleDAO.Data role) { Result rv = dao().delRole(trans,perm,role.encode()); - if(trans.debug().isLoggable()) + 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 1d8e6709..99fac2da 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 @@ -45,7 +45,7 @@ public class CachedRoleDAO extends CachedDAO { }; Result> lurd = get(trans, ns, getter); - if(lurd.isOK() && lurd.isEmpty()) { + if (lurd.isOK() && lurd.isEmpty()) { return Result.err(Status.ERR_RoleNotFound,"No Role found"); } return lurd; @@ -59,7 +59,7 @@ public class CachedRoleDAO extends CachedDAO { }; Result> lurd = get(trans, name, getter); - if(lurd.isOK() && lurd.isEmpty()) { + if (lurd.isOK() && lurd.isEmpty()) { return Result.err(Status.ERR_RoleNotFound,"No Role found"); } return lurd; @@ -74,7 +74,7 @@ public class CachedRoleDAO extends CachedDAO { public Result addPerm(AuthzTrans trans, RoleDAO.Data rd, PermDAO.Data perm) { Result rv = dao().addPerm(trans,rd,perm); - if(trans.debug().isLoggable()) + if (trans.debug().isLoggable()) trans.debug().log("Adding",perm,"to", rd, "with CachedRoleDAO.addPerm"); invalidate(trans, rd); return rv; @@ -82,7 +82,7 @@ public class CachedRoleDAO extends CachedDAO { public Result delPerm(AuthzTrans trans, RoleDAO.Data rd, PermDAO.Data perm) { Result rv = dao().delPerm(trans,rd,perm); - if(trans.debug().isLoggable()) + if (trans.debug().isLoggable()) trans.debug().log("Removing",perm,"from", rd, "with CachedRoleDAO.addPerm"); invalidate(trans, rd); return rv; 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 2121b136..c1aa9017 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 @@ -53,9 +53,9 @@ public class CachedUserRoleDAO extends CachedDAO> 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())) { + if (user!=null && user.equals(trans.user())) { Result> transLD = trans.get(transURSlot,null); - if(transLD==null ) { + if (transLD==null ) { transLD = dao.readByUser(trans, user); } return transLD; @@ -65,7 +65,7 @@ public class CachedUserRoleDAO extends CachedDAO> lurd = get(trans, user, getter); - if(lurd.isOK() && lurd.isEmpty()) { + if (lurd.isOK() && lurd.isEmpty()) { return Result.err(Status.ERR_UserRoleNotFound,"UserRole not found for [%s]",user); } return lurd; @@ -79,7 +79,7 @@ public class CachedUserRoleDAO extends CachedDAO> lurd = get(trans, role, getter); - if(lurd.isOK() && lurd.isEmpty()) { + if (lurd.isOK() && lurd.isEmpty()) { return Result.err(Status.ERR_UserRoleNotFound,"UserRole not found for [%s]",role); } return lurd; @@ -88,12 +88,12 @@ public class CachedUserRoleDAO extends CachedDAO> readUserInRole(final AuthzTrans trans, final String user, final String role) { DAOGetter getter = new DAOGetter(trans,dao()) { public Result> call() { - if(user.equals(trans.user())) { + if (user.equals(trans.user())) { Result> rrbu = readByUser(trans, user); - if(rrbu.isOK()) { + if (rrbu.isOK()) { List ld = new ArrayList<>(1); - for(Data d : rrbu.value) { - if(d.role.equals(role)) { + for (Data d : rrbu.value) { + if (d.role.equals(role)) { ld.add(d); break; } @@ -107,7 +107,7 @@ public class CachedUserRoleDAO extends CachedDAO> lurd = get(trans, keyFromObjs(user,role), getter); - if(lurd.isOK() && lurd.isEmpty()) { + 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 1948ac65..cc4135ee 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 @@ -99,7 +99,7 @@ public class ApprovalDAO extends CassDAOImpl { 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) { + if (row.getColumnDefinitions().size()>9) { // Rows reported in MicroSeconds data.updated = new Date(row.getLong(9)/1000); } @@ -168,11 +168,11 @@ public class ApprovalDAO extends CassDAOImpl { @Override public Result create(AuthzTrans trans, Data data) { // If ID is not set (typical), create one. - if(data.id==null) { + if (data.id==null) { data.id = Chrono.dateToUUID(System.currentTimeMillis()); } Result rs = createPS.exec(trans, C_TEXT, data); - if(rs.notOK()) { + if (rs.notOK()) { return Result.err(rs); } return Result.ok(data); @@ -200,14 +200,14 @@ public class ApprovalDAO extends CassDAOImpl { */ @Override public Result delete(AuthzTrans trans, Data data, boolean reread) { - if(reread || data.status == null) { // if Memo is empty, likely not full record + if (reread || data.status == null) { // if Memo is empty, likely not full record Result rd = readPS.exec(trans, R_TEXT, data); - if(rd.notOK()) { + if (rd.notOK()) { return Result.err(rd); } ApprovalLoader.deflt.load(data, rd.value.one()); } - if("approved".equals(data.status) || "denied".equals(data.status)) { + if ("approved".equals(data.status) || "denied".equals(data.status)) { StringBuilder sb = new StringBuilder("BEGIN BATCH\n"); sb.append("INSERT INTO "); sb.append(TABLELOG); @@ -228,7 +228,7 @@ public class ApprovalDAO extends CassDAOImpl { sb.append("APPLY BATCH;\n"); TimeTaken tt = trans.start("DELETE APPROVAL",Env.REMOTE); try { - if(async) { + if (async) { getSession(trans).executeAsync(sb.toString()); return Result.ok(); } else { @@ -270,7 +270,7 @@ public class ApprovalDAO extends CassDAOImpl { : (modified.name() + "d approval for " + data.user); // Detail? // Reconstruct? - if(historyDAO.create(trans, hd).status!=Status.OK) { + 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/ArtiDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/ArtiDAO.java index 6702476a..e0c0c0d4 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 @@ -170,7 +170,7 @@ public class ArtiDAO extends CassDAOImpl { writeString(os, data.mechid); writeString(os, data.machine); os.writeInt(data.type.size()); - for(String s : data.type) { + for (String s : data.type) { writeString(os, s); } writeString(os, data.sponsor); @@ -181,9 +181,9 @@ public class ArtiDAO extends CassDAOImpl { writeString(os, data.notify); os.writeLong(data.expires==null?-1:data.expires.getTime()); os.writeInt(data.renewDays); - if(data.sans!=null) { + if (data.sans!=null) { os.writeInt(data.sans.size()); - for(String s : data.sans) { + for (String s : data.sans) { writeString(os, s); } } else { @@ -200,7 +200,7 @@ public class ArtiDAO extends CassDAOImpl { data.machine = readString(is,buff); int size = is.readInt(); data.type = new HashSet<>(size); - for(int i=0;i { data.renewDays = is.readInt(); size = is.readInt(); data.sans = new HashSet<>(size); - for(int i=0;i { private void init(AuthzTrans trans) { // Set up sub-DAOs - if(historyDAO==null) { + if (historyDAO==null) { historyDAO = new HistoryDAO(trans,this); } @@ -288,7 +288,7 @@ 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) { + if (modified==CRUD.delete) { try { hd.reconstruct = data.bytify(); } catch (IOException e) { @@ -296,7 +296,7 @@ public class ArtiDAO extends CassDAOImpl { } } - if(historyDAO.create(trans, hd).status!=Status.OK) { + 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/CacheInfoDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CacheInfoDAO.java index e3f994c0..4aa94866 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 @@ -138,7 +138,7 @@ public class CacheInfoDAO extends CassDAOImpl impl } public static void startUpdate(AuthzEnv env, HMangr hman, SecuritySetter ss, String ip, int port) { - if(cacheUpdate==null) { + if (cacheUpdate==null) { Thread t= new Thread(cacheUpdate = new CacheUpdate(env,hman,ss, ip,port),"CacheInfo Update Thread"); t.setDaemon(true); t.start(); @@ -146,7 +146,7 @@ public class CacheInfoDAO extends CassDAOImpl impl } public static void stopUpdate() { - if(cacheUpdate!=null) { + if (cacheUpdate!=null) { cacheUpdate.go=false; } } @@ -195,9 +195,9 @@ public class CacheInfoDAO extends CassDAOImpl impl @Override public Integer code(Rcli client) throws APIException, CadiException { URI to = client.getURI(); - if(!to.getAuthority().equals(authority)) { + if (!to.getAuthority().equals(authority)) { Future f = client.delete("/mgmt/cache/"+type+'/'+segs,VOID_CT); - if(f.get(hman.readTimeout())) { + if (f.get(hman.readTimeout())) { ++total; } else { trans.error().log("Error During AAF Peer Notify",f.code(),f.body()); @@ -216,14 +216,14 @@ public class CacheInfoDAO extends CassDAOImpl impl set = null; } public void add(int[] ints) { - if(set==null) { + if (set==null) { set = new HashSet<>(); - for(int i=0;i impl public String toString() { StringBuilder sb = new StringBuilder(); boolean first = true; - if(set==null) { - for(int i : raw) { - if(first) { + if (set==null) { + for (int i : raw) { + if (first) { first=false; } else { sb.append(','); @@ -242,8 +242,8 @@ public class CacheInfoDAO extends CassDAOImpl impl sb.append(i); } } else { - for(Integer i : set) { - if(first) { + for (Integer i : set) { + if (first) { first=false; } else { sb.append(','); @@ -260,7 +260,7 @@ public class CacheInfoDAO extends CassDAOImpl impl do { try { Transfer data = notifyDQ.poll(4,TimeUnit.SECONDS); - if(data==null) { + if (data==null) { continue; } @@ -271,37 +271,37 @@ public class CacheInfoDAO extends CassDAOImpl impl long start=0; // Do a block poll first do { - if(gather==null) { + 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) { + 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()) { + } while ((data = notifyDQ.poll())!=null); + if (gather!=null) { + for (Entry es : gather.entrySet()) { cc.set(es); try { - if(hman.all(ss, cc, false)!=null) { + if (hman.all(ss, cc, false)!=null) { ++count; } } catch (Exception e) { trans.error().log(e, "Error on Cache Update"); } } - if(env.debug().isLoggable()) { + 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) { + if (count==1) { sb.append(" entry for "); } else { sb.append(" entries for "); @@ -309,7 +309,7 @@ public class CacheInfoDAO extends CassDAOImpl impl int peers = count<=0?0:cc.total/count; sb.append(peers); sb.append(" client"); - if(peers!=1) { + if (peers!=1) { sb.append('s'); } sb.append(" in "); @@ -323,7 +323,7 @@ public class CacheInfoDAO extends CassDAOImpl impl go = false; Thread.currentThread().interrupt(); } - } while(go); + } while (go); } } @@ -347,9 +347,9 @@ public class CacheInfoDAO extends CassDAOImpl impl ///////////// // 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) { + if (cacheUpdate!=null) { try { - if(!CacheUpdate.notifyDQ.offer(new CacheUpdate.Transfer(name, seg),2,TimeUnit.SECONDS)) { + 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) { @@ -367,7 +367,7 @@ public class CacheInfoDAO extends CassDAOImpl impl start.append(": "); StringBuilder sb = new StringBuilder("BEGIN BATCH\n"); boolean first = true; - for(int s : seg) { + for (int s : seg) { sb.append(UPDATE_SP); sb.append(TABLE); sb.append(" SET touched=dateof(now()) WHERE name = '"); @@ -375,7 +375,7 @@ public class CacheInfoDAO extends CassDAOImpl impl sb.append("' AND seg = "); sb.append(s); sb.append(";\n"); - if(first) { + if (first) { first =false; } else { start.append(','); @@ -413,24 +413,24 @@ public class CacheInfoDAO extends CassDAOImpl impl String lastName = null; Date[] dates = null; - for(Row row : rs.all()) { + for (Row row : rs.all()) { String name = row.getString(0); int seg = row.getInt(1); - if(!name.equals(lastName)) { + if (!name.equals(lastName)) { dates = info.get(name); lastName=name; } - if(dates==null) { + if (dates==null) { dates=new Date[seg+1]; info.put(name,dates); - } else if(dates.length<=seg) { + } 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)) { + if (dates[seg]==null || dates[seg].before(temp)) { dates[seg]=temp; } } @@ -443,16 +443,16 @@ public class CacheInfoDAO extends CassDAOImpl impl @Override public Date get(AuthzTrans trans, String table, int seg) { Date[] dates = info.get(table); - if(dates==null) { + if (dates==null) { dates = new Date[seg+1]; touch(trans,table, seg); - } else if(dates.length<=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) { + if (rv==null) { rv=dates[seg]=startTime; } return rv; 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 00c9ae90..6c23938f 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 @@ -143,7 +143,7 @@ public class CertDAO extends CassDAOImpl { writeString(os, data.x500); writeString(os, data.x509); writeString(os, data.ca); - if(data.serial==null) { + if (data.serial==null) { os.writeInt(-1); } else { byte[] dsba = data.serial.toByteArray(); @@ -164,9 +164,9 @@ public class CertDAO extends CassDAOImpl { data.ca = readString(is,buff); int i = is.readInt(); data.serial=null; - if(i>=0) { + 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) { + if (is.read(bytes)>0) { data.serial = new BigInteger(bytes); } } @@ -180,10 +180,10 @@ public class CertDAO extends CassDAOImpl { private void init(AuthzTrans trans) throws APIException, IOException { // Set up sub-DAOs - if(historyDAO==null) { + if (historyDAO==null) { historyDAO = new HistoryDAO(trans,this); } - if(infoDAO==null) { + if (infoDAO==null) { infoDAO = new CacheInfoDAO(trans,this); } @@ -226,7 +226,7 @@ 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) { + if (modified==CRUD.delete) { try { hd.reconstruct = data.bytify(); } catch (IOException e) { @@ -234,10 +234,10 @@ public class CertDAO extends CassDAOImpl { } } - if(historyDAO.create(trans, hd).status!=Status.OK) { + if (historyDAO.create(trans, hd).status!=Status.OK) { trans.error().log("Cannot log to History"); } - if(infoDAO.touch(trans, TABLE,data.invalidate(cache)).status!=Status.OK) { + if (infoDAO.touch(trans, TABLE,data.invalidate(cache)).status!=Status.OK) { trans.error().log("Cannot touch Cert"); } } 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 5bcba9d9..7674c7e8 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 @@ -158,7 +158,7 @@ public class CredDAO extends CassDAOImpl { os.writeInt(data.other==null?0:data.other); writeString(os, data.ns); writeString(os, data.notes); - if(data.cred==null) { + if (data.cred==null) { os.writeInt(-1); } else { int l = data.cred.limit()-data.cred.position(); @@ -183,10 +183,10 @@ public class CredDAO extends CassDAOImpl { int i = is.readInt(); data.cred=null; - if(i>=0) { + 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) { + if (read>0) { data.cred = ByteBuffer.wrap(bytes); } } @@ -195,10 +195,10 @@ public class CredDAO extends CassDAOImpl { private void init(AuthzTrans trans) throws APIException, IOException { // Set up sub-DAOs - if(historyDAO==null) { + if (historyDAO==null) { historyDAO = new HistoryDAO(trans,this); } - if(infoDAO==null) { + if (infoDAO==null) { infoDAO = new CacheInfoDAO(trans,this); } @@ -241,7 +241,7 @@ 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) { + if (modified==CRUD.delete) { try { hd.reconstruct = data.bytify(); } catch (IOException e) { @@ -249,10 +249,10 @@ public class CredDAO extends CassDAOImpl { } } - if(historyDAO.create(trans, hd).status!=Status.OK) { + if (historyDAO.create(trans, hd).status!=Status.OK) { trans.error().log("Cannot log to History"); } - if(infoDAO.touch(trans, TABLE,data.invalidate(cache)).status!=Status.OK) { + if (infoDAO.touch(trans, TABLE,data.invalidate(cache)).status!=Status.OK) { trans.error().log("Cannot touch Cred"); } } 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 6b0ea2df..a98f101f 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 @@ -143,14 +143,14 @@ public class FutureDAO extends CassDAOImpl { */ public Result create(AuthzTrans trans, FutureDAO.Data data, String id) { // If ID is not set (typical), create one. - if(data.id==null) { + 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()) { + if (rs.notOK()) { return Result.err(rs); } wasModified(trans, CRUD.create, data, null, id); @@ -175,7 +175,7 @@ public class FutureDAO extends CassDAOImpl { 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) { + 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 ce7e5477..a40b28fb 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 @@ -174,7 +174,7 @@ public class HistoryDAO extends CassDAOImpl { public Result> readByYYYYMM(AuthzTrans trans, int yyyymm) { Result rs = readByYRMN.exec(trans, "yr_mon", yyyymm); - if(rs.notOK()) { + if (rs.notOK()) { return Result.err(rs); } return extract(defLoader,rs.value,null,dflt); @@ -186,22 +186,22 @@ public class HistoryDAO extends CassDAOImpl { * month - the month in a year ...values 1 - 12 **/ public Result> readByUser(AuthzTrans trans, String user, int ... yyyymm) { - if(yyyymm.length==0) { + 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()) { + 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) { + 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()) { + if (rs.notOK()) { return Result.err(rs); } return extract(defLoader,rs.value,null,yyyymm.length>0?new YYYYMM(yyyymm):dflt); @@ -215,8 +215,8 @@ public class HistoryDAO extends CassDAOImpl { @Override public boolean ok(Data data) { int dym = data.yr_mon; - for(int ym:yyyymm) { - if(dym==ym) { + for (int ym:yyyymm) { + if (dym==ym) { return true; } } 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 5d7aebed..757efa5f 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 @@ -162,11 +162,11 @@ public class LocateDAO extends CassDAOImpl { os.writeFloat(data.latitude); os.writeFloat(data.longitude); writeString(os, data.protocol); - if(data.subprotocol==null) { + if (data.subprotocol==null) { os.writeInt(0); } else { os.writeInt(data.subprotocol.size()); - for(String s: data.subprotocol) { + for (String s: data.subprotocol) { writeString(os,s); } } @@ -192,11 +192,11 @@ public class LocateDAO extends CassDAOImpl { int size = is.readInt(); data.subprotocol = new HashSet<>(size); - for(int i=0;i0) { + if (port_key.length()>0) { data.port_key=UUID.fromString(port_key); } else { data.port_key = null; 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 29ac379b..192887b9 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 @@ -55,9 +55,9 @@ public class Namespace implements Bytification { description = ndd.description; type = ndd.type; parent = ndd.parent; - if(ndd.attrib!=null && !ndd.attrib.isEmpty()) { + if (ndd.attrib!=null && !ndd.attrib.isEmpty()) { attrib = new ArrayList<>(); - for( Entry entry : ndd.attrib.entrySet()) { + for ( Entry entry : ndd.attrib.entrySet()) { attrib.add(new Pair(entry.getKey(),entry.getValue())); } } @@ -70,9 +70,9 @@ public class Namespace implements Bytification { description = ndd.description; type = ndd.type; parent = ndd.parent; - if(ndd.attrib!=null && !ndd.attrib.isEmpty()) { + if (ndd.attrib!=null && !ndd.attrib.isEmpty()) { attrib = new ArrayList<>(); - for( Entry entry : ndd.attrib.entrySet()) { + for ( Entry entry : ndd.attrib.entrySet()) { attrib.add(new Pair(entry.getKey(),entry.getValue())); } } @@ -141,7 +141,7 @@ public class Namespace implements Bytification { */ @Override public boolean equals(Object arg0) { - if(arg0==null || !(arg0 instanceof Namespace)) { + 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 30f0d6b5..f769e38c 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 @@ -149,10 +149,10 @@ public class NsDAO extends CassDAOImpl { private void init(AuthzTrans trans) throws APIException, IOException { // Set up sub-DAOs - if(historyDAO==null) { + if (historyDAO==null) { historyDAO = new HistoryDAO(trans, this); } - if(infoDAO==null) { + if (infoDAO==null) { infoDAO = new CacheInfoDAO(trans,this); } @@ -205,11 +205,11 @@ public class NsDAO extends CassDAOImpl { os.writeInt(data.type); writeString(os,data.description); writeString(os,data.parent); - if(data.attrib==null) { + if (data.attrib==null) { os.writeInt(-1); } else { os.writeInt(data.attrib.size()); - for(Entry es : data.attrib(false).entrySet()) { + for (Entry es : data.attrib(false).entrySet()) { writeString(os,es.getKey()); writeString(os,es.getValue()); } @@ -227,9 +227,9 @@ public class NsDAO extends CassDAOImpl { data.description = readString(is,buff); data.parent = readString(is,buff); int count = is.readInt(); - if(count>0) { + if (count>0) { Map da = data.attrib(true); - for(int i=0;i { public Result create(AuthzTrans trans, Data data) { String ns = data.name; // Ensure Parent is set - if(data.parent==null) { + if (data.parent==null) { return Result.err(Result.ERR_BadData, "Need parent for %s", ns); } @@ -254,7 +254,7 @@ public class NsDAO extends CassDAOImpl { getSession(trans).execute(stmt.toString()); //// TEST CODE for Exception // boolean force = true; -// if(force) { +// 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"); // } @@ -272,7 +272,7 @@ public class NsDAO extends CassDAOImpl { public Result update(AuthzTrans trans, Data data) { String ns = data.name; // Ensure Parent is set - if(data.parent==null) { + if (data.parent==null) { return Result.err(Result.ERR_BadData, "Need parent for %s", ns); } @@ -281,26 +281,26 @@ public class NsDAO extends CassDAOImpl { try { Map localAttr = data.attrib; Result> rremoteAttr = readAttribByNS(trans,ns); - if(rremoteAttr.notOK()) { + if (rremoteAttr.notOK()) { return Result.err(rremoteAttr); } // update Attributes String str; - for(Entry es : localAttr.entrySet()) { + for (Entry es : localAttr.entrySet()) { str = rremoteAttr.value.get(es.getKey()); - if(str==null || !str.equals(es.getValue())) { + 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()) { +// for (Entry es : remoteAttr.entrySet()) { // str = localAttr.get(es.getKey()); -// if(str==null || !str.equals(es.getValue())) { +// if (str==null || !str.equals(es.getValue())) { // attribDeleteStmt(stmt, ns, es.getKey()); // } // } - if(stmt.length()>BEGIN_BATCH.length()) { + if (stmt.length()>BEGIN_BATCH.length()) { stmt.append(APPLY_BATCH); getSession(trans).execute(stmt.toString()); } @@ -320,11 +320,11 @@ public class NsDAO extends CassDAOImpl { public Result> read(AuthzTrans trans, Data data) { Result> rld = super.read(trans, data); - if(rld.isOKhasData()) { - for(Data d : rld.value) { + 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()) { + if (rabn.isOK()) { d.attrib = rabn.value; } else { return Result.err(rabn); @@ -341,11 +341,11 @@ public class NsDAO extends CassDAOImpl { public Result> read(AuthzTrans trans, Object... key) { Result> rld = super.read(trans, key); - if(rld.isOKhasData()) { - for(Data d : rld.value) { + 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()) { + if (rabn.isOK()) { d.attrib = rabn.value; } else { return Result.err(rabn); @@ -385,7 +385,7 @@ public class NsDAO extends CassDAOImpl { + ns + "';"); - for(Iterator iter = rs.iterator();iter.hasNext(); ) { + for (Iterator iter = rs.iterator();iter.hasNext(); ) { Row r = iter.next(); map.put(r.getString(0), r.getString(1)); } @@ -408,7 +408,7 @@ public class NsDAO extends CassDAOImpl { + key + "';"); - for(Iterator iter = rs.iterator();iter.hasNext(); ) { + for (Iterator iter = rs.iterator();iter.hasNext(); ) { Row r = iter.next(); set.add(r.getString(0)); } @@ -489,7 +489,7 @@ public class NsDAO extends CassDAOImpl { private void attribInsertStmts(StringBuilder stmt, Data data) { // INSERT new Attrib - for(Entry es : data.attrib(false).entrySet() ) { + for (Entry es : data.attrib(false).entrySet() ) { stmt.append(" "); attribInsertStmt(stmt,data.name,es.getKey(),es.getValue()); } @@ -541,7 +541,7 @@ 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) { + if (modified==CRUD.delete) { try { hd.reconstruct = data.bytify(); } catch (IOException e) { @@ -549,10 +549,10 @@ public class NsDAO extends CassDAOImpl { } } - if(historyDAO.create(trans, hd).status!=Status.OK) { + if (historyDAO.create(trans, hd).status!=Status.OK) { trans.error().log("Cannot log to History"); } - if(infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) { + if (infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) { trans.error().log("Cannot touch CacheInfo"); } } 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 a64c0a94..2beeaf38 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 @@ -28,10 +28,10 @@ public class NsSplit { public NsSplit(NsDAO.Data nsd, String child) { this.nsd = nsd; - if(child.startsWith(nsd.name)) { + if (child.startsWith(nsd.name)) { ns = nsd.name; int dot = ns.length(); - if(dot=0) { + if (dot>=0) { nsd.parent = ns.substring(0, dot); } else { nsd.parent = "."; 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 59e18ae9..e656a555 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 @@ -46,8 +46,8 @@ public enum NsType { * @return */ public static NsType fromType(int t) { - for(NsType nst : values()) { - if(t==nst.type) { + for (NsType nst : values()) { + if (t==nst.type) { return nst; } } @@ -60,9 +60,9 @@ public enum NsType { * @return */ public static NsType fromString(String s) { - if(s!=null) { - for(NsType nst : values()) { - if(nst.name().equals(s)) { + if (s!=null) { + for (NsType nst : values()) { + if (nst.name().equals(s)) { return nst; } } 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 c02387b1..6e1057b8 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 @@ -114,13 +114,13 @@ public class PermDAO extends CassDAOImpl { */ public static Result decode(AuthzTrans trans, Question q, String p) { String[] ss = Split.splitTrim('|', p,4); - if(ss[2]==null) { + 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 + if (ss[3]==null) { // older 3 part encoding must be evaluated for NS Result nss = q.deriveNsSplit(trans, ss[0]); - if(nss.notOK()) { + if (nss.notOK()) { return Result.err(nss); } data.ns=nss.value.ns; @@ -146,15 +146,15 @@ public class PermDAO extends CassDAOImpl { */ public static Result decodeToArray(AuthzTrans trans, Question q, String p) { String[] ss = Split.splitTrim('|', p,4); - if(ss[2]==null) { + 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 + 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()) { + if (nss.notOK()) { return Result.err(nss); } ss[1] = nss.value.name; @@ -191,7 +191,7 @@ public class PermDAO extends CassDAOImpl { String[] s = name.split("\\|"); Result rdns = q.deriveNsSplit(trans, s[0]); Data rv = new PermDAO.Data(); - if(rdns.isOKhasData()) { + if (rdns.isOKhasData()) { switch(s.length) { case 3: rv.type=s[1]; @@ -482,7 +482,7 @@ public class PermDAO extends CassDAOImpl { hd.memo = String.format("%sd %s|%s|%s", modified.name(),data.fullType(),data.instance,data.action); } - if(modified==CRUD.delete) { + if (modified==CRUD.delete) { try { hd.reconstruct = data.bytify(); } catch (IOException e) { @@ -490,10 +490,10 @@ public class PermDAO extends CassDAOImpl { } } - if(historyDAO.create(trans, hd).status!=Status.OK) { + if (historyDAO.create(trans, hd).status!=Status.OK) { trans.error().log("Cannot log to History"); } - if(infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) { + if (infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) { 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 4489d268..127dd4e2 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 @@ -124,9 +124,9 @@ public class RoleDAO extends CassDAOImpl { 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 + if (ss[1]==null) { // older 1 part encoding must be evaluated for NS Result nss = q.deriveNsSplit(trans, ss[0]); - if(nss.notOK()) { + if (nss.notOK()) { return Result.err(nss); } data.ns=nss.value.ns; @@ -161,9 +161,9 @@ public class RoleDAO extends CassDAOImpl { */ 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 + if (ss[1]==null) { // older 1 part encoding must be evaluated for NS Result nss = q.deriveNsSplit(trans, ss[0]); - if(nss.notOK()) { + if (nss.notOK()) { return Result.err(nss); } ss[0] = nss.value.ns; @@ -287,7 +287,7 @@ public class RoleDAO extends CassDAOImpl { } public Result> readChildren(AuthzTrans trans, String ns, String role) { - if(role.length()==0 || "*".equals(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}); @@ -392,7 +392,7 @@ public class RoleDAO extends CassDAOImpl { 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) { + if (modified==CRUD.delete) { try { hd.reconstruct = data.bytify(); } catch (IOException e) { @@ -400,10 +400,10 @@ public class RoleDAO extends CassDAOImpl { } } - if(historyDAO.create(trans, hd).status!=Status.OK) { + if (historyDAO.create(trans, hd).status!=Status.OK) { trans.error().log("Cannot log to History"); } - if(infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) { + if (infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) { trans.error().log("Cannot touch CacheInfo for Role"); } } 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 7b9f7b91..26f9a995 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 @@ -127,7 +127,7 @@ public class UserRoleDAO extends CassDAOImpl { public boolean role(AuthzTrans trans, Question ques, String role) { this.role = role; Result rnss = ques.deriveNsSplit(trans, role); - if(rnss.isOKhasData()) { + if (rnss.isOKhasData()) { ns = rnss.value.ns; rname = rnss.value.name; return true; @@ -304,15 +304,15 @@ public class UserRoleDAO extends CassDAOImpl { : "n/a"; } - if(historyDAO.create(trans, hd).status!=Status.OK) { + if (historyDAO.create(trans, hd).status!=Status.OK) { trans.error().log("Cannot log to History"); } - if(historyDAO.create(trans, hdRole).status!=Status.OK) { + 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()) { + if (infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) { 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 f0a59582..0bc23c92 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 @@ -47,7 +47,7 @@ public class CassExecutor implements Executor { @Override public boolean inRole(String name) { Result nss = q.deriveNsSplit(trans, name); - if(nss.notOK())return false; + if (nss.notOK())return false; return q.roleDAO.read(trans, nss.value.ns,nss.value.name).isOKhasData(); } @@ -58,7 +58,7 @@ public class CassExecutor implements Executor { @Override public String namespace() throws Exception { Result res = q.validNSOfDomain(trans,trans.user()); - if(res.isOK()) { + if (res.isOK()) { String user[] = trans.user().split("\\."); return user[user.length-1] + '.' + user[user.length-2]; } 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 f3aae2ec..f440a8cd 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 @@ -81,9 +81,9 @@ public class Function { * @return */ public static FUTURE_OP toFO(String value) { - if(value!=null) { - for(FUTURE_OP fo : values()) { - if(fo.name().equals(value)){ + if (value!=null) { + for (FUTURE_OP fo : values()) { + if (fo.name().equals(value)){ return fo; } } @@ -194,16 +194,16 @@ public class Function { 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) { + } 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 + 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()) { + 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"); @@ -267,7 +267,7 @@ public class Function { // or helpful for Operations folks.. // Admins can be empty, because they can be changed by lower level // NSs - // if(ns.admin(false).isEmpty()) { + // if (ns.admin(false).isEmpty()) { // ns.admin(true).add(user); // } if (namespace.admin != null) { @@ -334,9 +334,9 @@ public class Function { for (RoleDAO.Data rdd : rrdc.value) { // Remove old Role from Perms, save them off List lpdd = new ArrayList<>(); - for(String p : rdd.perms(false)) { + for (String p : rdd.perms(false)) { Result rpdd = PermDAO.Data.decode(trans,q,p); - if(rpdd.isOKhasData()) { + if (rpdd.isOKhasData()) { PermDAO.Data pdd = rpdd.value; lpdd.add(pdd); q.permDAO.delRole(trans, pdd, rdd); @@ -358,13 +358,13 @@ public class Function { // "create" per se if ((rq = q.roleDAO.create(trans, rdd)).isOK()) { // Put Role back into Perm, with correct info - for(PermDAO.Data pdd : lpdd) { + 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) { + if (rurd.isOKhasData()) { + for (UserRoleDAO.Data urd : rurd.value) { urd.ns = rdd.ns; urd.rname = rdd.name; q.userRoleDAO.update(trans, urd); @@ -389,9 +389,9 @@ public class Function { // Remove old Perm from Roles, save them off List lrdd = new ArrayList<>(); - for(String rl : pdd.roles(false)) { + for (String rl : pdd.roles(false)) { Result rrdd = RoleDAO.Data.decode(trans,q,rl); - if(rrdd.isOKhasData()) { + if (rrdd.isOKhasData()) { RoleDAO.Data rdd = rrdd.value; lrdd.add(rdd); q.roleDAO.delPerm(trans, rdd, pdd); @@ -408,7 +408,7 @@ public class Function { .substring(targetNameDot) : ""; if ((rq = q.permDAO.create(trans, pdd)).isOK()) { // Put Role back into Perm, with correct info - for(RoleDAO.Data rdd : lrdd) { + for (RoleDAO.Data rdd : lrdd) { q.roleDAO.addPerm(trans, rdd, pdd); } @@ -698,7 +698,7 @@ public class Function { } else { if (org.isTestEnv()) { String reason2; - if((reason2 = org.validate(trans, Policy.AS_RESPONSIBLE, new CassExecutor(trans, this), id))==null) { + if ((reason2 = org.validate(trans, Policy.AS_RESPONSIBLE, new CassExecutor(trans, this), id))==null) { return Result.ok(); } else { trans.debug().log(reason2); @@ -726,7 +726,7 @@ public class Function { 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()))) { + if (!(ruinr.isOKhasData() && ruinr.value.get(0).expires.after(new Date()))) { return Result.err(rq); } } @@ -748,7 +748,7 @@ public class Function { "%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)) { +// } else if (user.endsWith(ALTERNATE OAUTH DOMAIN)) { // return Result.ok(); } else { Result> cdr = q.credDAO.readID(trans, user); @@ -794,7 +794,7 @@ public class Function { 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()))) { + if (!(ruinr.isOKhasData() && ruinr.value.get(0).expires.after(new Date()))) { return Result.err(rq); } } @@ -827,9 +827,9 @@ public class Function { // Remove old Perm from Roles, save them off List lrdd = new ArrayList<>(); - for(String rl : pdd.roles(false)) { + for (String rl : pdd.roles(false)) { Result rrdd = RoleDAO.Data.decode(trans,q,rl); - if(rrdd.isOKhasData()) { + if (rrdd.isOKhasData()) { RoleDAO.Data rdd = rrdd.value; lrdd.add(rdd); q.roleDAO.delPerm(trans, rdd, pdd); @@ -846,7 +846,7 @@ public class Function { // 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) { + for (RoleDAO.Data rdd : lrdd) { q.roleDAO.addPerm(trans, rdd, pdd); } @@ -892,9 +892,9 @@ public class Function { } // Remove old Role from Perms, save them off List lpdd = new ArrayList<>(); - for(String p : rdd.perms(false)) { + for (String p : rdd.perms(false)) { Result rpdd = PermDAO.Data.decode(trans,q,p); - if(rpdd.isOKhasData()) { + if (rpdd.isOKhasData()) { PermDAO.Data pdd = rpdd.value; lpdd.add(pdd); q.permDAO.delRole(trans, pdd, rdd); @@ -912,7 +912,7 @@ public class Function { // 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) { + for (PermDAO.Data pdd : lpdd) { q.permDAO.addRole(trans, pdd, rdd); } @@ -973,7 +973,7 @@ public class Function { // For each Role for (String role : roles = perm.roles(true)) { Result rdd = RoleDAO.Data.decode(trans,q,role); - if(rdd.isOKhasData()) { + if (rdd.isOKhasData()) { RoleDAO.Data rd = rdd.value; if (!fromApproval) { // May User write to the Role in question. @@ -1038,7 +1038,7 @@ public class Function { for (String role : fullperm.roles) { Result rv = null; Result rrdd = RoleDAO.Data.decode(trans, q, role); - if(rrdd.isOKhasData()) { + 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()) { @@ -1131,19 +1131,19 @@ public class Function { if (!fromApproval) { Result rRoleCo = q.deriveFirstNsForType(trans, role.ns, NsType.COMPANY); - if(rRoleCo.notOK()) { + if (rRoleCo.notOK()) { return Result.err(rRoleCo); } Result rPermCo = q.deriveFirstNsForType(trans, pd.ns, NsType.COMPANY); - if(rPermCo.notOK()) { + if (rPermCo.notOK()) { return Result.err(rPermCo); } // Not from same company - if(!rRoleCo.value.name.equals(rPermCo.value.name)) { + 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()) { + if ((r = q.mayUser(trans, user, role, Access.write)).notOK()) { return Result.err(r); } } @@ -1279,7 +1279,7 @@ public class Function { break; } } - if(!notFound) { + if (!notFound) { break; } } @@ -1343,14 +1343,14 @@ public class Function { */ public Result addUserRole(AuthzTrans trans,UserRoleDAO.Data urData) { Result rv; - if(Question.ADMIN.equals(urData.rname)) { + if (Question.ADMIN.equals(urData.rname)) { rv = mayAddAdmin(trans, urData.ns, urData.user); - } else if(Question.OWNER.equals(urData.rname)) { + } 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()) { + if (rv.notOK()) { return rv; } @@ -1378,7 +1378,7 @@ public class Function { public Result addUserRole(AuthzTrans trans, String user, String ns, String rname) { try { - if(trans.org().getIdentity(trans, user)==null) { + 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) { @@ -1476,9 +1476,9 @@ public class Function { Result> rrbr = q.userRoleDAO .readByRole(trans, nsd.name + Question.DOT_OWNER); if (rrbr.isOKhasData()) { - for(UserRoleDAO.Data urd : rrbr.value) { + for (UserRoleDAO.Data urd : rrbr.value) { Identity owner = org.getIdentity(trans, urd.user); - if(owner==null) { + if (owner==null) { return Result.err(Result.ERR_NotFound,urd.user + " is not a Valid Owner of " + nsd.name); } else { owners.add(owner); @@ -1487,7 +1487,7 @@ public class Function { } } - if(owners.isEmpty()) { + if (owners.isEmpty()) { return Result.err(Result.ERR_NotFound,"No Owners found for " + nsd.name); } @@ -1501,17 +1501,17 @@ public class Function { final UUID ticket = fr.value.id; sb.append(", Approvals: "); Boolean first[] = new Boolean[]{true}; - if(op!=FUTURE_OP.A) { + 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()) { + 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()) { + if (r.notOK()) { return Result.err(r); } } @@ -1534,7 +1534,7 @@ public class Function { @Override public UserRoleDAO.Data get(AuthzTrans trans, Object ... keys) { Result> r = q.userRoleDAO.read(trans, keys); - if(r.isOKhasData()) { + if (r.isOKhasData()) { return r.value.get(0); } else { return null; @@ -1556,18 +1556,18 @@ public class Function { 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) { + 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) { + if (lurdd==null) { q.futureDAO.delete(trans, curr, false); return OP_STATUS.RL; } else { - if(curr.expires.compareTo(lurdd.expires)<0) { + if (curr.expires.compareTo(lurdd.expires)<0) { q.futureDAO.delete(trans, curr, false); return OP_STATUS.RL; } @@ -1579,21 +1579,21 @@ public class Function { boolean aDenial = false; int cntSuper=0, appSuper=0,cntOwner=0, appOwner=0; - for(ApprovalDAO.Data add : la.get(trans)) { + for (ApprovalDAO.Data add : la.get(trans)) { switch(add.status) { case "approved": - if("owner".equals(add.type)) { + if ("owner".equals(add.type)) { ++cntOwner; ++appOwner; - } else if("supervisor".equals(add.type)) { + } else if ("supervisor".equals(add.type)) { ++cntSuper; ++appSuper; } break; case "pending": - if("owner".equals(add.type)) { + if ("owner".equals(add.type)) { ++cntOwner; - } else if("supervisor".equals(add.type)) { + } else if ("supervisor".equals(add.type)) { ++cntSuper; } break; @@ -1604,18 +1604,18 @@ public class Function { } Result ros=null; - if(aDenial) { + 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()) { + 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)) { + if (fop.equals(FUTURE_OP.U) || fop.equals(FUTURE_OP.A)) { UserRoleDAO.Data data = new UserRoleDAO.Data(); try { data.reconstitute(curr.construct); @@ -1631,7 +1631,7 @@ public class Function { // 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) { + if (goDecision) { // should check if any other pendings before performing // actions try { @@ -1684,7 +1684,7 @@ public class Function { default: } } else if (FOP_USER_ROLE.equalsIgnoreCase(curr.target)) { - if(urdd==null) { + if (urdd==null) { urdd = new UserRoleDAO.Data(); urdd.reconstitute(curr.construct); } @@ -1737,7 +1737,7 @@ public class Function { } q.futureDAO.delete(trans, curr, false); } // end for goDecision - if(ros==null) { + if (ros==null) { //return Result.err(Status.ACC_Future, "Full Approvals not obtained: No action taken"); ros = OP_STATUS.RP; } @@ -1747,7 +1747,7 @@ public class Function { // Convenience method for setting OPSTatus Results private Result set(Result rs, Result orig) { - if(orig.isOK()) { + if (orig.isOK()) { return rs; } else { return Result.err(orig); @@ -1767,8 +1767,8 @@ public class Function { ad.operation = op.name(); // Note ad.updated is created in System Result r = q.approvalDAO.create(trans,ad); - if(r.isOK()) { - if(first[0]) { + if (r.isOK()) { + if (first[0]) { first[0] = false; } else { sb.append(", "); 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 6bb440ad..98621457 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 @@ -75,17 +75,17 @@ class PermLookup { } public Result> getUserRoles() { - if(userRoles==null) { + if (userRoles==null) { userRoles = q.userRoleDAO.readByUser(trans,user); - if(userRoles.isOKhasData()) { + if (userRoles.isOKhasData()) { List lurdd = new ArrayList<>(); Date now = new Date(); - for(UserRoleDAO.Data urdd : userRoles.value) { - if(urdd.expires.after(now)) { // Remove Expired + for (UserRoleDAO.Data urdd : userRoles.value) { + if (urdd.expires.after(now)) { // Remove Expired lurdd.add(urdd); } } - if(lurdd.size()==0) { + if (lurdd.size()==0) { return userRoles = Result.err(Status.ERR_UserNotFound, "%s not found or not associated with any Roles: ", user); @@ -101,18 +101,18 @@ class PermLookup { } public Result> getRoles() { - if(roles==null) { + if (roles==null) { Result> rur = getUserRoles(); - if(rur.isOK()) { + 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) { + 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()) { + if (rlrd.isOK()) { lrdd.addAll(rlrd.value); } } @@ -127,7 +127,7 @@ class PermLookup { } public Result> getPermNames() { - if(permNames==null) { + if (permNames==null) { Result> rlrd = getRoles(); if (rlrd.isOK()) { Set pns = new TreeSet<>(); @@ -144,16 +144,16 @@ class PermLookup { } public Result> getPerms(boolean lookup) { - if(perms==null) { + 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()) { + if (rss.isOK()) { List lpdd = new ArrayList<>(); for (String perm : rss.value) { - if(lookup) { + if (lookup) { Result ap = PermDAO.Data.decodeToArray(trans, q, perm); - if(ap.isOK()) { + if (ap.isOK()) { Result> rlpd = q.permDAO.read(perm,trans,ap.value); if (rlpd.isOKhasData()) { 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 152412a2..e63bc52a 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 @@ -166,17 +166,17 @@ public class Question { // Only want to aggressively cleanse User related Caches... The others, // just normal refresh - if(startClean) { + 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) { + if (specialLogSlot==null) { specialLogSlot = trans.slot(AuthzTransFilter.SPECIAL_LOG_SLOT); } - if(transIDSlot==null) { + if (transIDSlot==null) { transIDSlot = trans.slot(AuthzTransFilter.TRANS_ID_SLOT); } @@ -226,25 +226,25 @@ public class Question { public Result> getPermsByUserFromRolesFilter(AuthzTrans trans, String user, String forUser) { PermLookup plUser = PermLookup.get(trans, this, user); Result> plPermNames = plUser.getPermNames(); - if(plPermNames.notOK()) { + if (plPermNames.notOK()) { return Result.err(plPermNames); } Set nss; - if(forUser.equals(user)) { + 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()) { + if (forUpn.notOK()) { return Result.err(forUpn); } - for(String pn : forUpn.value) { + for (String pn : forUpn.value) { Result decoded = PermDAO.Data.decodeToArray(trans, this, pn); - if(decoded.isOKhasData()) { + if (decoded.isOKhasData()) { nss.add(decoded.value[0]); } else { trans.error().log(pn,", derived from a Role, is invalid:",decoded.errorString()); @@ -255,11 +255,11 @@ public class Question { List rlpUser = new ArrayList<>(); Result rpdd; PermDAO.Data pdd; - for(String pn : plPermNames.value) { + for (String pn : plPermNames.value) { rpdd = PermDAO.Data.decode(trans, this, pn); - if(rpdd.isOKhasData()) { + if (rpdd.isOKhasData()) { pdd=rpdd.value; - if(nss==null || nss.contains(pdd.ns)) { + if (nss==null || nss.contains(pdd.ns)) { rlpUser.add(pdd); } } else { @@ -314,7 +314,7 @@ public class Question { return Result.err(pr); } - if(lookup) { + if (lookup) { Result> rlpd = permDAO.read(trans, pr.value); if (rlpd.isOKhasData()) { for (PermDAO.Data pData : rlpd.value) { @@ -368,7 +368,7 @@ public class Question { return Result.ok(r.value.get(0)); } else { int dot; - if(child==null) { + if (child==null) { return Result.err(Status.ERR_NsNotFound, "No Namespace"); } else { dot = child.lastIndexOf('.'); @@ -384,12 +384,12 @@ public class Question { public Result deriveFirstNsForType(AuthzTrans trans, String str, NsType type) { NsDAO.Data nsd; - for(String lookup = str;!".".equals(lookup) && lookup!=null;) { + for (String lookup = str;!".".equals(lookup) && lookup!=null;) { Result> rld = nsDAO.read(trans, lookup); - if(rld.isOKhasData()) { + if (rld.isOKhasData()) { nsd=rld.value.get(0); lookup = nsd.parent; - if(type.type == nsd.type) { + if (type.type == nsd.type) { return Result.ok(nsd); } } else { @@ -455,13 +455,13 @@ public class Question { 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 + 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)) { + if (!trans.org().getDomain().equals(ns)) { Result> rlnsd = nsDAO.read(trans, ns); if (rlnsd.isOKhasData()) { return Result.ok(rlnsd.value.get(0)); @@ -490,7 +490,7 @@ public class Question { Result rv = mayUserVirtueOfNS(trans, user, ndd, ":" + ndd.name + ":ns", access.name()); if (rv.isOK()) { return rv; - } else if(rv.status==Result.ERR_Backend) { + } 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]", @@ -532,7 +532,7 @@ public class Question { + rdd.ns + roleInst, access.name()); if (rnsd.isOK()) { return rnsd; - } else if(rnsd.status==Result.ERR_Backend) { + } else if (rnsd.status==Result.ERR_Backend) { return Result.err(rnsd); } @@ -543,7 +543,7 @@ public class Question { ":" + rdd.ns + ":ns", access.name()); if (rv.isOK()) { return rv; - } else if(rnsd.status==Result.ERR_Backend) { + } else if (rnsd.status==Result.ERR_Backend) { return Result.err(rnsd); } else { return Result.err(Status.ERR_Denied, "[%s] may not %s Role [%s]", @@ -582,7 +582,7 @@ public class Question { Result rnsd = mayUserVirtueOfNS(trans, user, ndd, ":" + pdd.ns + permInst, access.name()); if (rnsd.isOK()) { return rnsd; - } else if(rnsd.status==Result.ERR_Backend) { + } else if (rnsd.status==Result.ERR_Backend) { return Result.err(rnsd); } @@ -603,7 +603,7 @@ public class Question { 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()) { + 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); @@ -663,7 +663,7 @@ public class Question { Result> rurd; if ((rurd = userRoleDAO.readUserInRole(trans, user, ns+DOT_ADMIN)).isOKhasData()) { return Result.ok(nsd); - } else if(rurd.status==Result.ERR_Backend) { + } else if (rurd.status==Result.ERR_Backend) { return Result.err(rurd); } @@ -679,12 +679,12 @@ public class Question { 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) { + } 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) { + } else if (rnsd.status==Result.ERR_Backend) { return Result.err(rnsd); } } @@ -712,7 +712,7 @@ public class Question { 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 + if (PermEval.evalAction(pd.action, action)) { // don't return action here, might miss other action return true; } } @@ -733,7 +733,7 @@ public class Question { } Result rv = null; - if(result.isOK()) { + if (result.isOK()) { if (result.isEmpty()) { rv = Result.err(Status.ERR_UserNotFound, user); if (willSpecialLog(trans,user)) { @@ -743,14 +743,14 @@ public class Question { 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) { + 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) { + 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) { + if (cddl.size()>1) { Collections.sort(cddl,new Comparator() { @Override public int compare(org.onap.aaf.auth.dao.cass.CredDAO.Data a, @@ -766,7 +766,7 @@ public class Question { Date expired = null; StringBuilder debug = willSpecialLog(trans,user)?new StringBuilder():null; for (CredDAO.Data cdd : cddl) { - if(!cdd.id.equals(user)) { + if (!cdd.id.equals(user)) { trans.error().log("doesUserCredMatch DB call does not match for user: " + user); } if (cdd.expires.after(now)) { @@ -776,7 +776,7 @@ public class Question { switch(cdd.type) { case CredDAO.BASIC_AUTH: byte[] md5=Hash.hashMD5(cred); - if(Hash.compareTo(md5,dbcred)==0) { + if (Hash.compareTo(md5,dbcred)==0) { checkLessThanDays(trans,7,now,cdd); return Result.ok(cdd.expires); } else if (debug!=null) { @@ -789,7 +789,7 @@ public class Question { bb.put(cred); byte[] hash = Hash.hashSHA256(bb.array()); - if(Hash.compareTo(hash,dbcred)==0) { + if (Hash.compareTo(hash,dbcred)==0) { checkLessThanDays(trans,7,now,cdd); return Result.ok(cdd.expires); } else if (debug!=null) { @@ -803,17 +803,17 @@ public class Question { trans.error().log(e); } } else { - if(expired==null || expired.before(cdd.expires)) { + if (expired==null || expired.before(cdd.expires)) { expired = cdd.expires; } } } // end for each - if(debug==null) { + 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) { + 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)); @@ -840,7 +840,7 @@ public class Question { 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) { + if (cred.type==CredDAO.RAW) { TimeTaken tt = trans.start("Hash Cred", Env.SUB); try { cred.type = CredDAO.BASIC_AUTH_SHA256; @@ -935,32 +935,32 @@ public class Question { if (all || NsDAO.TABLE.equals(cname)) { int seg[] = series(NsDAO.CACHE_SEG); - for(int i: seg) {cacheClear(trans, NsDAO.TABLE,i);} + 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);} + 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);} + 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);} + 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);} + 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);} + for (int i: seg) {cacheClear(trans, CertDAO.TABLE,i);} rv = cacheInfoDAO.touch(trans, CertDAO.TABLE,seg); } @@ -999,11 +999,11 @@ public class Question { public boolean isDelegated(AuthzTrans trans, String user, String approver, Map>> rldd ) { Result> userDelegatedFor = rldd.get(user); - if(userDelegatedFor==null) { + if (userDelegatedFor==null) { userDelegatedFor=delegateDAO.readByDelegate(trans, user); rldd.put(user, userDelegatedFor); } - if(userDelegatedFor.isOKhasData()) { + if (userDelegatedFor.isOKhasData()) { for (DelegateDAO.Data curr : userDelegatedFor.value) { if (curr.user.equals(approver) && curr.delegate.equals(user) && curr.expires.after(new Date())) { @@ -1016,8 +1016,8 @@ public class Question { 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) { + if (b==null) { // we haven't evaluated in this trans for Special Log yet + if (specialLog==null) { return false; } else { b = specialLog.contains(user); @@ -1042,21 +1042,21 @@ public class Question { specialLog = new HashSet<>(); } boolean rc = specialLog.add(id); - if(rc) { + 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) { + if (specialLog==null) { return false; } boolean rv = specialLog.remove(id); if (specialLog.isEmpty()) { specialLog = null; } - if(rv) { + if (rv) { trans.trace().printf("Trace off for %s requested by %s",id,trans.user()); } return rv; @@ -1086,8 +1086,8 @@ public class Question { 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)) { + if (rur.isOKhasData()) {for (UserRoleDAO.Data urdd : rur.value){ + if (urdd.expires.after(now)) { return true; } }}; @@ -1097,8 +1097,8 @@ public class Question { 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)) { + if (rur.isOKhasData()) {for (UserRoleDAO.Data urdd : rur.value){ + if (urdd.expires.after(now)) { return true; } }}; @@ -1109,8 +1109,8 @@ public class Question { 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)) { + if (rur.isOKhasData()) {for (UserRoleDAO.Data urdd : rur.value){ + if (urdd.expires.after(now)) { ++count; } }}; @@ -1129,7 +1129,7 @@ public class Question { byte[] from = name.getBytes(); StringBuilder sb = new StringBuilder(); byte f; - for(int i=0;i>4)+0x61)); sb.append((char)((f&0x0F)+0x61)); @@ -1141,7 +1141,7 @@ public class Question { byte[] from = name.getBytes(); StringBuilder sb = new StringBuilder(); char c; - for(int i=0;i { super(env.access(), name, 1000L /* Don't hit DB more than once a second */); this.env = env; this.ldao = ldao; - if(version!=null) { + 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]);} + 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); } @@ -83,13 +83,13 @@ public class DirectAAFLocator extends AbsAAFLocator { public boolean refresh() { AuthzTrans trans = env.newTransNoAvg(); Result> rl = ldao.readByName(trans, name); - if(rl.isOK()) { + if (rl.isOK()) { LinkedList epl = new LinkedList<>(); - for(Data d : rl.value) { -// if(myhostname!=null && d.port==myport && d.hostname.equals(myhostname)) { + for (Data d : rl.value) { +// if (myhostname!=null && d.port==myport && d.hostname.equals(myhostname)) { // continue; // } - if((major<0 || major==d.major) && + if ((major<0 || major==d.major) && (minor<0 || minor<=d.minor) && (patch<0 || patch==d.patch) && (pkg<0 || pkg ==d.pkg)) { @@ -104,7 +104,7 @@ public class DirectAAFLocator extends AbsAAFLocator { endpoint.setLatitude(d.latitude); endpoint.setLongitude(d.longitude); endpoint.setProtocol(d.protocol); - for(String s : d.subprotocol(false)) { + for (String s : d.subprotocol(false)) { endpoint.getSubprotocol().add(s); } 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 75f6c7a5..59613961 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 @@ -61,10 +61,10 @@ public class DirectAAFLur implements Lur { Result> pdr = question.getPermsByUser(trans, bait.getName(),false); switch(pdr.status) { case OK: - for(PermDAO.Data d : pdr.value) { - if(!rv) { + for (PermDAO.Data d : pdr.value) { + if (!rv) { for (Permission p : pond) { - if(new PermPermission(d).match(p)) { + if (new PermPermission(d).match(p)) { rv=true; break; } @@ -86,7 +86,7 @@ public class DirectAAFLur implements Lur { Result> pdr = question.getPermsByUser(env.newTrans(), bait.getName(),false); switch(pdr.status) { case OK: - for(PermDAO.Data d : pdr.value) { + for (PermDAO.Data d : pdr.value) { permissions.add(new PermPermission(d)); } break; @@ -135,23 +135,23 @@ public class DirectAAFLur implements Lur { @Override public boolean match(Permission p) { - if(p==null) { + if (p==null) { return false; } PermDAO.Data pd; - if(p instanceof DirectAAFLur.PermPermission) { + 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))) + 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))) + 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; @@ -180,9 +180,9 @@ public class DirectAAFLur implements Lur { @Override public Permission createPerm(String p) { String[] params = Split.split('|', p); - if(params.length==3) { + if (params.length==3) { Result nss = question.deriveNsSplit(NullTrans.singleton(), params[0]); - if(nss.isOK()) { + if (nss.isOK()) { return new PermPermission(nss.value.ns,nss.value.name,params[1],params[2]); } } 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 9d4cd05f..3ef532b4 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 @@ -54,12 +54,12 @@ public class DirectAAFUserPass implements CredVal { public boolean validate(String user, Type type, byte[] pass, Object state) { try { AuthzTrans trans; - if(state !=null) { - if(state instanceof AuthzTrans) { + if (state !=null) { + if (state instanceof AuthzTrans) { trans = (AuthzTrans)state; } else { trans = env.newTransNoAvg(); - if(state instanceof HttpServletRequest) { + if (state instanceof HttpServletRequest) { trans.set((HttpServletRequest)state); } } 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 6dd5e006..f3351dae 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 @@ -53,10 +53,10 @@ public class DirectCertIdentity implements CertIdentity { @Override public TaggedPrincipal identity(HttpServletRequest req, X509Certificate cert, byte[] _certBytes) throws CertificateException { byte[] certBytes = _certBytes; - if(cert==null && certBytes==null) { + if (cert==null && certBytes==null) { return null; } - if(certBytes==null) { + if (certBytes==null) { certBytes = cert.getEncoded(); } byte[] fingerprint = X509Taf.getFingerPrint(certBytes); @@ -64,7 +64,7 @@ public class DirectCertIdentity implements CertIdentity { AuthzTrans trans = (AuthzTrans) req.getAttribute(TransFilter.TRANS_TAG); Result> cresp = certDAO.read(trans, ByteBuffer.wrap(fingerprint)); - if(cresp.isOKhasData()) { + if (cresp.isOKhasData()) { Data cdata = cresp.value.get(0); return new X509Principal(cdata.id,cert,certBytes,null); } 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 caededa2..aa6bf8c5 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 @@ -40,7 +40,7 @@ public class DirectLocatorCreator implements AbsAAFLocator.LocatorCreator { @Override public AbsAAFLocator create(String key, String version) throws LocatorException { DirectAAFLocator dal = new DirectAAFLocator(env,locateDAO,key,version); - if(myhostname!=null) { + if (myhostname!=null) { dal.setSelf(myhostname, myport); } return dal; 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 da7044cf..9eea77e3 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 @@ -45,14 +45,14 @@ public class DirectRegistrar implements Registrant { try { String latitude = access.getProperty(Config.CADI_LATITUDE, null); - if(latitude==null) { + if (latitude==null) { latitude = access.getProperty("AFT_LATITUDE", null); } String longitude = access.getProperty(Config.CADI_LONGITUDE, null); - if(longitude==null) { + if (longitude==null) { longitude = access.getProperty("AFT_LONGITUDE", null); } - if(latitude==null || 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); @@ -64,18 +64,18 @@ public class DirectRegistrar implements Registrant { 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) { + if (locate.hostname==null) { locate.hostname = access.getProperty(Config.HOSTNAME, null); } - if(locate.hostname==null) { + if (locate.hostname==null) { locate.hostname = Inet4Address.getLocalHost().getHostName(); } String subprotocols = access.getProperty(Config.CADI_PROTOCOLS, null); - if(subprotocols==null) { + if (subprotocols==null) { locate.protocol="http"; } else { locate.protocol="https"; - for(String s : Split.split(',', subprotocols)) { + for (String s : Split.split(',', subprotocols)) { locate.subprotocol(true).add(s); } } @@ -87,7 +87,7 @@ public class DirectRegistrar implements Registrant { @Override public Result update(AuthzEnv env) { org.onap.aaf.auth.layer.Result dr = ldao.update(env.newTransNoAvg(), locate); - if(dr.isOK()) { + if (dr.isOK()) { return Result.ok(200, null); } else { return Result.err(503, dr.errorString()); @@ -100,7 +100,7 @@ public class DirectRegistrar implements Registrant { @Override public Result cancel(AuthzEnv env) { org.onap.aaf.auth.layer.Result dr = ldao.delete(env.newTransNoAvg(), locate, false); - if(dr.isOK()) { + 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 0dd03da4..7cc8bd67 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 @@ -121,14 +121,14 @@ public class JU_Cached { // 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)) { +// 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 +// 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){ +//// } else if (rld.status == Result.ERR_Backend){ //// map.remove(key); // } // } 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 692c3a82..dea2ccdd 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 @@ -67,13 +67,13 @@ public class AbsJUCass { @BeforeClass public static void startup() throws APIException, IOException { synchronized(AUTHZ) { - if(env==null) { + 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()) { + if (f.exists()) { is = new FileInputStream(f); } else { URL rsrc = ClassLoader.getSystemResource(resource); @@ -81,7 +81,7 @@ public class AbsJUCass { } props.load(is); } finally { - if(is==null) { + if (is==null) { env= new AuthzEnv(); Assert.fail(resource + " must exist in etc dir, or in Classpath"); } @@ -95,7 +95,7 @@ public class AbsJUCass { env.info().log("Connecting to Cluster"); try { cluster.connect(AUTHZ); - } catch(Exception e) { + } catch (Exception e) { cluster=null; env.error().log(e); Assert.fail("Not able to connect to DB: " + e.getLocalizedMessage()); @@ -114,7 +114,7 @@ public class AbsJUCass { @AfterClass public static void shutdown() { - if(cluster!=null) { + if (cluster!=null) { cluster.close(); cluster = null; } @@ -129,10 +129,10 @@ public class AbsJUCass { @After public void auditTrail() { - if(totals==0) { // "updateTotals()" was not called... just do one Trans + 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) { + if (details) { env.info().log( sb, "Total time:", @@ -159,7 +159,7 @@ public class AbsJUCass { @AfterClass public static void print() { float transTime; - if(iterations==0) { + if (iterations==0) { transTime=totals; } else { transTime=totals/iterations; 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 c91bfe1e..7e460899 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 @@ -78,12 +78,12 @@ public class JU_Bytification { assertEquals(a.type,b.type); // assertEquals(a.admin.size(),b.admin.size()); -// for(String s: a.admin) { +// for (String s: a.admin) { // assertTrue(b.admin.contains(s)); // } // // assertEquals(a.responsible.size(),b.responsible.size()); -// for(String s: a.responsible) { +// for (String s: a.responsible) { // assertTrue(b.responsible.contains(s)); // } } @@ -105,7 +105,7 @@ public class JU_Bytification { // Overshoot Buffer StringBuilder sb = new StringBuilder(300); sb.append("role|instance|veryLongAction..."); - for(int i=0;i<280;++i) { + for (int i=0;i<280;++i) { sb.append('a'); } rd1.perms(true).add(sb.toString()); @@ -123,7 +123,7 @@ public class JU_Bytification { check(rd1,rd2); // 1000 Perms - for(int i=0;i<1000;++i) { + for (int i=0;i<1000;++i) { rd1.perms(true).add("com|inst|action"+ i); } @@ -139,7 +139,7 @@ public class JU_Bytification { assertEquals(a.name,b.name); assertEquals(a.perms.size(),b.perms.size()); - for(String s: a.perms) { + for (String s: a.perms) { assertTrue(b.perms.contains(s)); } } @@ -169,7 +169,7 @@ public class JU_Bytification { check(pd1,rd2); // 1000 Perms - for(int i=0;i<1000;++i) { + for (int i=0;i<1000;++i) { pd1.roles(true).add("org.osaaf..my.Role"+ i); } @@ -187,7 +187,7 @@ public class JU_Bytification { assertEquals(a.action,b.action); assertEquals(a.roles.size(),b.roles.size()); - for(String s: a.roles) { + for (String s: a.roles) { assertTrue(b.roles.contains(s)); } } @@ -252,7 +252,7 @@ public class JU_Bytification { assertEquals(a.id,b.id); assertEquals(a.ns,b.ns); assertEquals(a.type,b.type); - if(a.cred==null) { + if (a.cred==null) { assertEquals(a.cred,b.cred); } else { int l = a.cred.limit(); diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/aaf/test/JU_NsType.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/aaf/test/JU_NsType.java index 33b67429..05195eeb 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/aaf/test/JU_NsType.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/aaf/test/JU_NsType.java @@ -38,7 +38,7 @@ public class JU_NsType { public void test() { NsType nt,nt2; String[] tests = new String[] {"DOT","ROOT","COMPANY","APP","STACKED_APP","STACK"}; - for(String s : tests) { + for (String s : tests) { nt = NsType.valueOf(s); assertEquals(s,nt.name()); diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/AAF_CM.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/AAF_CM.java index d80b085b..15e298b7 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/AAF_CM.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/AAF_CM.java @@ -97,7 +97,7 @@ public class AAF_CM extends AbsService { aafAuthn = aafCon().newAuthn(aafLurPerm); String aaf_env = env.getProperty(Config.AAF_ENV); - if(aaf_env==null) { + if (aaf_env==null) { throw new APIException("aaf_env needs to be set"); } @@ -112,17 +112,17 @@ public class AAF_CM extends AbsService { // 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()) { + for (Entry es : env.access().getProperties().entrySet()) { String key = es.getKey().toString(); - if(key.startsWith(CA.CM_CA_PREFIX)) { + if (key.startsWith(CA.CM_CA_PREFIX)) { int idx = key.indexOf('.'); - if(idx==key.lastIndexOf('.')) { // else it's a regular property + 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) { + if (segs.length>0) { String[][] multiParams = new String[segs.length-1][]; - for(int i=0;i { } } } - if(certAuths.size()==0) { + if (certAuths.size()==0) { throw new APIException("No Certificate Authorities have been configured in CertMan"); } @@ -152,7 +152,7 @@ public class AAF_CM extends AbsService { synchronized(env) { - if(cacheUser == null) { + if (cacheUser == null) { cacheUser = Cache.obtain(USER_PERMS); Cache.startCleansing(env, USER_PERMS); } @@ -184,7 +184,7 @@ public class AAF_CM extends AbsService { 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()); + 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,"*/*"); 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 34f7927e..a3a30607 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 @@ -52,7 +52,7 @@ public class API_Artifact { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result r = context.createArtifacts(trans, req, resp); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.CREATED_201); } else { context.error(trans,resp,r); @@ -67,7 +67,7 @@ public class API_Artifact { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result r = context.readArtifacts(trans, req, resp); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { context.error(trans,resp,r); @@ -81,7 +81,7 @@ public class API_Artifact { 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()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { context.error(trans,resp,r); @@ -94,7 +94,7 @@ public class API_Artifact { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result r = context.updateArtifacts(trans, req, resp); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { context.error(trans,resp,r); @@ -107,7 +107,7 @@ public class API_Artifact { 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()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { context.error(trans,resp,r); @@ -120,7 +120,7 @@ public class API_Artifact { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result r = context.deleteArtifacts(trans, req, resp); - if(r.isOK()) { + 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 625fed62..68354413 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 @@ -63,12 +63,12 @@ public class API_Cert { public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { String key = pathParam(req, ":ca"); CA ca; - if((ca = aafCM.getCA(key))==null) { + 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()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { context.error(trans,resp,r); @@ -82,12 +82,12 @@ public class API_Cert { public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { String key = pathParam(req, ":ca"); CA ca; - if((ca = aafCM.getCA(key))==null) { + 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()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { context.error(trans,resp,r); @@ -104,7 +104,7 @@ public class API_Cert { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result r = context.check(trans, resp, pathParam(req,"perm")); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { trans.checkpoint(r.errorString()); @@ -125,7 +125,7 @@ public class API_Cert { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result r = context.readCertsByMechID(trans, resp, pathParam(req,"id")); - if(r.isOK()) { + 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/ca/CA.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/CA.java index 820f02d1..881c9bea 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 @@ -71,7 +71,7 @@ public abstract class CA { this.env = env; permNS = CM_CA_PREFIX + name; permType = access.getProperty(permNS + ".perm_type",null); - if(permType==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)); @@ -79,22 +79,22 @@ public abstract class CA { String tag = CA.CM_CA_PREFIX+caName+CA.CM_CA_BASE_SUBJECT; String fields = access.getProperty(tag, null); - if(fields==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 + 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) { + 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(", "); @@ -103,31 +103,31 @@ public abstract class CA { sb.append(s); } } - if(sb!=null) { + 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) { + if (dataDir!=null) { File data = new File(dataDir); byte[] bytes; - if(data.exists()) { + if (data.exists()) { String trustCas = access.getProperty(CM_TRUST_CAS,null); - if(trustCas!=null) { - for(String fname : Split.splitTrim(',', trustCas)) { + if (trustCas!=null) { + for (String fname : Split.splitTrim(',', trustCas)) { File crt; - if(fname.contains("/")) { + if (fname.contains("/")) { crt = new File(fname); } else { crt = new File(data,fname); } - if(crt.exists()) { + 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) { + if (read>0) { addTrustedCA(new String(bytes)); } } finally { @@ -148,13 +148,13 @@ public abstract class CA { protected void addCaIssuerDN(String issuerDN) { boolean changed = true; - for(String id : caIssuerDNs) { - if(id.equals(issuerDN)) { + for (String id : caIssuerDNs) { + if (id.equals(issuerDN)) { changed = false; break; } } - if(changed) { + if (changed) { String[] newsa = new String[caIssuerDNs.length+1]; newsa[0]=issuerDN; System.arraycopy(caIssuerDNs, 0, newsa, 1, caIssuerDNs.length); @@ -164,13 +164,13 @@ public abstract class CA { protected synchronized void addTrustedCA(final String crtString) { String crt; - if(crtString.endsWith("\n")) { + if (crtString.endsWith("\n")) { crt = crtString; } else { crt = crtString + '\n'; } - for(int i=0;i=0) { + if (at>=0) { return idDomains.contains(p.getName().substring(at+1)); } else { return false; 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 000b6dd5..bc81fc43 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 @@ -75,10 +75,10 @@ public class JscepCA extends CA { mxcwiS = new ConcurrentHashMap<>(); mxcwiC = new ConcurrentHashMap<>(); - if(params.length<2) { + if (params.length<2) { throw new CertException("No Trust Chain parameters are included"); } - if(params[0].length<2) { + if (params[0].length<2) { throw new CertException("User/Password required for JSCEP"); } final String id = params[0][0]; @@ -98,21 +98,21 @@ public class JscepCA extends CA { StringBuilder urlstr = new StringBuilder(); - for(int i=1;i1) { + if (i>1) { urlstr.append(','); // delimiter } urlstr.append(params[i][0]); String dir = access.getProperty(CM_PUBLIC_DIR, ""); - if(!"".equals(dir) && !dir.endsWith("/")) { + if (!"".equals(dir) && !dir.endsWith("/")) { dir = dir + '/'; } String path; List frs = new ArrayList<>(params.length-1); try { - for(int j=1; j=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()) { + if (f.exists() && f.isFile()) { String fileName = f.getName(); - if(fileName.endsWith(".key")) { + 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("/")) { + 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")) { + if (fileName.endsWith(".pkcs11")) { String ksType="PKCS11"; p = Factory.getSecurityProvider(ksType,params); keyStore = KeyStore.getInstance(ksType,p); - } else if(fileName.endsWith(".jks")) { + } else if (fileName.endsWith(".jks")) { keyStore = KeyStore.getInstance("JKS"); fis = new FileInputStream(f); - } else if(fileName.endsWith(".p12") || fileName.endsWith(".pkcs12")) { + } else if (fileName.endsWith(".p12") || fileName.endsWith(".pkcs12")) { keyStore = KeyStore.getInstance("PKCS12"); fis = new FileInputStream(f); } else { @@ -151,7 +151,7 @@ public class LocalCA extends CA { try { String pass = access.decrypt(params[0][2]/*encrypted passcode*/, true); - if(pass==null) { + if (pass==null) { throw new CertException("Passcode for " + fileName + " cannot be decrypted."); } char[] ksPass = pass.toCharArray(); @@ -164,12 +164,12 @@ public class LocalCA extends CA { fis.close(); } Entry entry; - if(fileName.endsWith(".pkcs11")) { + if (fileName.endsWith(".pkcs11")) { entry = keyStore.getEntry(params[0][1]/*alias*/, null); } else { entry = keyStore.getEntry(params[0][1]/*alias*/, keyPass); } - if(entry==null) { + if (entry==null) { throw new CertException("There is no Keystore entry with name '" + params[0][1] +'\''); } PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry)entry; @@ -188,7 +188,7 @@ public class LocalCA extends CA { X500NameBuilder xnb = new X500NameBuilder(); List rp = RDN.parse(',', x509cwi.getIssuerDN()); Collections.reverse(rp); - for(RDN rnd : rp) { + for (RDN rnd : rp) { xnb.addRDN(rnd.aoi,rnd.value); } issuer = xnb.build(); @@ -226,7 +226,7 @@ public class LocalCA extends CA { // new SubjectPublicKeyInfo(ASN1Sequence.getInstance(caCert.getPublicKey().getEncoded())) ); List lsan = new ArrayList<>(); - for(String s : csrmeta.sans()) { + for (String s : csrmeta.sans()) { lsan.add(new GeneralName(GeneralName.dNSName,s)); } GeneralName[] sans = new GeneralName[lsan.size()]; 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 e51f2faa..2ef6da55 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 @@ -45,8 +45,8 @@ public class X509ChainWithIssuer extends X509andChain { // Trust Chain. Last one should be the CA Collection certs; X509Certificate x509; - for(Reader rdr : rdrs) { - if(rdr==null) { // cover for badly formed array + for (Reader rdr : rdrs) { + if (rdr==null) { // cover for badly formed array continue; } @@ -56,13 +56,13 @@ public class X509ChainWithIssuer extends X509andChain { } catch (CertificateException e) { throw new CertException(e); } - for(Certificate c : certs) { + for (Certificate c : certs) { x509=(X509Certificate)c; Principal subject = x509.getSubjectDN(); - if(subject==null) { + if (subject==null) { continue; } - if(cert==null) { // first in Trust Chain + if (cert==null) { // first in Trust Chain issuerDN = subject.toString(); cert=x509; // adding each time makes sure last one is signer. } @@ -73,12 +73,12 @@ public class X509ChainWithIssuer extends X509andChain { public X509ChainWithIssuer(Certificate[] certs) throws IOException, CertException { X509Certificate x509; - for(int i=certs.length-1; i>=0; --i) { + for (int i=certs.length-1; i>=0; --i) { x509=(X509Certificate)certs[i]; Principal subject = x509.getSubjectDN(); - if(subject!=null) { + if (subject!=null) { addTrustChainEntry(x509); - if(i==0) { // last one is signer + if (i==0) { // last one is signer cert=x509; issuerDN= subject.toString(); } 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 3c684db2..7eb88bd2 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 @@ -58,7 +58,7 @@ public class X509andChain { public void addTrustChainEntry(X509Certificate x509) throws IOException, CertException { - if(trustChain==null) { + if (trustChain==null) { trustChain = new String[] {Factory.toString(NullTrans.singleton(),x509)}; } else { String[] temp = new String[trustChain.length+1]; 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 8edfa634..b84816ab 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 @@ -65,7 +65,7 @@ public class BCFactory extends Factory { } public static String toString(PKCS10CertificationRequest csr) throws IOException, CertException { - if(csr==null) { + if (csr==null) { throw new CertException("x509 Certificate Request not built"); } return textBuilder("CERTIFICATE REQUEST",csr.getEncoded()); @@ -94,8 +94,8 @@ public class BCFactory extends Factory { CSRMeta csr = ca.newCSRMeta(); boolean first = true; // Set CN (and SAN) - for(String fqdn : fqdns) { - if(first) { + for (String fqdn : fqdns) { + if (first) { first = false; csr.cn(fqdn); } @@ -106,7 +106,7 @@ public class BCFactory extends Factory { csr.mechID(mechid); csr.email(sponsorEmail); String errs; - if((errs=validateApp(csr))!=null) { + if ((errs=validateApp(csr))!=null) { throw new CertException(errs); } return csr; @@ -114,7 +114,7 @@ public class BCFactory extends Factory { private static String validateApp(CSRMeta csr) { CertmanValidator v = new CertmanValidator(); - if(v.nullOrBlank("cn", csr.cn()) + if (v.nullOrBlank("cn", csr.cn()) .nullOrBlank("mechID", csr.mechID()) // .nullOrBlank("email", csr.email()) .err()) { @@ -130,7 +130,7 @@ public class BCFactory extends Factory { csr.challenge(new String(Symm.randomGen(24))); csr.email(email); String errs; - if((errs=validatePersonal(csr))!=null) { + if ((errs=validatePersonal(csr))!=null) { throw new CertException(errs); } return csr; @@ -138,7 +138,7 @@ public class BCFactory extends Factory { private static String validatePersonal(CSRMeta csr) { CertmanValidator v = new CertmanValidator(); - if(v.nullOrBlank("cn", csr.cn()) + if (v.nullOrBlank("cn", csr.cn()) .nullOrBlank("email", csr.email()) .err()) { return v.errs(); 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 5df439ab..a3740bfe 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 @@ -70,18 +70,18 @@ public class CSRMeta { } public X500Name x500Name() { - if(name==null) { + if (name==null) { X500NameBuilder xnb = new X500NameBuilder(); xnb.addRDN(BCStyle.CN,cn); xnb.addRDN(BCStyle.E,email); - if(mechID!=null) { - if(environment==null) { + if (mechID!=null) { + if (environment==null) { xnb.addRDN(BCStyle.OU,mechID); } else { xnb.addRDN(BCStyle.OU,mechID+':'+environment); } } - for(RDN rdn : rdns) { + for (RDN rdn : rdns) { xnb.addRDN(rdn.aoi,rdn.value); } name = xnb.build(); @@ -92,16 +92,16 @@ public class CSRMeta { public PKCS10CertificationRequest generateCSR(Trans trans) throws IOException, CertException { PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(x500Name(),keypair(trans).getPublic()); - if(challenge!=null) { + 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()) { + if (!sanList.isEmpty()) { GeneralName[] gna = new GeneralName[sanList.size()+plus]; int i=-1; - for(String s : sanList) { + for (String s : sanList) { gna[++i]=new GeneralName(GeneralName.dNSName,s); } gna[++i]=new GeneralName(GeneralName.rfc822Name,email); @@ -132,17 +132,17 @@ public class CSRMeta { 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++) { + for (int k=0; k < names.length; k++) { String title = ""; - if(names[k].getTagNo() == GeneralName.dNSName) { + if (names[k].getTagNo() == GeneralName.dNSName) { title = "dNSName"; - } else if(names[k].getTagNo() == GeneralName.iPAddress) { + } 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) { + } else if (names[k].getTagNo() == GeneralName.otherName) { title = "otherName"; - } else if(names[k].getTagNo() == GeneralName.rfc822Name) { + } else if (names[k].getTagNo() == GeneralName.rfc822Name) { title = "email"; } @@ -180,7 +180,7 @@ public class CSRMeta { public KeyPair keypair(Trans trans) { - if(keyPair == null) { + if (keyPair == null) { keyPair = Factory.generateKeyPair(trans); } return keyPair; 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 c39ba6d3..f57c837a 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 @@ -69,19 +69,19 @@ public class RDN { List lrnd = new ArrayList<>(); StringBuilder sb = new StringBuilder(); boolean inQuotes = false; - for(int i=0;i0) { + } else if (delim==c) { + if (sb.length()>0) { lrnd.add(new RDN(sb.toString())); sb.setLength(0); } @@ -90,7 +90,7 @@ public class RDN { } } } - if(sb.indexOf("=")>0) { + if (sb.indexOf("=")>0) { lrnd.add(new RDN(sb.toString())); } return lrnd; 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 310ea8b2..e05b2a27 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 @@ -115,7 +115,7 @@ public abstract class FacadeImpl extends org.onap.aaf. (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")) { + 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,*/*"; @@ -206,7 +206,7 @@ public abstract class FacadeImpl extends org.onap.aaf. "] " + holder.toString(), Env.ALWAYS); - if(hidemsg) { + if (hidemsg) { holder.setLength(0); em = mapper().errorFromMessage(holder, msgId, "Server had an issue processing this request"); } @@ -231,7 +231,7 @@ public abstract class FacadeImpl extends org.onap.aaf. default: return Result.err(Result.ERR_BadData,"Invalid Perm String"); } - if(certman.aafLurPerm.fish(trans.getUserPrincipal(), ap)) { + if (certman.aafLurPerm.fish(trans.getUserPrincipal(), ap)) { resp.setContentType(voidResp); resp.getOutputStream().write(0); return Result.ok(); @@ -253,13 +253,13 @@ public abstract class FacadeImpl extends org.onap.aaf. try { Data rd = certRequestDF.newData().load(req.getInputStream()); request = rd.asObject(); - } catch(APIException e) { + } 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()) { + if (rcr.notOK()) { return Result.err(rcr); } @@ -291,7 +291,7 @@ public abstract class FacadeImpl extends org.onap.aaf. 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()) { +// if (rcr.notOK()) { // return Result.err(rcr); // } else { // try { @@ -308,17 +308,17 @@ public abstract class FacadeImpl extends org.onap.aaf. // zos.closeEntry(); // // String wt; -// if((wt=req.getParameter("withTrust"))!=null || TRUE.equalsIgnoreCase(wt)) { +// if ((wt=req.getParameter("withTrust"))!=null || TRUE.equalsIgnoreCase(wt)) { // zos.putNextEntry(new ZipEntry(trans.user()+".trustCrts")); -// for(String s : ca.getTrustChain()) { +// 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) { +// 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")); @@ -337,7 +337,7 @@ public abstract class FacadeImpl extends org.onap.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) { +// if (withJKS) { // ps.println("chmod 600 " + trans.user() + ".jks"); // } // ps.println("cd $THE_PWD"); @@ -362,7 +362,7 @@ public abstract class FacadeImpl extends org.onap.aaf. // // Get the Cert(s)... Might include Trust store // List lcerts = new ArrayList<>(); // lcerts.add(cr.asCertString()); -// for(String s : trustChain) { +// for (String s : trustChain) { // lcerts.add(s); // } // @@ -377,7 +377,7 @@ public abstract class FacadeImpl extends org.onap.aaf. // jks.setEntry(name, pkEntry, protParam); // // int i=0; -// for(X509Certificate x509 : certs) { +// for (X509Certificate x509 : certs) { // jks.setCertificateEntry("cert_"+ ++i, x509); // } // return jks; @@ -391,7 +391,7 @@ public abstract class FacadeImpl extends org.onap.aaf. try { Data rd = certRenewDF.newData().load(req.getInputStream()); request = rd.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN,RENEW_CERT); return Result.err(Result.ERR_BadData,"Invalid Input"); } @@ -427,7 +427,7 @@ public abstract class FacadeImpl extends org.onap.aaf. try { Data rd = certDropDF.newData().load(req.getInputStream()); request = rd.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN,DROP_CERT); return Result.err(Result.ERR_BadData,"Invalid Input"); } @@ -485,7 +485,7 @@ public abstract class FacadeImpl extends org.onap.aaf. try { Data rd = artiDF.newData().load(req.getInputStream()); arti = rd.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN,CREATE_ARTIFACTS); return Result.err(Result.ERR_BadData,"Invalid Input"); } @@ -509,23 +509,23 @@ public abstract class FacadeImpl extends org.onap.aaf. String ns = req.getParameter("ns"); Result ra; - if( machine !=null && mechid == null) { + if ( machine !=null && mechid == null) { ra = mapper.fromArtifacts(service.readArtifactsByMachine(trans, machine)); - } else if(mechid!=null && machine==null) { + } else if (mechid!=null && machine==null) { ra = mapper.fromArtifacts(service.readArtifactsByMechID(trans, mechid)); - } else if(mechid!=null && machine!=null) { + } 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) { + } else if (ns!=null) { ra = mapper.fromArtifacts(service.readArtifactsByNs(trans, ns)); } else { ra = Result.err(Status.ERR_BadData,"Invalid request inputs"); } - if(ra.isOK()) { + if (ra.isOK()) { RosettaData data = artiDF.newData(trans).load(ra.value); data.to(resp.getOutputStream()); setContentType(resp,artiDF.getOutType()); @@ -550,7 +550,7 @@ public abstract class FacadeImpl extends org.onap.aaf. add.mechid = mechid; add.machine = machine; Result ra = mapper.fromArtifacts(service.readArtifacts(trans,add)); - if(ra.isOK()) { + if (ra.isOK()) { RosettaData data = artiDF.newData(trans).load(ra.value); data.to(resp.getOutputStream()); setContentType(resp,artiDF.getOutType()); @@ -575,7 +575,7 @@ public abstract class FacadeImpl extends org.onap.aaf. try { Data rd = artiDF.newData().load(req.getInputStream()); arti = rd.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN,UPDATE_ARTIFACTS); return Result.err(Result.ERR_BadData,"Invalid Input"); } @@ -597,7 +597,7 @@ public abstract class FacadeImpl extends org.onap.aaf. try { Data rd = artiDF.newData().load(req.getInputStream()); arti = rd.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN,DELETE_ARTIFACTS); return Result.err(Result.ERR_BadData,"Invalid Input"); } 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 53b97626..99d0c478 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 @@ -86,7 +86,7 @@ public class Mapper1_0 implements Mapper { err.setMessageId(msgID); // AT&T Restful Error Format requires numbers "%" placements err.setText(Vars.convert(holder, text, var)); - for(String s : var) { + for (String s : var) { err.getVariables().add(s); } return err; @@ -97,7 +97,7 @@ public class Mapper1_0 implements Mapper { */ @Override public Result toCert(AuthzTrans trans, Result in, boolean withTrustChain) throws IOException { - if(!in.isOK()) { + if (!in.isOK()) { return Result.err(in); } @@ -105,15 +105,15 @@ public class Mapper1_0 implements Mapper { CertInfo cout = newInstance(API.CERT); cout.setPrivatekey(cin.privateString()); String value; - if((value=cin.challenge())!=null) { + 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) { + if (cin.trustChain()!=null) { + for (String c : cin.trustChain()) { + if (c!=null) { cout.getCerts().add(c); } } @@ -121,20 +121,20 @@ public class Mapper1_0 implements Mapper { // 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)) { + 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) { + if (cin.notes()!=null) { boolean first = true; StringBuilder sb = new StringBuilder(); - for(String n : cin.notes()) { - if(first) { + for (String n : cin.notes()) { + if (first) { first = false; } else { sb.append('\n'); @@ -144,7 +144,7 @@ public class Mapper1_0 implements Mapper { cout.setNotes(sb.toString()); } List caIssuerDNs = cout.getCaIssuerDNs(); - for(String s : cin.caIssuerDNs()) { + for (String s : cin.caIssuerDNs()) { caIssuerDNs.add(s); } cout.setEnv(cin.env()); @@ -154,10 +154,10 @@ public class Mapper1_0 implements Mapper { @Override public Result toCert(AuthzTrans trans, Result> in) { - if(in.isOK()) { + if (in.isOK()) { CertInfo cout = newInstance(API.CERT); List certs = cout.getCerts(); - for(CertDAO.Data cdd : in.value) { + for (CertDAO.Data cdd : in.value) { certs.add(cdd.x509); } return Result.ok(cout); @@ -174,7 +174,7 @@ public class Mapper1_0 implements Mapper { CertificateRequest in; try { in = (CertificateRequest)req; - } catch(ClassCastException e) { + } catch (ClassCastException e) { return Result.err(Result.ERR_BadData,"Request is not a CertificateRequest"); } @@ -184,7 +184,7 @@ public class Mapper1_0 implements Mapper { out.fqdns=in.getFqdns(); v.isNull("CertRequest", req).nullOrBlank("MechID", out.mechid); v.nullBlankMin("FQDNs", out.fqdns,1); - if(v.err()) { + if (v.err()) { return Result.err(Result.ERR_BadData, v.errs()); } out.emails = in.getEmail(); @@ -217,7 +217,7 @@ public class Mapper1_0 implements Mapper { @Override public List toArtifact(AuthzTrans trans, Artifacts artifacts) { List ladd = new ArrayList<>(); - for(Artifact arti : artifacts.getArtifact()) { + for (Artifact arti : artifacts.getArtifact()) { ArtiDAO.Data data = new ArtiDAO.Data(); data.mechid = arti.getMechid(); data.machine = arti.getMachine(); @@ -235,11 +235,11 @@ public class Mapper1_0 implements Mapper { data.expires = null; // Derive Optional Data from Machine (Domain) if exists - if(data.machine!=null) { - if(data.ca==null && data.machine.endsWith(".att.com")) { + if (data.machine!=null) { + if (data.ca==null && data.machine.endsWith(".att.com")) { data.ca = "aaf"; // default } - if(data.ns==null ) { + if (data.ns==null ) { data.ns=FQI.reverseDomain(data.machine); } } @@ -254,9 +254,9 @@ public class Mapper1_0 implements Mapper { */ @Override public Result fromArtifacts(Result> lArtiDAO) { - if(lArtiDAO.isOK()) { + if (lArtiDAO.isOK()) { Artifacts artis = new Artifacts(); - for(ArtiDAO.Data arti : lArtiDAO.value) { + for (ArtiDAO.Data arti : lArtiDAO.value) { Artifact a = new Artifact(); a.setMechid(arti.mechid); a.setMachine(arti.machine); 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 d85ea2ca..55a292e0 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 @@ -86,7 +86,7 @@ public class Mapper2_0 implements Mapper { err.setMessageId(msgID); // AT&T Restful Error Format requires numbers "%" placements err.setText(Vars.convert(holder, text, var)); - for(String s : var) { + for (String s : var) { err.getVariables().add(s); } return err; @@ -100,25 +100,25 @@ public class Mapper2_0 implements Mapper { */ @Override public Result toCert(AuthzTrans trans, Result in, boolean withTrustChain) throws IOException { - if(!in.isOK()) { + if (!in.isOK()) { CertResp cin = in.value; CertInfo cout = newInstance(API.CERT); cout.setPrivatekey(cin.privateString()); String value; - if((value=cin.challenge())!=null) { + if ((value=cin.challenge())!=null) { cout.setChallenge(value); } cout.getCerts().add(cin.asCertString()); - if(cin.trustChain()!=null) { - for(String c : cin.trustChain()) { + if (cin.trustChain()!=null) { + for (String c : cin.trustChain()) { cout.getCerts().add(c); } } - if(cin.notes()!=null) { + if (cin.notes()!=null) { boolean first = true; StringBuilder sb = new StringBuilder(); - for(String n : cin.notes()) { - if(first) { + for (String n : cin.notes()) { + if (first) { first = false; } else { sb.append('\n'); @@ -129,7 +129,7 @@ public class Mapper2_0 implements Mapper { } List caIssuerDNs = cout.getCaIssuerDNs(); - for(String s : cin.caIssuerDNs()) { + for (String s : cin.caIssuerDNs()) { caIssuerDNs.add(s); } @@ -143,10 +143,10 @@ public class Mapper2_0 implements Mapper { @Override public Result toCert(AuthzTrans trans, Result> in) { - if(in.isOK()) { + if (in.isOK()) { CertInfo cout = newInstance(API.CERT); List certs = cout.getCerts(); - for(CertDAO.Data cdd : in.value) { + for (CertDAO.Data cdd : in.value) { certs.add(cdd.x509); } return Result.ok(cout); @@ -163,7 +163,7 @@ public class Mapper2_0 implements Mapper { CertificateRequest in; try { in = (CertificateRequest)req; - } catch(ClassCastException e) { + } catch (ClassCastException e) { return Result.err(Result.ERR_BadData,"Request is not a CertificateRequest"); } @@ -172,7 +172,7 @@ public class Mapper2_0 implements Mapper { v.isNull("CertRequest", req) .nullOrBlank("MechID", out.mechid=in.getMechid()); v.nullBlankMin("FQDNs", out.fqdns=in.getFqdns(),1); - if(v.err()) { + if (v.err()) { return Result.err(Result.ERR_BadData, v.errs()); } @@ -206,7 +206,7 @@ public class Mapper2_0 implements Mapper { @Override public List toArtifact(AuthzTrans trans, Artifacts artifacts) { List ladd = new ArrayList<>(); - for(Artifact arti : artifacts.getArtifact()) { + for (Artifact arti : artifacts.getArtifact()) { ArtiDAO.Data data = new ArtiDAO.Data(); data.mechid = arti.getMechid(); data.machine = arti.getMachine(); @@ -224,13 +224,13 @@ public class Mapper2_0 implements Mapper { 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")) { + if (data.machine!=null) { + if (data.ca==null) { + if (data.machine.endsWith(".att.com")) { data.ca = "aaf"; // default } } - if(data.ns==null ) { + if (data.ns==null ) { data.ns=FQI.reverseDomain(data.machine); } } @@ -245,9 +245,9 @@ public class Mapper2_0 implements Mapper { */ @Override public Result fromArtifacts(Result> lArtiDAO) { - if(lArtiDAO.isOK()) { + if (lArtiDAO.isOK()) { Artifacts artis = new Artifacts(); - for(ArtiDAO.Data arti : lArtiDAO.value) { + for (ArtiDAO.Data arti : lArtiDAO.value) { Artifact a = new Artifact(); a.setMechid(arti.mechid); a.setMachine(arti.machine); 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 62f0d680..89824a47 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 @@ -164,7 +164,7 @@ public class CMService { } else { for (String cn : req.value.fqdns) { - if(!ignoreIPs) { + if (!ignoreIPs) { try { InetAddress[] ias = InetAddress.getAllByName(cn); Set potentialSanNames = new HashSet<>(); @@ -186,7 +186,7 @@ public class CMService { } final String host; - if(ignoreIPs) { + 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()); @@ -271,7 +271,7 @@ public class CMService { // Make sure Primary is the first in fqdns if (fqdns.size() > 1) { for (int i = 0; i < fqdns.size(); ++i) { - if(primary==null) { + if (primary==null) { trans.error().log("CMService var primary is null"); } else { String fg = fqdns.get(i); 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 ea97dd0d..1a27b41f 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 @@ -49,13 +49,13 @@ public class CertmanValidator extends Validator{ 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) { + if (list==null) { msg(name + IS_NULL); } else { - if(list.size() list, int min) { - if(list==null) { + if (list==null) { msg(ARTIFACT_LIST_IS_NULL); } else { - if(list.size() list, int min) { - if(list==null) { + if (list==null) { msg(ARTIFACT_LIST_IS_NULL); } else { - if(list.size() loc = new DNSLocator(env, "https", "aaf.it.att.com", "8150"); -// for(Item item = loc.first(); item!=null; item=loc.next(item)) { +// for (Item item = loc.first(); item!=null; item=loc.next(item)) { // System.out.println(loc.get(item)); // } // @@ -111,7 +111,7 @@ public class CertmanTest { // @Test // public void testX500Name() throws Exception { // -// for( InetAddress ia : InetAddress.getAllByName("aaf.dev.att.com")) { +// 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()); @@ -133,12 +133,12 @@ public class CertmanTest { // try { // System.out.println(reqDF.newData().option(Data.PRETTY).load(cr).asString()); // Future f = client.updateRespondString(path, reqDF, cr); -// if(f.get(10000)) { +// 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)) { +// for (String c :capi.getCerts()) { +// for ( java.security.cert.Certificate x509 : Factory.toX509Certificate(c)) { // System.out.println(x509.toString()); // } // } 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 c308e775..ea366576 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 @@ -161,7 +161,7 @@ public class AAFcli { 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) { + if (p==null) { p = System.getProperty(largs[idx].substring(v+2,e)); } ++e; @@ -183,7 +183,7 @@ public class AAFcli { while (rv && idx < largs.length) { // Allow Script to change Credential if (!gui) { - if("as".equalsIgnoreCase(largs[idx])) { + if ("as".equalsIgnoreCase(largs[idx])) { if (largs.length > ++idx) { // get Password from Props with ID as Key String user = largs[idx++]; @@ -255,13 +255,13 @@ public class AAFcli { } - if("REQUEST".equalsIgnoreCase(largs[idx])) { + if ("REQUEST".equalsIgnoreCase(largs[idx])) { request=true; ++idx; - } else if("FORCE".equalsIgnoreCase(largs[idx])) { + } else if ("FORCE".equalsIgnoreCase(largs[idx])) { force="true"; ++idx; - } else if("DETAILS".equalsIgnoreCase(largs[idx])) { + } else if ("DETAILS".equalsIgnoreCase(largs[idx])) { showDetails=true; ++idx; } else if ("set".equalsIgnoreCase(largs[idx])) { @@ -271,11 +271,11 @@ public class AAFcli { if (equals < 0) { tag = largs[idx]; value = access.getProperty(Config.AAF_APPPASS,null); - if(value==null) { + if (value==null) { break; } else { value = access.decrypt(value, false); - if(value==null) { + if (value==null) { break; } access.getProperties().put(tag, value); @@ -287,11 +287,11 @@ public class AAFcli { pw.println("set " + tag + ' ' + value); } boolean isTrue = "TRUE".equalsIgnoreCase(value); - if("FORCE".equalsIgnoreCase(tag)) { + if ("FORCE".equalsIgnoreCase(tag)) { force = value; - } else if("REQUEST".equalsIgnoreCase(tag)) { + } else if ("REQUEST".equalsIgnoreCase(tag)) { request = isTrue; - } else if("DETAILS".equalsIgnoreCase(tag)) { + } else if ("DETAILS".equalsIgnoreCase(tag)) { showDetails = isTrue; } else { access.getProperties().put(tag, value); @@ -380,7 +380,7 @@ public class AAFcli { } else { quote = ch; } - } else if(ch=='|' && quote==0) { + } else if (ch=='|' && quote==0) { arr.add(sb.toString()); sb.setLength(0); start = true; @@ -437,7 +437,7 @@ public class AAFcli { try { PropAccess access = aafsso.access(); - if(aafsso.ok()) { + if (aafsso.ok()) { Define.set(access); AuthzEnv env = new AuthzEnv(access); @@ -450,7 +450,7 @@ public class AAFcli { for (int i = 0; i < args.length; ++i) { if ("-i".equalsIgnoreCase(args[i])) { rdr = new InputStreamReader(System.in); - // } else if("-o".equalsIgnoreCase(args[i])) { + // } else if ("-o".equalsIgnoreCase(args[i])) { // // shall we do something different? Output stream is // already done... } else if ("-f".equalsIgnoreCase(args[i])) { @@ -488,7 +488,7 @@ public class AAFcli { aafsso.setStdErrDefault(); // Note, with AAF Locator, this may not longer be necessary 3/2018 Jonathan - if(!aafsso.loginOnly()) { + if (!aafsso.loginOnly()) { // try { // loc = new AAFLocator(si,new URI(access.getProperty(Config.AAF_URL))); // } catch (Throwable t) { @@ -502,7 +502,7 @@ public class AAFcli { 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) { + 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"); } @@ -511,13 +511,13 @@ public class AAFcli { aafcon.hman(), aafcon.securityInfo(), aafcon.securityInfo().defSS); // new HBasicAuthSS(si,aafsso.user(), access.decrypt(aafsso.enc_pass(),false))); // } - if(!ignoreDelay) { + if (!ignoreDelay) { File delay = new File("aafcli.delay"); - if(delay.exists()) { + if (delay.exists()) { BufferedReader br = new BufferedReader(new FileReader(delay)); try { globalDelay = Integer.parseInt(br.readLine()); - } catch(Exception e) { + } catch (Exception e) { access.log(Level.DEBUG,e); } finally { br.close(); @@ -596,7 +596,7 @@ public class AAFcli { System.err.println(err); } } - if(noexit==null) { + if (noexit==null) { return; } 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 168d2753..77d1894f 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 @@ -45,20 +45,20 @@ public class BaseCmd extends Cmd { @Override public int _exec( int idx, final String ... args) throws CadiException, APIException, LocatorException { - if(args.length-idx<1) { + 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) { + for (Cmd c: cmds) { name = c.getName(); - if(name==null && empty==null) { // Mark with Command is null, and take the first one. + if (name==null && empty==null) { // Mark with Command is null, and take the first one. empty = c; - } else if(s.equalsIgnoreCase(c.getName())) + } else if (s.equalsIgnoreCase(c.getName())) return c.exec(idx+1, args); } - if(empty!=null) { + 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."); 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 9ec126b4..3a0c869b 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 @@ -92,21 +92,21 @@ public abstract class Cmd { this.aafcli = aafcli; this.env = aafcli.env; this.access = aafcli.access; - if(parent!=null) { + 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) { + for (Param p : params) { + if (p.required) { ++required; } } String temp = access.getProperty(Config.AAF_DEFAULT_REALM,null); - if(temp!=null && !temp.startsWith("@")) { + if (temp!=null && !temp.startsWith("@")) { defaultRealm = '@' + temp; } else { defaultRealm=""; @@ -114,7 +114,7 @@ public abstract class Cmd { } 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) { + if (head) { sb.append('\n'); detailLine(sb,indent,"APIs:"); } @@ -145,7 +145,7 @@ public abstract class Cmd { sb.append(' '); sb.append(pathInfo); String cliString = aafcli.typeString(cls,true); - if(indent+smeth.length()+pathInfo.length()+cliString.length()+2>80) { + if (indent+smeth.length()+pathInfo.length()+cliString.length()+2>80) { sb.append(" ..."); multiChar(sb,indent+3+smeth.length(),' ',0); } else { // same line @@ -156,54 +156,54 @@ public abstract class Cmd { 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) { + for (Cmd child : children) { + if (!(child instanceof DeprecatedCMD)) { + if (first) { first = false; - } else if(detail==null) { + } 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) { + for (Cmd c = child.parent;c!=null;c=c.parent) { + if (c.name!=null) { stack.push(c.name); } } - if(!stack.isEmpty()) { + if (!stack.isEmpty()) { sb.append(" "); - while(!stack.isEmpty()) { + while (!stack.isEmpty()) { sb.append(stack.pop()); sb.append(' '); } } } child.build(sb,detail); - if(detail!=null) { + if (detail!=null) { child.detailedHelp(4, detail); // If Child wrote something, then add, bracketing by lines - if(detail.length()>0) { + if (detail.length()>0) { multiChar(sb,80,'-',2); sb.append(detail); sb.append('\n'); @@ -223,9 +223,9 @@ public abstract class Cmd { StringBuilder sb = new StringBuilder("Failed"); String desc = future.body(); int code = future.code(); - if(desc==null || desc.length()==0) { + if (desc==null || desc.length()==0) { withCode(sb,code); - } else if(desc.startsWith("{")) { + } 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. @@ -240,7 +240,7 @@ public abstract class Cmd { String var = vars.get(varCounter); ++varCounter; if (messageBody.indexOf("%" + varCounter) >= 0) { - if((pipe = var.indexOf('|'))>=0) { // In AAF, we use a PIPE for Choice + 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]"); @@ -260,7 +260,7 @@ public abstract class Cmd { withCode(sb,code); sb.append(" (Note: Details cannot be obtained from Error Structure)"); } - } else if(desc.startsWith("")){ // Core Jetty, etc sends HTML for Browsers + } else if (desc.startsWith("")){ // Core Jetty, etc sends HTML for Browsers withCode(sb,code); } else { sb.append(" with code "); @@ -296,11 +296,11 @@ public abstract class Cmd { protected void setStartEnd(Request req) { // Set Start/End Dates, if exist String str; - if((str = access.getProperty(Cmd.STARTDATE,null))!=null) { + if ((str = access.getProperty(Cmd.STARTDATE,null))!=null) { req.setStart(Chrono.timeStamp(Date.valueOf(str))); } - if((str = access.getProperty(Cmd.ENDDATE,null))!=null) { + if ((str = access.getProperty(Cmd.ENDDATE,null))!=null) { req.setEnd(Chrono.timeStamp(Date.valueOf(str))); } } @@ -326,7 +326,7 @@ public abstract class Cmd { @SuppressWarnings("unchecked") public static RosettaDF getDF(AuthzEnv env, Class cls) throws APIException { RosettaDF rdf = (RosettaDF)dfs.get(cls); - if(rdf == null) { + if (rdf == null) { rdf = env.newDataFactory(cls); dfs.put(cls, rdf); } @@ -341,11 +341,11 @@ public abstract class Cmd { } } else { pw().println(header); - 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) { + if (aafcli.prevCall!=null) { retryable.item(aafcli.prevCall.item()); retryable.lastClient=aafcli.prevCall.lastClient; } @@ -450,9 +450,9 @@ public abstract class Cmd { pw().println(); boolean first = true; int i=0; - for(String s : str) { - if(first) { - if(++i>1) { + for (String s : str) { + if (first) { + if (++i>1) { first = false; pw().print("["); } @@ -461,7 +461,7 @@ public abstract class Cmd { } pw().print(s); } - if(!first) { + if (!first) { pw().print(']'); } pw().println(); @@ -475,25 +475,25 @@ public abstract class Cmd { } public void reportLine() { - for(int i=0;i rcli) { StringBuilder sb=null; String force; - if((force=aafcli.forceString())!=null) { + if ((force=aafcli.forceString())!=null) { sb = new StringBuilder("force="); sb.append(force); } - if(aafcli.addRequest()) { - if(sb==null) { + if (aafcli.addRequest()) { + if (sb==null) { sb = new StringBuilder("future=true"); } else { sb.append("&future=true"); } } - if(sb!=null && rcli!=null) { + if (sb!=null && rcli!=null) { rcli.setQueryParams(sb.toString()); } } @@ -504,7 +504,7 @@ public abstract class Cmd { // * @return // */ // protected String checkForce() { -// if(TRUE.equalsIgnoreCase(env.getProperty(FORCE, FALSE))) { +// if (TRUE.equalsIgnoreCase(env.getProperty(FORCE, FALSE))) { // env.setProperty(FORCE, FALSE); // return "true"; // } @@ -513,7 +513,7 @@ public abstract class Cmd { public String toString() { StringBuilder sb = new StringBuilder(); - if(parent==null) { // ultimate parent + if (parent==null) { // ultimate parent build(sb,null); return sb.toString(); } else { @@ -530,7 +530,7 @@ public abstract class Cmd { * @throws OrganizationException */ public String fullID(String id) { - if(id != null) { + if (id != null) { if (id.indexOf('@') < 0) { id+=defaultRealm; } else { 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 bd70d9e5..66a3355a 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 @@ -53,27 +53,27 @@ public class Help extends Cmd { details = aafcli.isDetailed()?new StringBuilder():null; String comp = args.length>idx?args[idx++]:null; - if("help".equalsIgnoreCase(comp)) { + 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())) { + 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) { + if (first) { first=false; } else { multiChar(sb,80,'-',2); } multiChar(sb,2,' ',0); c.build(sb,details); - if(details!=null) { + if (details!=null) { c.detailedHelp(4, sb); // multiChar(sb,80,'-',2); } 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 ca8a72ca..5c74dda8 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 @@ -48,7 +48,7 @@ public class Clear extends Cmd { 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)) { + for (final String name : args[idx++].split(COMMA)) { rv = all(new Retryable() { @Override public Integer code(Rcli client) throws APIException, CadiException { @@ -57,11 +57,11 @@ public class Clear extends Cmd { "/mgmt/cache/"+name, Void.class ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { pw().println("Cleared Cache for " + name + " on " + client); rv=200; } else { - if(rv==409)rv = fp.code(); + if (rv==409)rv = fp.code(); error(fp); } return rv; 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 17f23729..159a51bc 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 @@ -59,9 +59,9 @@ public class Deny extends BaseCmd { String action = args[idx++]; final int option = whichOption(options, action); int rv=409; - for(final String name : args[idx++].split(COMMA)) { + for (final String name : args[idx++].split(COMMA)) { final String append; - if(isID && name.indexOf("@")<0) { + if (isID && name.indexOf("@")<0) { append='@'+ access.getProperty(Config.AAF_DEFAULT_REALM,null); } else { append = ""; @@ -82,11 +82,11 @@ public class Deny extends BaseCmd { fp = client.delete(path, Void.class); resp = " deleted"; } - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { pw().println(name + append + resp + " on " + client); rv=fp.code(); } else { - if(rv==409)rv = fp.code(); + if (rv==409)rv = fp.code(); error(fp); } 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 535de3bb..db59df0a 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 @@ -49,9 +49,9 @@ public class Log extends BaseCmd { int idx = _idx; final int option = whichOption(options, args[idx++]); - for(String name : args[idx++].split(COMMA)) { + for (String name : args[idx++].split(COMMA)) { final String fname; - if(name.indexOf("@")<0) { + if (name.indexOf("@")<0) { fname=name+'@'+ access.getProperty(Config.AAF_DEFAULT_REALM,null); } else { fname = name; @@ -78,12 +78,12 @@ public class Log extends BaseCmd { msg = "Ignored"; } - if(fp!=null) { - if(fp.get(AAFcli.timeout())) { + 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(); + if (rv==409)rv = fp.code(); error(fp); } return rv; 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 a52d5dc7..cd10ef60 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 @@ -56,11 +56,11 @@ public class SessClear extends Cmd { "/mgmt/dbsession", Void.class ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { pw().println("Cleared DBSession on " + client); rv=200; } else { - if(rv==409)rv = fp.code(); + if (rv==409)rv = fp.code(); error(fp); } return rv; 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 f1952fa9..90141819 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 @@ -54,7 +54,7 @@ public class Admin extends BaseCmd { @Override public Integer code(Rcli client) throws CadiException, APIException { Future fp = null; - for(String id : ids) { + for (String id : ids) { id = fullID(id); String verb; switch(option) { @@ -70,7 +70,7 @@ public class Admin extends BaseCmd { throw new CadiException("Bad Argument"); }; - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { pw().append("Admin "); pw().append(id); pw().append(verb); 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 f1b2621d..31dad45c 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 @@ -50,8 +50,8 @@ public class Attrib extends BaseCmd { final String ns = args[idx+1]; final String key = args[idx+2]; final String value; - if(option!=2) { - if(args.length<=idx+3) { + if (option!=2) { + if (args.length<=idx+3) { throw new CadiException("Not added: Need more Data"); } value = args[idx+3]; @@ -83,10 +83,10 @@ public class Attrib extends BaseCmd { default: throw new CadiException("Bad Argument"); }; - if(fp==null) { + if (fp==null) { return 500; } else { - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { pw().println(message); } else { error(fp); 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 1719ada7..05d66881 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 @@ -56,16 +56,16 @@ public class Create extends Cmd { nr.setName(args[idx++]); String[] responsible = args[idx++].split(COMMA); - for(String s : responsible) { + for (String s : responsible) { nr.getResponsible().add(fullID(s)); } String[] admin; - if(args.length>idx) { + if (args.length>idx) { admin = args[idx++].split(COMMA); } else { admin = responsible; } - for(String s : admin) { + for (String s : admin) { nr.getAdmin().add(fullID(s)); } @@ -82,10 +82,10 @@ public class Create extends Cmd { getDF(NsRequest.class), nr ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { pw().println("Created Namespace"); } else { - if(fp.code()==202) { + if (fp.code()==202) { pw().println("Namespace Creation Accepted, but requires Approvals before actualizing"); } else { error(fp); 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 99ac7ed2..7da6c26b 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 @@ -56,7 +56,7 @@ public class Delete extends Cmd { setQueryParamsOn(client); Future fp = client.delete(path.toString(),Void.class); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { pw().println("Deleted Namespace"); } else { error(fp); 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 18823297..e521d616 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 @@ -70,11 +70,11 @@ public class Describe extends Cmd { nsr ); - if(fn.get(AAFcli.timeout())) { + if (fn.get(AAFcli.timeout())) { rv=fn.code(); pw().println("Description added to Namespace"); } else { - if((rv=fn.code())==202) { + if ((rv=fn.code())==202) { pw().print("Adding description"); pw().println(" Accepted, but requires Approvals before actualizing"); } else { 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 01b3ad14..8fc79401 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 @@ -58,34 +58,34 @@ public class List extends BaseCmd { public void report(Future fp, String ... str) { reportHead(str); - if(fp==null) { + if (fp==null) { pw().println(" *** Namespace Not Found ***"); } - if(fp!=null && fp.value!=null) { - for(Ns ns : fp.value.getNs()) { + 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) { + if (ns.getAdmin().size()>0) { pw().println(" Administrators"); - for(String admin : ns.getAdmin()) { + for (String admin : ns.getAdmin()) { pw().format(sformat,admin); } } - if(ns.getResponsible().size()>0) { + if (ns.getResponsible().size()>0) { pw().println(" Owners (Responsible for Namespace)"); - for(String responsible : ns.getResponsible()) { + for (String responsible : ns.getResponsible()) { pw().format(sformat,responsible); } } - if(ns.getAttrib().size()>0) { + if (ns.getAttrib().size()>0) { pw().println(" Namespace Attributes"); - for( Ns.Attrib attr : ns.getAttrib()) { + for ( Ns.Attrib attr : ns.getAttrib()) { StringBuilder sb = new StringBuilder(attr.getKey()); - if(attr.getValue()==null || attr.getValue().length()>0) { + if (attr.getValue()==null || attr.getValue().length()>0) { sb.append('='); sb.append(attr.getValue()); } @@ -99,7 +99,7 @@ public class List extends BaseCmd { public void reportName(Future fp, String ... str) { reportHead(str); - if(fp!=null && fp.value!=null) { + if (fp!=null && fp.value!=null) { java.util.List nss = fp.value.getNs(); Collections.sort(nss, new Comparator() { @Override @@ -108,7 +108,7 @@ public class List extends BaseCmd { } }); - for(Ns ns : nss) { + for (Ns ns : nss) { pw().println(ns.getName()); if (this.aafcli.isDetailed() && ns.getDescription() != null) { pw().println(" " + ns.getDescription()); @@ -118,9 +118,9 @@ public class List extends BaseCmd { } public void reportRole(Future fr) { - if(fr!=null && fr.value!=null && fr.value.getRole().size()>0) { + if (fr!=null && fr.value!=null && fr.value.getRole().size()>0) { pw().println(" Roles"); - for(aaf.v2_0.Role r : fr.value.getRole()) { + for (aaf.v2_0.Role r : fr.value.getRole()) { pw().format(sformat,r.getName()); } } @@ -128,9 +128,9 @@ public class List extends BaseCmd { 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) { + if (fp!=null && fp.value!=null && fp.value.getPerm().size()>0) { pw().println(" Permissions"); - for(aaf.v2_0.Perm p : fp.value.getPerm()) { + for (aaf.v2_0.Perm p : fp.value.getPerm()) { pw().format(pformat,p.getType(),p.getInstance(),p.getAction()); } } @@ -139,7 +139,7 @@ public class List extends BaseCmd { 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) { + 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() { @@ -148,7 +148,7 @@ public class List extends BaseCmd { return u1.getId().compareTo(u2.getId()); } }); - for(aaf.v2_0.Users.User u : users) { + for (aaf.v2_0.Users.User u : users) { if (this.aafcli.isTest()) { pw().format(sformat,u.getId()); } else { @@ -160,7 +160,7 @@ public class List extends BaseCmd { public static String getType(User u) { Integer type; - if((type=u.getType())==null) { + if ((type=u.getType())==null) { type = 9999; } switch(type) { 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 52b9a108..f8f82466 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 @@ -59,7 +59,7 @@ public class ListActivity extends Cmd { getDF(History.class) ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { activity(fp.value, HEADER + " [ " + ns + " ]"); } else { error(fp); 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 06de6cab..e62207a0 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 @@ -56,9 +56,9 @@ public class ListAdminResponsible extends Cmd { String apipart = "owner".equals(title)?"responsible":title; Future fn = client.read("/authz/nss/"+apipart+"/"+user,getDF(Nss.class)); - if(fn.get(AAFcli.timeout())) { + if (fn.get(AAFcli.timeout())) { ((List)parent).reportName(fn,HEADER + title + " privileges for ",user); - } else if(fn.code()==404) { + } else if (fn.code()==404) { ((List)parent).report(null,HEADER + title + " privileges for ",user); return 200; } else { 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 ffd3cf01..3189b88b 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 @@ -59,29 +59,29 @@ public class ListByName extends Cmd { @Override public Integer code(Rcli client) throws CadiException, APIException { Future fn = client.read("/authz/nss/"+ns,getDF(Nss.class)); - if(fn.get(AAFcli.timeout())) { + if (fn.get(AAFcli.timeout())) { ((List)parent).report(fn,HEADER,ns); - if(fn.value!=null) { - for(Ns n : fn.value.getNs()) { + 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())) { + if (fr.get(AAFcli.timeout())) { ((List)parent).reportRole(fr); } } - for(Ns n : fn.value.getNs()) { + 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())) { + if (fp.get(AAFcli.timeout())) { ((List)parent).reportPerm(fp); } } - for(Ns n : fn.value.getNs()) { + 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())) { + if (fu.get(AAFcli.timeout())) { ((List)parent).reportCred(fu); } } } - } else if(fn.code()==404) { + } else if (fn.code()==404) { ((List)parent).report(null,HEADER,ns); return 200; } else { 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 6d514df8..b3b0bcfc 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 @@ -56,12 +56,12 @@ public class ListChildren extends Cmd { @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())) { + if (fn.get(AAFcli.timeout())) { parent.reportHead(HEADER); - for(Ns ns : fn.value.getNs()) { + for (Ns ns : fn.value.getNs()) { pw().format(List.kformat, ns.getName()); } - } else if(fn.code()==404) { + } else if (fn.code()==404) { ((List)parent).report(null,HEADER,ns); return 200; } else { 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 df72ff08..01b0f21c 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 @@ -58,12 +58,12 @@ public class ListNsKeysByAttrib extends Cmd { @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())) { + if (fn.get(AAFcli.timeout())) { parent.reportHead(HEADER); - for(String key : fn.value.getKey()) { + for (String key : fn.value.getKey()) { pw().printf(List.kformat, key); } - } else if(fn.code()==404) { + } else if (fn.code()==404) { parent.reportHead(HEADER); pw().println(" *** No Namespaces Found ***"); return 200; 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 1347b918..eadf1c97 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 @@ -65,42 +65,42 @@ public class ListUsersContact extends Cmd { 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) { + if (fn.get(AAFcli.timeout())) { + if (fn.value!=null) { Set uset = detail?null:new HashSet<>(); - for(Ns n : fn.value.getNs()) { + 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) { + 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) { + 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) { + } else if (fn.code()==404) { return 200; } } } } - if(uset!=null) { - for(String u : uset) { + if (uset!=null) { + for (String u : uset) { pw().print(" "); pw().println(u); } } } - } else if(fn.code()==404) { + } else if (fn.code()==404) { return 200; } else { error(fn); 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 301e1508..c0838cb7 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 @@ -65,42 +65,42 @@ public class ListUsersInRole extends Cmd { 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) { + if (fn.get(AAFcli.timeout())) { + if (fn.value!=null) { Set uset = detail?null:new HashSet<>(); - for(Ns n : fn.value.getNs()) { + 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) { + 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) { + 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) { + } else if (fn.code()==404) { return 200; } } } } - if(uset!=null) { - for(String u : uset) { + if (uset!=null) { + for (String u : uset) { pw().print(" "); pw().println(u); } } } - } else if(fn.code()==404) { + } else if (fn.code()==404) { return 200; } else { error(fn); 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 472070d9..96ca95ee 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 @@ -65,42 +65,42 @@ public class ListUsersWithPerm extends Cmd { 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) { + if (fn.get(AAFcli.timeout())) { + if (fn.value!=null) { Set uset = detail?null:new HashSet<>(); - for(Ns n : fn.value.getNs()) { + 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()) { + 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); + 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) + 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) { + } else if (fn.code()==404) { return 200; } } } } - if(uset!=null) { - for(String u : uset) { + if (uset!=null) { + for (String u : uset) { pw().print(" "); pw().println(u); } } } - } else if(fn.code()==404) { + } else if (fn.code()==404) { return 200; } else { error(fn); 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 e5e50187..35dd6b96 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 @@ -55,7 +55,7 @@ public class Owner extends BaseCmd { @Override public Integer code(Rcli client) throws CadiException, APIException { Future fp=null; - for(String id : ids) { + for (String id : ids) { id=fullID(id); String verb; switch(option) { @@ -71,7 +71,7 @@ public class Owner extends BaseCmd { throw new CadiException("Bad Argument"); }; - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { pw().append(id); pw().append(verb); pw().append("responsible for "); 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 1f123cff..be49cf28 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 @@ -65,9 +65,9 @@ public class Create extends Cmd { boolean force = aafcli.forceString()!=null; int rv; - if(roles!=null && force) { // Make sure Roles are Created + if (roles!=null && force) { // Make sure Roles are Created RoleRequest rr = new RoleRequest(); - for(String role : roles) { + for (String role : roles) { rr.setName(role);; Future fr = client.create( "/authz/role", @@ -96,13 +96,13 @@ public class Create extends Cmd { getDF(PermRequest.class), pr ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { rv = fp.code(); pw().println("Created Permission"); - if(roles!=null) { - if(aafcli.forceString()!=null) { // Make sure Roles are Created + if (roles!=null) { + if (aafcli.forceString()!=null) { // Make sure Roles are Created RoleRequest rr = new RoleRequest(); - for(String role : roles) { + for (String role : roles) { rr.setName(role);; Future fr = client.create( "/authz/role", @@ -120,7 +120,7 @@ public class Create extends Cmd { } try { - if(201!=(rv=((Perm)parent)._exec(0, + if (201!=(rv=((Perm)parent)._exec(0, new String[] {"grant",pr.getType(),pr.getInstance(),pr.getAction(),roleCommas}))) { rv = 206 /*HttpStatus.PARTIAL_CONTENT_206*/; } @@ -130,9 +130,9 @@ public class Create extends Cmd { } } else { rv = fp.code(); - if(rv==409 && force) { + if (rv==409 && force) { rv = 201; - } else if(rv==202) { + } 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."); 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 ed52a071..0f0c0011 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 @@ -65,10 +65,10 @@ public class Delete extends Cmd { "/authz/perm", getDF(PermRequest.class), pk); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { pw().println("Deleted Permission"); } else { - if(fp.code()==202) { + if (fp.code()==202) { pw().println("Permission Deletion Accepted, but requires Approvals before actualizing"); } else { error(fp); 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 8396f7d3..bb894ca7 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 @@ -76,11 +76,11 @@ public class Describe extends Cmd { pr ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { rv=fp.code(); pw().println("Description added to Permission"); } else { - if((rv=fp.code())==202) { + if ((rv=fp.code())==202) { pw().print("Adding description"); pw().println(" Accepted, but requires Approvals before actualizing"); } else { 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 4ed411ba..dd45fb4b 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 @@ -75,9 +75,9 @@ public class Grant extends Cmd { if (option != 2) { String[] roles = args[idx++].split(","); String strA,strB; - for(String role : roles) { + for (String role : roles) { rpr.setRole(role); - if(option==0) { + if (option==0) { // You can request to Grant Permission to a Role setQueryParamsOn(client); frpr = client.create( @@ -98,7 +98,7 @@ public class Grant extends Cmd { strA = "UnGranted Permission ["; strB = "] from Role ["; } - if(frpr.get(AAFcli.timeout())) { + if (frpr.get(AAFcli.timeout())) { pw().println(strA + pk.getType() + '|' + pk.getInstance() + '|' + pk.getAction() + strB + role +']'); } else { @@ -122,7 +122,7 @@ public class Grant extends Cmd { "/authz/role/perm", getDF(RolePermRequest.class), rpr); - if(frpr.get(AAFcli.timeout())) { + if (frpr.get(AAFcli.timeout())) { pw().println("Set Permission's Roles to [" + allRoles + "]"); } else { error(frpr); 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 48b8a488..5df2afa2 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 @@ -48,7 +48,7 @@ public class List extends BaseCmd { // 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())) { + if (fp.get(AAFcli.timeout())) { report(fp,header, parentPerm); } else { error(fp); @@ -61,10 +61,10 @@ public class List extends BaseCmd { @Override public int compare(aaf.v2_0.Perm a, aaf.v2_0.Perm b) { int rc; - if((rc=a.getType().compareTo(b.getType()))!=0) { + if ((rc=a.getType().compareTo(b.getType()))!=0) { return rc; } - if((rc=a.getInstance().compareTo(b.getInstance()))!=0) { + if ((rc=a.getInstance().compareTo(b.getInstance()))!=0) { return rc; } return a.getAction().compareTo(b.getAction()); @@ -80,9 +80,9 @@ public class List extends BaseCmd { 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()) { + for (aaf.v2_0.Perm p : fp.value.getPerm()) { String pns = p.getNs(); - if(pns==null) { + if (pns==null) { pw().format(format, p.getType(), p.getInstance(), @@ -94,7 +94,7 @@ public class List extends BaseCmd { p.getAction()); } String desc = p.getDescription(); - if(desc!=null && desc.length()>0) { + if (desc!=null && desc.length()>0) { pw().format(descFmt,p.getDescription()); } } @@ -103,7 +103,7 @@ public class List extends BaseCmd { String format = reportColHead(permFormat,"PERM Type","Instance","Action"); Collections.sort(fp.value.getPerm(),permCompare); - for(aaf.v2_0.Perm p : fp.value.getPerm()) { + for (aaf.v2_0.Perm p : fp.value.getPerm()) { pw().format(format, p.getType(), p.getInstance(), 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 c59e9b5a..c96220a5 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 @@ -57,7 +57,7 @@ public class ListActivity extends Cmd { "/authz/hist/perm/"+type, getDF(History.class) ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { activity(fp.value, HEADER + " [ " + type + " ]"); } else { error(fp); 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 550386cf..325f45db 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 @@ -51,12 +51,12 @@ public class ListByUser extends Cmd { @Override public Integer code(Rcli client) throws CadiException, APIException { StringBuilder sb = null; - if("true".equalsIgnoreCase(aafcli.forceString())) { + if ("true".equalsIgnoreCase(aafcli.forceString())) { sb = new StringBuilder(); sb.append("?force"); } - if(aafcli.isDetailed()) { - if(sb==null) { + if (aafcli.isDetailed()) { + if (sb==null) { sb = new StringBuilder('?'); } else { sb.append('&'); 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 620e1e04..dbadd8a0 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 @@ -71,12 +71,12 @@ public class Rename extends Cmd { pr ); int rv; - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { rv = fp.code(); pw().println("Updated Permission"); } else { rv = fp.code(); - if(rv==202) { + if (rv==202) { pw().println("Permission Update Accepted, but requires Approvals before actualizing"); } else { error(fp); 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 f9dcbcd8..320bac5b 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 @@ -90,17 +90,17 @@ public class CreateDelete extends Cmd { } boolean rolesSupplied = (args.length>idx); - if(fp == null) {// This useless code brought to you by Sonar. + if (fp == null) {// This useless code brought to you by Sonar. throw new CadiException("No call made."); } - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { rv=fp.code(); pw().print(verb); pw().println("d Role"); - if(rolesSupplied) { - for(;args.length>idx;++idx ) { + if (rolesSupplied) { + for (;args.length>idx;++idx ) { try { - if(201!=(rv=((Role)parent)._exec(0,new String[] {"user","add",rr.getName(),args[idx]}))) { + if (201!=(rv=((Role)parent)._exec(0,new String[] {"user","add",rr.getName(),args[idx]}))) { rv = 206 /*HttpStatus.PARTIAL_CONTENT_206*/; } } catch (LocatorException e) { @@ -109,7 +109,7 @@ public class CreateDelete extends Cmd { } } } else { - if((rv=fp.code())==202) { + if ((rv=fp.code())==202) { pw().print("Role "); pw().print(verb); pw().println(" Accepted, but requires Approvals before actualizing"); 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 e8001040..f4d24fb1 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 @@ -70,11 +70,11 @@ public class Describe extends Cmd { rr ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { rv=fp.code(); pw().println("Description added to role"); } else { - if((rv=fp.code())==202) { + if ((rv=fp.code())==202) { pw().print("Adding description"); pw().println(" Accepted, but requires Approvals before actualizing"); } else { 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 ec8d8ee3..f8a633af 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 @@ -61,16 +61,16 @@ public class List extends BaseCmd { // 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())) { + if (fr.get(AAFcli.timeout())) { Perms perms=null; if (aafcli.isDetailed()) { - for(aaf.v2_0.Role r : fr.value.getRole()) { + 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) { + if (fp.get(AAFcli.timeout())) { + if (perms==null) { perms = fp.value; } else { perms.getPerm().addAll(fp.value.getPerm()); @@ -101,7 +101,7 @@ public class List extends BaseCmd { public void report(Roles roles, Perms perms, UserRoles urs, String ... str) { reportHead(str); XMLGregorianCalendar now = Chrono.timeStamp().normalize(); - if(roles==null || roles.getRole().isEmpty()) { + if (roles==null || roles.getRole().isEmpty()) { pw().println(""); } else if (aafcli.isDetailed()){ if (aafcli.isDetailed() && str[0].toLowerCase().contains(LIST_ROLES_BY_NAME)) { @@ -113,25 +113,25 @@ public class List extends BaseCmd { 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()) { + for (aaf.v2_0.Role r : roles.getRole()) { String roleName = r.getName(); String ns = r.getNs(); - if(aafcli.isTest()) { - if(ns==null) { + 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) { + 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) { + 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()):""); @@ -139,9 +139,9 @@ public class List extends BaseCmd { } } - for(Pkey pkey : r.getPerms()) { + for (Pkey pkey : r.getPerms()) { Perm perm = get(pkey,perms); - if(perm==null || perm.getNs()==null) { + if (perm==null || perm.getNs()==null) { pw().format(permFormat, pkey.getType(), pkey.getInstance(), @@ -159,12 +159,12 @@ public class List extends BaseCmd { String fullFormat = roleFormat; reportColHead(fullFormat,"ROLE Name","","PERM Type","Instance","Action"); Collections.sort(roles.getRole(),roleCompare); - for(aaf.v2_0.Role r : roles.getRole()) { + for (aaf.v2_0.Role r : roles.getRole()) { if (urs != null) { String roleName = r.getName(); - if(!aafcli.isTest()) { + if (!aafcli.isTest()) { UserRole ur = get(roleName,urs); - if(ur!=null && now.compare(ur.getExpires().normalize())>0) { + 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()):""); @@ -174,7 +174,7 @@ public class List extends BaseCmd { } } else { pw().format(roleFormatNoDate, r.getName()); - for(Pkey perm : r.getPerms()) { + for (Pkey perm : r.getPerms()) { pw().format(permFormat, perm.getType(), perm.getInstance(), @@ -185,9 +185,9 @@ public class List extends BaseCmd { } } private Perm get(Pkey pkey, Perms perms) { - if(perms!=null) { - for(Perm p : perms.getPerm()) { - if(pkey.getAction().equals(p.getAction()) && + 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; @@ -198,9 +198,9 @@ public class List extends BaseCmd { } // 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())) { + if (urs!=null) { + for (UserRole ur : urs.getUserRole()) { + if (roleName.equals(ur.getRole())) { return ur; } } 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 1f6f18f7..603ec33b 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 @@ -57,7 +57,7 @@ public class ListActivity extends Cmd { "/authz/hist/role/"+role, getDF(History.class) ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { activity(fp.value,HEADER + " [ " + role + " ]"); } else { error(fp); 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 c9ed37a4..bdcf1e50 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 @@ -68,13 +68,13 @@ public class ListByUser extends Cmd { "/authz/userRoles/user/"+user, getDF(UserRoles.class) ); - if(fr.get(AAFcli.timeout())) { + 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())) { + if (fp.get(AAFcli.timeout())) { perms = fp.value; } } 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 c628eb17..364b3980 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 @@ -69,7 +69,7 @@ public class User extends Cmd { // You can request to be added or removed from role. setQueryParamsOn(client); - for(String id: ids) { + for (String id: ids) { id=fullID(id); urr.setUser(id); switch(option) { @@ -97,7 +97,7 @@ public class User extends Cmd { default: // actually, should never get here... throw new CadiException("Invalid action [" + action + ']'); } - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { pw().print(verb); pw().print(" User ["); pw().print(urr.getUser()); @@ -112,7 +112,7 @@ public class User extends Cmd { pw().println(" is Accepted, but requires Approvals before actualizing"); break; case 404: - if(option==3) { + if (option==3) { pw().println("Failed with code 404: UserRole is not found, or you do not have permission to view"); break; } @@ -139,7 +139,7 @@ public class User extends Cmd { "/authz/userRole/role", getDF(UserRoleRequest.class), urr); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { pw().println("Set the Role to Users [" + allUsers + "]"); } else { error(fp); 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 40447c19..cc9ccf98 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 @@ -57,11 +57,11 @@ public class Cred extends Cmd { final CredRequest cr = new CredRequest(); cr.setId(args[idx++]); - if(option!=1 && option!=3) { - if(idx>=args.length) throw new CadiException("Password Required"); + if (option!=1 && option!=3) { + if (idx>=args.length) throw new CadiException("Password Required"); cr.setPassword(args[idx++]); } - if(args.length>idx) + if (args.length>idx) cr.setEntry(args[idx++]); // Set Start/End commands @@ -82,7 +82,7 @@ public class Cred extends Cmd { verb = "Added Credential ["; break; case 1: -// if(aafcli.addForce())cr.setForce("TRUE"); +// if (aafcli.addForce())cr.setForce("TRUE"); setQueryParamsOn(client); fp = client.delete(CRED_PATH, getDF(CredRequest.class), @@ -109,16 +109,16 @@ public class Cred extends Cmd { // case 4: // return clean.exec(cleanIDX, args); } - if(fp==null) { + if (fp==null) { return null; // get by Sonar check. } - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { pw().print(verb); pw().print(cr.getId()); pw().println(']'); - } else if(fp.code()==202) { + } else if (fp.code()==202) { pw().println("Credential Action Accepted, but requires Approvals before actualizing"); - } else if(fp.code()==406 && option==1) { + } else if (fp.code()==406 && option==1) { pw().println("You cannot delete this Credential"); } else { pw().println(ATTEMPT_FAILED_SPECIFICS_WITHELD); @@ -126,7 +126,7 @@ public class Cred extends Cmd { return fp.code(); } }); - if(ret==null)ret = -1; + if (ret==null)ret = -1; return ret; } 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 8587ac3d..3cb9fb04 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 @@ -64,10 +64,10 @@ public class Delg extends BaseCmd { int option= whichOption(options, args[idx++]); String user = fullID(args[idx++]); dr.setUser(user); - if(option<2) { + if (option<2) { String delegate = fullID(args[idx++]); dr.setDelegate(delegate); - if(option<2 && args.length>idx) { + if (option<2 && args.length>idx) { Date date; try { date = Chrono.dateOnlyFmt.parse(args[idx++]); @@ -100,7 +100,7 @@ public class Delg extends BaseCmd { throw new CadiException("Bad Argument"); }; - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { pw().append("Delegate "); pw().println(verb); } else { 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 03148ce5..3074ab86 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 @@ -53,7 +53,7 @@ public class List extends BaseCmd { 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) { + if (u1==null || u2 == null) { return -1; } return u1.getId().compareTo(u2.getId()); @@ -61,8 +61,8 @@ public class List extends BaseCmd { }); 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()) { + for (aaf.v2_0.Users.User user : sorted) { + if (!aafcli.isTest()) { date = Chrono.dateOnlyStamp(user.getExpires()); } pw().format(format, @@ -84,9 +84,9 @@ public class List extends BaseCmd { } } ); String ticket = null, prev = null; - for(Approval app : lapp ) { + for (Approval app : lapp ) { ticket = app.getTicket(); - if(!ticket.equals(prev)) { + if (!ticket.equals(prev)) { pw().print("Ticket: "); pw().println(ticket); } @@ -106,8 +106,8 @@ public class List extends BaseCmd { 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()) + for (Delg delg : delgs.getDelgs()) { + if (!this.aafcli.isTest()) date = Chrono.dateOnlyStamp(delg.getExpires()); pw().printf(format, delg.getUser(), 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 4bb87374..162dadac 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 @@ -58,7 +58,7 @@ public class ListActivity extends Cmd { "/authz/hist/user/"+user, getDF(History.class) ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { activity(fp.value,HEADER + " [ " + user + " ]"); } else { error(fp); 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 d9379174..068aacb1 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 @@ -67,9 +67,9 @@ public class ListApprovals extends Cmd { "/authz/approval/"+type+'/'+fullValue, getDF(Approvals.class) ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { ((List)parent).report(fp.value,HEADER + " by " + type,fullValue); - if(fp.code()==404) { + if (fp.code()==404) { return 200; } } else { 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 5cc7a52b..28b5c9e7 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 @@ -61,9 +61,9 @@ public class ListDelegates extends Cmd { "/authz/delegates/" + key + '/' + id, getDF(Delgs.class) ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { ((List)parent).report(fp.value,HEADER + " by " + key, id); - if(fp.code()==404)return 200; + if (fp.code()==404)return 200; } else { error(fp); } 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 a71090ea..4977b752 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 @@ -66,7 +66,7 @@ public class ListForCreds extends Cmd { "/authn/creds/"+which+'/'+value, getDF(Users.class) ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { if (aafcli.isTest()) Collections.sort(fp.value.getUser(), new Comparator() { @Override @@ -75,7 +75,7 @@ public class ListForCreds extends Cmd { } }); ((org.onap.aaf.auth.cmd.user.List)parent).report(fp.value,option==1,HEADER+which,value); - if(fp.code()==404)return 200; + if (fp.code()==404)return 200; } else { error(fp); } 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 439c8af6..516713ef 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 @@ -60,14 +60,14 @@ public class ListForPermission extends Cmd { int idx = index; String type = args[idx++]; String instance = args[idx++]; - if("\\*".equals(instance))instance="*"; + if ("\\*".equals(instance))instance="*"; String action = args[idx++]; - if("\\*".equals(action))action="*"; + if ("\\*".equals(action))action="*"; Future fp = client.read( "/authz/users/perm/"+type+'/'+instance+'/'+action, getDF(Users.class) ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { if (aafcli.isTest()) Collections.sort(fp.value.getUser(), new Comparator() { @Override @@ -76,7 +76,7 @@ public class ListForPermission extends Cmd { } }); ((org.onap.aaf.auth.cmd.user.List)parent).report(fp.value,false,HEADER,type+"|"+instance+"|"+action); - if(fp.code()==404)return 200; + if (fp.code()==404)return 200; } else { error(fp); } 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 1d1b328a..b534240b 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 @@ -60,7 +60,7 @@ public class ListForRoles extends Cmd { "/authz/users/role/"+role, getDF(Users.class) ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { if (aafcli.isTest()) Collections.sort(fp.value.getUser(), new Comparator() { @Override @@ -69,7 +69,7 @@ public class ListForRoles extends Cmd { } }); ((org.onap.aaf.auth.cmd.user.List)parent).report(fp.value,false, HEADER,role); - if(fp.code()==404)return 200; + if (fp.code()==404)return 200; } else { error(fp); } 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 04b444a1..4bc99366 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 @@ -108,7 +108,7 @@ public class Role extends Cmd { pw().println(" Accepted, but requires Approvals before actualizing"); break; case 404: - if(option==3) { + if (option==3) { pw().println("Failed with code 404: UserRole is not found, or you do not have permission to view"); break; } 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 13aa04fd..9393e143 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 @@ -89,7 +89,7 @@ public class Cache { public static Map obtain(String key) { Map m = cacheMap.get(key); - if(m==null) { + if (m==null) { m = new ConcurrentHashMap<>(); synchronized(cacheMap) { cacheMap.put(key, m); @@ -137,13 +137,13 @@ public class Cache { Date now = new Date(System.currentTimeMillis() + advance); - for(String name : set) { + for (String name : set) { Map map = cacheMap.get(name); - if(map==null) { + if (map==null) { continue; } - for(Map.Entry me : map.entrySet()) { + for (Map.Entry me : map.entrySet()) { ++total; if (me.getValue().timestamp.before(now)) { map.remove(me.getKey()); @@ -152,13 +152,13 @@ public class Cache { } } - if(count>0) { + 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) { + if (total>high) { // advance cleanup by 10%, without getting greater than timeInterval. advance = Math.min(timeInterval, advance+(timeInterval/10)); } else { @@ -169,20 +169,20 @@ public class Cache { } public static synchronized void startCleansing(Env env, String ... keys) { - if(cleanseTimer==null) { + 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) { + for (String key : keys) { clean.add(key); } } public static void stopTimer() { - if(cleanseTimer!=null) { + if (cleanseTimer!=null) { cleanseTimer.cancel(); cleanseTimer = null; } 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 606e7735..7bc1fdc6 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 @@ -38,14 +38,14 @@ public class Define { private static final String ROOT_NS_TAG_DOT = ROOT_NS_TAG +"."; public static String ROOT_NS() { - if(ROOT_NS==null) { + if (ROOT_NS==null) { throw new RuntimeException(Define.class.getName() + MSG); } return ROOT_NS; } public static String ROOT_COMPANY() { - if(ROOT_NS==null) { + if (ROOT_NS==null) { throw new RuntimeException(Define.class.getName() + MSG); } return ROOT_COMPANY; @@ -54,17 +54,17 @@ public class Define { 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) { + if (ROOT_COMPANY==null) { int last = ROOT_NS.lastIndexOf('.'); - if(last>=0) { + 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)) { + 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())); } } @@ -74,7 +74,7 @@ public class Define { } public static String varReplace(final String potential) { - if(potential.startsWith(ROOT_NS_TAG_DOT)) { + if (potential.startsWith(ROOT_NS_TAG_DOT)) { return ROOT_NS + potential.substring(6); } else { return potential; 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 70cee5c3..56db6f60 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 @@ -120,7 +120,7 @@ public class AuthzEnv extends RosettaEnv implements Access { public AuthzTransImpl newTrans() { synchronized(this) { times[idx]=System.currentTimeMillis(); - if(++idx>=times.length)idx=0; + if (++idx>=times.length)idx=0; } return new AuthzTransImpl(this); } @@ -137,18 +137,18 @@ public class AuthzEnv extends RosettaEnv implements Access { int count = 0; long pot = 0; long prev = 0; - for(int i=idx;i0) { - if(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) { + for (int i=0;i0) { + if (prev>0) { ++count; pot += times[i]-prev; } @@ -199,11 +199,11 @@ public class AuthzEnv extends RosettaEnv implements Access { private static final byte[] ENC="enc:".getBytes(); public String decrypt(String encrypted, final boolean anytext) throws IOException { - if(encrypted==null) { + 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) { + if (anytext || encrypted.startsWith("enc:")) { + if (decryptor.equals(Decryptor.NULL) && getProperty(Config.CADI_KEYFILE)!=null) { final Symm s; try { s = Symm.obtain(this); 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 06fd310e..b08e0240 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 @@ -54,10 +54,10 @@ public class AuthzTransFilter extends TransFilter { this.env = env; serviceMetric = new Metric(); serviceMetric.buckets = new float[BUCKETSIZE]; - if(transIDslot==null) { + if (transIDslot==null) { transIDslot = env.slot(TRANS_ID_SLOT); } - if(specialLogSlot==null) { + if (specialLogSlot==null) { specialLogSlot = env.slot(SPECIAL_LOG_SLOT); } } @@ -89,7 +89,7 @@ public class AuthzTransFilter extends TransFilter { Boolean b = trans.get(specialLogSlot, false); LogTarget lt = b?trans.warn():trans.info(); - if(lt.isLoggable()) { + 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 @@ -98,12 +98,12 @@ public class AuthzTransFilter extends TransFilter { // Add current Metrics to total metrics serviceMetric.total+= m.total; - for(int i=0;i { sb.append(trans.port()); // Current code won't ever get here... Always does a Full Audit Trail // Long tsi; -// if((tsi=trans.get(transIDslot, null))!=null) { +// if ((tsi=trans.get(transIDslot, null))!=null) { // sb.append(",TraceID="); // sb.append(Long.toHexString(tsi)); // } @@ -165,10 +165,10 @@ public class AuthzTransFilter extends TransFilter { sb.append(",path="); sb.append(trans.path()); - if(content.length()>0) { + if (content.length()>0) { sb.append(",msg=\""); int start = content.lastIndexOf(",msg=\""); - if(start>=0) { + if (start>=0) { sb.append(content,start+6,content.length()-1); } else { sb.append(content); 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 ee90f284..aa6b038b 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 @@ -60,12 +60,12 @@ public class AuthzTransImpl extends BasicTrans implements AuthzTrans { meth = req.getMethod(); path = req.getPathInfo(); - for(REQD_TYPE rt : REQD_TYPE.values()) { + for (REQD_TYPE rt : REQD_TYPE.values()) { requested(rt,req); } // Handle alternate "request" for "future" String request = req.getParameter("request"); - if(request!=null) { + if (request!=null) { requested(REQD_TYPE.future,(request.length()==0 || "true".equalsIgnoreCase(request))); } @@ -146,7 +146,7 @@ public class AuthzTransImpl extends BasicTrans implements AuthzTrans { } public void requested(REQD_TYPE requested, boolean b) { - if(b) { + if (b) { mask|=requested.bit; } else { mask&=~requested.bit; @@ -155,7 +155,7 @@ public class AuthzTransImpl extends BasicTrans implements AuthzTrans { private void requested(REQD_TYPE reqtype, HttpServletRequest req) { String p = req.getParameter(reqtype.name()); - if(p!=null) { + if (p!=null) { requested(reqtype,p.length()==0 || "true".equalsIgnoreCase(p)); } } @@ -167,7 +167,7 @@ public class AuthzTransImpl extends BasicTrans implements AuthzTrans { @Override public boolean fish(Permission ... pond) { - if(lur!=null) { + if (lur!=null) { return lur.fish(user, pond); } return false; @@ -178,9 +178,9 @@ public class AuthzTransImpl extends BasicTrans implements AuthzTrans { */ @Override public Organization org() { - if(org==null) { + if (org==null) { try { - if((org = OrganizationFactory.obtain(env(), user()))==null) { + if ((org = OrganizationFactory.obtain(env(), user()))==null) { org = Organization.NULL; } } catch (Exception e) { @@ -196,7 +196,7 @@ public class AuthzTransImpl extends BasicTrans implements AuthzTrans { */ @Override public void logAuditTrail(LogTarget lt) { - if(lt.isLoggable()) { + if (lt.isLoggable()) { StringBuilder sb = new StringBuilder(); auditTrail(1, sb); lt.log(sb); @@ -208,7 +208,7 @@ public class AuthzTransImpl extends BasicTrans implements AuthzTrans { */ @Override public Date now() { - if(now==null) { + 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 d7b6f1da..b1111638 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 @@ -70,7 +70,7 @@ public class AuthzTransOnlyFilter extends TransOnlyFilter { 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 { protected Result(RV value, int status, String details, String[] variables) { this.value = value; - if(value==null) { + if (value==null) { specialCondition|=EMPTY_LIST; } this.status = status; this.details = details; - if(variables==null) { + if (variables==null) { this.variables = EMPTY_VARS; } else { this.variables=variables; @@ -290,17 +290,17 @@ public class Result { @Override public String toString() { - if(status==0) { + if (status==0) { return details; } else { StringBuilder sb = new StringBuilder(); sb.append(status); sb.append(':'); sb.append(String.format(details,((Object[])variables))); - if(isEmpty()) { + if (isEmpty()) { sb.append("{empty}"); } - if(value!=null) { + if (value!=null) { sb.append('-'); sb.append(value.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 90857b42..6f644bd4 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 @@ -74,14 +74,14 @@ public abstract class AbsData implements Iterable { TimeTaken tt = trans.start("Open Data File", Env.SUB); boolean first = true; try { - if(!dataf.exists()) { + 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()) && begin { } begin = System.currentTimeMillis(); } - if(exists) { + if (exists) { throw new IOException(lockf.getCanonicalPath() + "exists. May not open Datafile"); } data.open(); @@ -110,12 +110,12 @@ public abstract class AbsData implements Iterable { } private synchronized void ensureIdxGood(AuthzTrans trans) throws IOException { - if(!idxf.exists() || idxf.length()==0 || dataf.lastModified()>idxf.lastModified()) { + if (!idxf.exists() || idxf.length()==0 || dataf.lastModified()>idxf.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)) { + if (!idxf.exists() || (idxf.length()==0 && dataf.length()!=0)) { throw new IOException("Data Index File did not create correctly"); } } finally { @@ -189,7 +189,7 @@ public abstract class AbsData implements Iterable { @Override public String next() { - if(!hasNext()) { + if (!hasNext()) { throw new NoSuchElementException(); } reuse.reset(); 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 7e420df4..a65c13db 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 @@ -43,7 +43,7 @@ public class DataFile { this.access = access; } public void open() throws IOException { - if(!file.exists()) throw new FileNotFoundException(); + 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()); @@ -52,10 +52,10 @@ public class DataFile { return mapBuff!=null; } public void close() throws IOException { - if(channel!=null){ + if (channel!=null){ channel.close(); } - if(rafile!=null) { + if (rafile!=null) { rafile.close(); } mapBuff = null; @@ -67,7 +67,7 @@ public class DataFile { private synchronized int load(Token t) { int len = Math.min(mapBuff.limit()-t.next,t.buff.length); - if(len>0) { + if (len>0) { mapBuff.position(t.next); mapBuff.get(t.buff,0,len); } @@ -91,8 +91,8 @@ public class DataFile { public boolean nextLine() { end = load(this); pos = next; - for(int i=0;i=end)return null; + if (idx>=end)return null; int start = idx; byte c=0; int endStr = -1; - while(idx=end)?1:0))); 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 bb1b6117..73ad07c7 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 @@ -54,7 +54,7 @@ public class TextIndex { } public void close() throws IOException { - if(dataFile!=null) { + if (dataFile!=null) { dataFile.close(); dataFile=null; } @@ -65,7 +65,7 @@ public class TextIndex { } public int find(Object key, DataFile.Token dtok, Field df, int offset) throws IOException { - if(dataFile==null) { + if (dataFile==null) { throw new IOException("File not opened"); } long hash = hashToLong(key.hashCode()); @@ -74,13 +74,13 @@ public class TextIndex { IntBuffer tib = ttok.getIntBuffer(); long lhash; int curr; - while((max-min)>100) { + while ((max-min)>100) { ttok.pos((curr=(min+(max-min)/2))*REC_SIZE); tib.rewind(); lhash = hashToLong(tib.get()); - if(lhashhash) { + } else if (lhash>hash) { max=curr-1; } else { min=curr-40; @@ -90,20 +90,20 @@ public class TextIndex { } List entries = new ArrayList<>(); - for(int i=min;i<=max;++i) { + for (int i=min;i<=max;++i) { ttok.pos(i*REC_SIZE); tib.rewind(); lhash = hashToLong(tib.get()); - if(lhash==hash) { + if (lhash==hash) { entries.add(tib.get()); - } else if(lhash>hash) { + } else if (lhash>hash) { break; } } - for(Integer i : entries) { + for (Integer i : entries) { dtok.pos(i); - if(df.at(offset).equals(key)) { + if (df.at(offset).equals(key)) { return i; } } @@ -116,7 +116,7 @@ public class TextIndex { */ private static long hashToLong(int hash) { long rv; - if(hash<0) { + if (hash<0) { rv = 0xFFFFFFFFL & hash; } else { rv = hash; @@ -145,15 +145,15 @@ public class TextIndex { Field f = t.new Field(delim); int count = 0; - if(skipLines>0) { + if (skipLines>0) { trans.info().log("Skipping",skipLines,"line"+(skipLines==1?" in":"s in"),data.file().getName()); } - for(int i=0;i es : env.getProperties().entrySet()) { + for (Entry es : env.getProperties().entrySet()) { String key = es.getKey().toString(); - if(key.startsWith(ORGANIZATION_DOT)) { + if (key.startsWith(ORGANIZATION_DOT)) { org = obtain(env,key.substring(idx)); - if(firstOrg==null) { + if (firstOrg==null) { firstOrg = org; } } } - if(defaultOrg == null) { + if (defaultOrg == null) { defaultOrg = firstOrg; } return defaultOrg; } public static Organization obtain(Env env,final String theNS) throws OrganizationException { String orgNS; - if(theNS.indexOf('@')>=0) { + if (theNS.indexOf('@')>=0) { orgNS=FQI.reverseDomain(theNS); } else { orgNS=theNS; } Organization org = orgs.get(orgNS); - if(org == null) { + if (org == null) { env.debug().printf("Attempting to instantiate Organization %s\n",orgNS); String orgClass = env.getProperty(ORGANIZATION_DOT+orgNS); - if(orgClass == null) { + 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)) { + for (Organization o : orgs.values()) { + if (o.getClass().isAssignableFrom(orgCls)) { org = o; } } @@ -93,15 +93,15 @@ public class OrganizationFactory { env.error().log(e1, orgClass + " is not on the Classpath."); throw new OrganizationException(e1); } - if(org==null) { + 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)) { + if (other_realms!=null) { + for (String r : Split.splitTrim(',', other_realms)) { org.addSupportedRealm(r); } } @@ -114,13 +114,13 @@ public class OrganizationFactory { } orgs.put(orgNS, org); boolean isDefault; - if((isDefault="true".equalsIgnoreCase(env.getProperty(orgNS+".default")))) { + 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) { + if (org==null) { + if (defaultOrg!=null) { org=defaultOrg; orgs.put(orgNS, org); } @@ -133,7 +133,7 @@ public class OrganizationFactory { public static Organization get(AuthzTrans trans) throws OrganizationException { String domain = FQI.reverseDomain(trans.user()); Organization org = orgs.get(domain); - if(org==null) { + 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 30924dd5..0e70e25e 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 @@ -46,16 +46,16 @@ class Acceptor { private boolean eval(HttpCode code, String str, List props) { // int plus = str.indexOf('+'); -// if(plus<0) { +// if (plus<0) { boolean ok = false; boolean any = false; - for(Pair, List>>> type : types) { + for (Pair, List>>> type : types) { ok = true; - if(type.x.equals(str)) { - for(Iterator iter = props.iterator();ok && iter.hasNext();) { + if (type.x.equals(str)) { + for (Iterator iter = props.iterator();ok && iter.hasNext();) { ok = props(type,iter.next(),iter.next()); } - if(ok) { + if (ok) { any = true; acceptable.add(type); } @@ -65,11 +65,11 @@ class Acceptor { // int prev = str.indexOf('/')+1; // String first = str.substring(0,prev); // String nstr; -// while(prev!=0) { +// while (prev!=0) { // nstr = first + (plus<0?str.substring(prev):str.substring(prev,plus)); // -// for(Pair, List>>> type : types) { -// if(type.x.equals(nstr)) { +// for (Pair, List>>> type : types) { +// if (type.x.equals(nstr)) { // acceptable.add(type); // return type; // } @@ -90,14 +90,14 @@ class Acceptor { */ 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")) { + 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")) { + } 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 + } else if (tag.equals(Content.Q)) { // replace Q value try { type.y.y.get(0).y=Float.parseFloat(value); } catch (NumberFormatException e) { @@ -135,34 +135,34 @@ class Acceptor { name=null; cis = cie+1; // find comma start - while(ciscis && Character.isSpaceChar(bytes[cend-1]))--cend; + while (cend>cis && 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 + 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 && eqsis && eq=cis); // End SEMI processing + } while (sie<=cend && sie>=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 + 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 } 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 53511b40..9af11152 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 @@ -66,12 +66,12 @@ 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 extends HttpCode extends HttpCode extends HttpCode0?key+'/'+cmd:key, null, checkInterval); - if(c.attachmentOnly) { + if (c.attachmentOnly) { resp.setHeader("Content-disposition", "attachment"); } c.setHeader(resp); @@ -214,12 +214,12 @@ public class CachingFileAccess extends HttpCode extends HttpCodec.date) { + if (f.lastModified()>c.date) { c=null; } } } - if(c==null) { - if(logTarget!=null) { + if (c==null) { + if (logTarget!=null) { logTarget.log("File Read: ",key); } - if(f==null){ + if (f==null){ f = new File(fileName); } boolean cacheMe; - if(f.exists()) { - if(f.isDirectory()) { + if (f.exists()) { + if (f.isDirectory()) { cacheMe = false; c = new DirectoryContent(f,isRoot); } else { - if(f.length() > maxItemSize) { + if (f.length() > maxItemSize) { c = new DirectFileContent(f); cacheMe = false; } else { @@ -260,10 +260,10 @@ public class CachingFileAccess extends HttpCode0; } - if(mediaType==null) { // determine from file Ending + 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 ((c.contentType = idx<0?null:typeMap.get(subkey))==null) { // if nothing else, just set to default type... c.contentType = "application/octet-stream"; } @@ -275,7 +275,7 @@ public class CachingFileAccess extends HttpCode extends HttpCode extends HttpCode extends HttpCode=0) { + while ((read = fr.read(buff,0,1024))>=0) { writer.write(buff,0,read); } } finally { @@ -387,7 +387,7 @@ public class CachingFileAccess extends HttpCode=0) { + while ((read = fis.read(buff,0,1024))>=0) { os.write(buff,0,read); } } finally { @@ -415,13 +415,13 @@ public class CachingFileAccess extends HttpCode extends HttpCode extends HttpCode extends HttpCodemaxSize) { + 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/Content.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Content.java index f8760ada..63a2eeaa 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 @@ -80,13 +80,13 @@ public abstract class Content { sis = sie+1; sie = cntnt.indexOf(';',sis); send = sie>cend || sie<0?cend:sie; - if(me==null) { + 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) { + if (me==null) { sie=-1; // skip the rest of the processing... not a type } else { contType=true; @@ -95,20 +95,20 @@ public abstract class Content { // If there are additional elements (more entities within Semi Colons) // apply Propertys int eq = cntnt.indexOf('=',sis); - if(eq>sis && eqsis && eq { */ public String pathParam(HttpServletRequest req, String key) { String rv = req.getParameter(key); - if(rv==null) { + if (rv==null) { rv = match.param(req.getPathInfo(), key); - if(rv!=null) { + if (rv!=null) { rv = rv.trim(); - if(rv.endsWith("/")) { + if (rv.endsWith("/")) { rv = rv.substring(0, rv.length()-1); } } @@ -102,10 +102,10 @@ public abstract class HttpCode { * @return */ public boolean isAuthorized(HttpServletRequest req) { - if(all)return true; - if(roles!=null) { - for(String srole : roles) { - if(req.isUserInRole(srole)) return true; + if (all)return true; + if (roles!=null) { + for (String srole : roles) { + if (req.isUserInRole(srole)) return true; } } return false; diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Match.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Match.java index 5a036551..599e45b2 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Match.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Match.java @@ -52,16 +52,16 @@ public class Match { public Match(String path) { // IF DEBUG: System.out.print("\n[" + path + "]"); params = new HashMap<>(); - if(path!=null) { + 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) { + if (pa[i].length()>1) { /* remove * from value */ int newlength = values[i].length-1; byte[] real = new byte[newlength]; @@ -107,25 +107,25 @@ public class Match { */ public String param(String path,String key) { Integer val = params.get(key); // :key or key - if(val!=null) { + if (val!=null) { int start = val & 0xFFFF; int end = (val >> 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 / + 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 + 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; + 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 + if (k==lastByte && pabytes[k-1]!='/')++field; + if (k>i)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 (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) { + if (fieldIdx==0 && values[field].length==0) { fieldMatched = true; } rv = fieldMatched && ++field implements Servlet { @SuppressWarnings("unchecked") TRANS trans = (TRANS)req.getAttribute(TransFilter.TRANS_TAG); - if(trans==null) { + if (trans==null) { response.setStatus(404); // Not Found, because it didn't go through TransFilter return; } @@ -79,7 +79,7 @@ public abstract class RServlet implements Servlet { CodeSetter codesetter = new CodeSetter(trans,request,response); // Find declared route route = routes.derive(request, codesetter); - if(route==null) { + if (route==null) { String method = request.getMethod(); trans.checkpoint("No Route matches "+ method + ' ' + request.getPathInfo()); response.setStatus(404); // Not Found @@ -91,12 +91,12 @@ public abstract class RServlet implements Servlet { tt.done(); } - if(route!=null && code!=null) { + if (route!=null && code!=null) { StringBuilder sb = new StringBuilder(72); sb.append(route.auditText); sb.append(','); sb.append(code.desc()); - if(ct!=null) { + if (ct!=null) { sb.append(", ContentType: "); sb.append(ct); } 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 81b3d0a2..b11916ef 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 @@ -67,18 +67,18 @@ public class Route { // FYI, thought about this a long time before implementing this way. String compare; // String special[]; // todo, expose Charset (in special) to outside - if(isGet) { + 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) { + 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 + 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); 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 7c69d9b7..de42e26b 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 @@ -47,12 +47,12 @@ public class Routes { // Package on purpose synchronized Route findOrCreate(HttpMethods meth, String path) { Route rv = null; - for(int i=0;i=routes.length) { + if (rv==null) { + if (end>=routes.length) { @SuppressWarnings("unchecked") Route[] temp = new Route[end+10]; System.arraycopy(routes, 0, temp, 0, routes.length); @@ -69,9 +69,9 @@ public class Routes { String path = req.getPathInfo(); String meth = req.getMethod(); //TODO a TREE would be better - for(int i=0;rv==null && i { public List routeReport() { ArrayList ltr = new ArrayList<>(); - for(int i=0;i implements Filter { 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) { + if (no!=null) { no_authn = Split.split(':', no); } else { no_authn=null; @@ -101,9 +101,9 @@ public abstract class TransFilter implements Filter { try { request.setAttribute(TRANS_TAG, trans); - if(no_authn!=null) { - for(String prefix : no_authn) { - if(req.getPathInfo().startsWith(prefix)) { + if (no_authn!=null) { + for (String prefix : no_authn) { + if (req.getPathInfo().startsWith(prefix)) { chain.doFilter(request, response); return; } @@ -128,9 +128,9 @@ public abstract class TransFilter implements Filter { security.done(); } - if(r==RESP.IS_AUTHENTICATED) { + if (r==RESP.IS_AUTHENTICATED) { trans.checkpoint(resp.desc()); - if(cadi.notCadi(cw, res)) { + if (cadi.notCadi(cw, res)) { chain.doFilter(cw, response); } } else { @@ -138,10 +138,10 @@ public abstract class TransFilter implements Filter { // Would need Cached Counter objects that are cleaned up on // use trans.checkpoint(resp.desc(),Env.ALWAYS); - if(resp.isFailedAttempt()) + if (resp.isFailedAttempt()) trans.audit().log(resp.desc()); } - } catch(Exception e) { + } catch (Exception e) { trans.error().log(e); trans.checkpoint("Error: " + e.getClass().getSimpleName() + ": " + e.getMessage()); throw new ServletException(e); 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 8c57838d..1a66cf7d 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 @@ -72,8 +72,8 @@ public class TypedCode extends Content { public TypedCode add(HttpCode code, String ... others) { StringBuilder sb = new StringBuilder(); boolean first = true; - for(String str : others) { - if(first) { + for (String str : others) { + if (first) { first = false; } else { sb.append(','); @@ -94,7 +94,7 @@ public class TypedCode extends Content { Pair, List>> cl = new Pair, List>>(code, props); // // breakup "plus" stuff, i.e. application/xaml+xml // int plus = str.indexOf('+'); -// if(plus<0) { +// if (plus<0) { type = new Pair,List>>>(str, cl); types.add(type); return type; @@ -102,7 +102,7 @@ public class TypedCode extends Content { // int prev = str.indexOf('/')+1; // String first = str.substring(0,prev); // String nstr; -// while(prev!=0) { +// while (prev!=0) { // nstr = first + (plus>-1?str.substring(prev,plus):str.substring(prev)); // type = new Pair,List>>>(nstr, cl); // types.add(type); @@ -115,7 +115,7 @@ public class TypedCode extends Content { @Override protected boolean props(Pair, List>>> type, String tag, String value) { - if(tag.equals(Q)) { // reset the Q value (first in array) + if (tag.equals(Q)) { // reset the Q value (first in array) boolean rv = true; try { type.y.y.get(0).y=Float.parseFloat(value); @@ -130,10 +130,10 @@ public class TypedCode extends Content { 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 + 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) { + if (compare==null || compare.length()==0) { rv = types.get(0); // first code is used } else { Acceptor acc = new Acceptor(types); @@ -144,7 +144,7 @@ public class TypedCode extends Content { } finally { tt.done(); } - if(accepted) { + if (accepted) { switch(acc.acceptable.size()) { case 0: // // TODO best Status Code? @@ -156,16 +156,16 @@ public class TypedCode extends Content { default: // compare Q values to get Best Match float bestQ = -1.0f; Pair, List>>> bestT = null; - for(Pair, List>>> type : acc.acceptable) { + for (Pair, List>>> type : acc.acceptable) { Float f = (Float)type.y.y.get(0).y; // first property is always Q - if(f>bestQ) { + if (f>bestQ) { bestQ=f; bestT = type; } } - if(bestT!=null) { + 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 +// if (isGet)resp.setContentType(bestT.x); // set ContentType of Code // rv = bestT.y.x; rv = bestT; } @@ -190,17 +190,17 @@ public class TypedCode extends Content { */ public StringBuilder relatedTo(HttpCode code, StringBuilder sb) { boolean first = true; - for(Pair, List>>> pair : types) { - if(code==null || pair.y.x == code) { - if(first) { + 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) { + 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) ) { + if (!prop.x.equals(Q) || !prop.y.equals(1f) ) { sb.append(';'); sb.append(prop.x); sb.append('='); @@ -213,8 +213,8 @@ public class TypedCode extends Content { } public List> getContent(HttpCode code) { - for(Pair, List>>> pair : types) { - if(pair.y.x == code) { + for (Pair, List>>> pair : types) { + if (pair.y.x == code) { return pair.y.y; } } @@ -232,11 +232,11 @@ public class TypedCode extends Content { tr.desc = null; // Read through Code/TypeCode trees for all accepted Typecodes - for(Pair, List>>> tc : types) { + for (Pair, List>>> tc : types) { // If new, then it's new Code set, create prefix content - if((temp=psb.get(tc.y.x))==null) { + if ((temp=psb.get(tc.y.x))==null) { psb.put(tc.y.x,temp=new StringBuilder()); - if(tr.desc==null) { + if (tr.desc==null) { tr.desc = tc.y.x.desc(); } } else { @@ -245,7 +245,7 @@ public class TypedCode extends Content { temp.append(tc.x); // add all properties - for(Pair props : tc.y.y) { + for (Pair props : tc.y.y) { temp.append(';'); temp.append(props.x); temp.append('='); @@ -254,13 +254,13 @@ public class TypedCode extends Content { } // Gather all ContentType possibilities for the same code together - for(StringBuilder sb : psb.values()) { + for (StringBuilder sb : psb.values()) { tr.contextTypes.add(sb.toString()); } } public String first() { - if(types.size()>0) { + if (types.size()>0) { return types.get(0).x; } return null; 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 f4818579..adf05380 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 @@ -35,7 +35,7 @@ public class Version { 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 + 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) { @@ -46,20 +46,20 @@ public class Version { } public boolean equals(Object obj) { - if(obj instanceof Version) { + if (obj instanceof Version) { Version ver = (Version)obj; int length = Math.min(parts.length, ver.parts.length); - for(int i=0;i exte String component = access.getProperty(Config.AAF_COMPONENT, null); final String[] locator_deploy; - if(component == null) { + if (component == null) { locator_deploy = null; } else { locator_deploy = Split.splitTrim(':', component); } - if(component == null || locator_deploy==null || locator_deploy.length<2) { + if (component == null || locator_deploy==null || locator_deploy.length<2) { throw new CadiException("AAF Component must include the " + Config.AAF_COMPONENT + " property, : exte app_interface_version = version[0]+'.'+version[1]; // Print Cipher Suites Available - if(access.willLog(Level.DEBUG)) { + if (access.willLog(Level.DEBUG)) { SSLContext context; try { context = SSLContext.getDefault(); @@ -94,11 +94,11 @@ public abstract class AbsService exte StringBuilder sb = new StringBuilder("Available Cipher Suites: "); boolean first = true; int count=0; - for( String cs : sf.getSupportedCipherSuites()) { - if(first)first = false; + for ( String cs : sf.getSupportedCipherSuites()) { + if (first)first = false; else sb.append(','); sb.append(cs); - if(++count%4==0){sb.append('\n');} + if (++count%4==0){sb.append('\n');} } access.log(Level.DEBUG,sb); } @@ -121,8 +121,8 @@ public abstract class AbsService exte // Lazy Instantiation public synchronized AAFConHttp aafCon() throws CadiException, LocatorException { - if(aafCon==null) { - if(access.getProperty(Config.AAF_URL,null)!=null) { + 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); @@ -137,7 +137,7 @@ public abstract class AbsService exte * @throws LocatorException */ protected synchronized AAFConHttp _newAAFConHttp() throws CadiException, LocatorException { - if(aafCon==null) { + if (aafCon==null) { aafCon = new AAFConHttp(access); } return aafCon; @@ -165,20 +165,20 @@ public abstract class AbsService exte 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)) { + 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) { + if (value!=null) { props.put(tag, value); return value; } - if(def!=null) { + 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 f14d6c32..29166b0b 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 @@ -72,11 +72,11 @@ public abstract class AbsServiceStarter ... registrants) { - if(do_register) { - if(registrar==null) { + if (do_register) { + if (registrar==null) { registrar = new Registrar(env(),false); } - for(Registrant r : registrants) { + for (Registrant r : registrants) { registrar.register(r); } } @@ -84,11 +84,11 @@ public abstract class AbsServiceStarter ex // 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) { +// 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"))) { +// 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()); @@ -98,15 +98,15 @@ public class JettyServiceStarter ex 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) { + 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")))) { + 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); } } @@ -114,7 +114,7 @@ public class JettyServiceStarter ex @Override public void _start(RServlet rserv) throws Exception { String hostname = access().getProperty(Config.HOSTNAME, null); - if(hostname==null) { + if (hostname==null) { hostname = Inet4Address.getLocalHost().getHostName(); } final int port = Integer.parseInt(access().getProperty("port","0")); @@ -124,14 +124,14 @@ public class JettyServiceStarter ex ServerConnector conn; String protocol; - if(!secure || keystore==null) { + 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) { + if (keystorePassword==null) { throw new CadiException("No Keystore Password configured for " + keystore); } SslContextFactory sslContextFactory = new SslContextFactory(); @@ -142,9 +142,9 @@ public class JettyServiceStarter ex temp=null; // don't leave lying around String truststore = access().getProperty(Config.CADI_TRUSTSTORE, null); - if(truststore!=null) { + if (truststore!=null) { String truststorePassword = access().getProperty(Config.CADI_TRUSTSTORE_PASSWORD, null); - if(truststorePassword==null) { + if (truststorePassword==null) { throw new CadiException("No Truststore Password configured for " + truststore); } sslContextFactory.setTrustStorePath(truststore); @@ -163,7 +163,7 @@ public class JettyServiceStarter ex // sslContextFactory.setEnableCRLDP(false); // sslContextFactory.setEnableOCSP(false); String certAlias = access().getProperty(Config.CADI_ALIAS, null); - if(certAlias!=null) { + if (certAlias!=null) { sslContextFactory.setCertAlias(certAlias); } @@ -232,7 +232,7 @@ public class JettyServiceStarter ex 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) { + } catch (Exception e) { access().log(e,"Error registering " + service.app_name); String doExit = access().getProperty("cadi_exitOnFailure", "true"); if (doExit == "true") { @@ -246,7 +246,7 @@ public class JettyServiceStarter ex 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) { + for (int i=filters.length-1;i>=0;--i) { fc = new FCImpl(filters[i],fc); } return fc; 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 31b76395..fd0691b6 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 @@ -55,14 +55,14 @@ public class Log4JLogIt implements LogIt { 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()) { + if (!logs.isDirectory()) { logs.delete(); } - if(!logs.exists()) { + if (!logs.exists()) { logs.mkdirs(); } - if(System.getProperty("log4j.configuration")==null) { + if (System.getProperty("log4j.configuration")==null) { System.setProperty("log4j.configuration", etc_dir+'/'+propsFile); } LogFileNamer lfn = new LogFileNamer(log_dir,root); @@ -86,14 +86,14 @@ public class Log4JLogIt implements LogIt { 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)) { + for (String arg : args) { + if (arg.startsWith(tagEQ)) { return arg.substring(tagEQ.length()); } } // check System.properties value = System.getProperty(tag); - if(value!=null) { + if (value!=null) { return value; } 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 eb721285..1c9f4123 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 @@ -70,16 +70,16 @@ public class Validator { } public final Validator nullOrBlank(String name, String str) { - if(str==null) { + if (str==null) { msg(name + " is null."); - } else if(str.length()==0) { + } else if (str.length()==0) { msg(name + " is blank."); } return this; } public final Validator isNull(String name, Object o) { - if(o==null) { + if (o==null) { msg(name + " is null."); } return this; @@ -93,10 +93,10 @@ public class Validator { } protected final void msg(String ... strs) { - if(msgs==null) { + if (msgs==null) { msgs=new StringBuilder(); } - for(String str : strs) { + for (String str : strs) { msgs.append(str); } msgs.append('\n'); @@ -107,23 +107,23 @@ public class Validator { } public final Validator notOK(Result res) { - if(res==null) { + if (res==null) { msgs.append("Result object is blank"); - } else if(res.notOK()) { + } 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) { + 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) { + if (targetend) { msg(text + " is out of range (" + start + '-' + end + ')'); } return this; @@ -137,25 +137,25 @@ public class Validator { } public final Validator permType(String type) { - if(nob(type,NAME_CHARS)) { + if (nob(type,NAME_CHARS)) { msg("Perm Type [" +type + "] is invalid."); } return this; } public final Validator permType(String type, String ns) { - if(type==null) { + if (type==null) { msg("Perm Type is null"); - } else if(ns==null) { + } else if (ns==null) { msg("Perm NS is null"); - } else if(nob(type,NAME_CHARS)) { + } 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)) { + if (nob(instance,instChars)) { msg("Perm Instance [" + instance + "] is invalid."); } return this; @@ -163,28 +163,28 @@ public class Validator { public final Validator permAction(String action) { // TODO check for correct Splits? Type|Instance|Action ? - if(nob(action, actionChars)) { + if (nob(action, actionChars)) { msg("Perm Action [" + action + "] is invalid."); } return this; } public final Validator role(String role) { - if(nob(role, NAME_CHARS)) { + if (nob(role, NAME_CHARS)) { msg("Role [" + role + "] is invalid."); } return this; } public final Validator ns(String ns) { - if(ns==null) { + if (ns==null) { msg("NS is null"); return this; - } else if(nob(ns,NAME_CHARS)) { + } else if (nob(ns,NAME_CHARS)) { msg("NS [" + ns + "] is invalid."); } - for(String s : nsKeywords) { - if(ns.endsWith(s)) { + for (String s : nsKeywords) { + if (ns.endsWith(s)) { msg("NS [" + ns + "] may not be named with NS keywords"); break; } @@ -193,14 +193,14 @@ public class Validator { } public final Validator key(String key) { - if(nob(key,NAME_CHARS)) { + 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)) { + 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/local/test/JU_AbsData.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/local/test/JU_AbsData.java index a88b005d..2bc7dfa0 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 @@ -74,7 +74,7 @@ public class JU_AbsData { 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 + for (int i = 0; i< 10; i++) { //Write lines to file w.write("a\nsdfasdfxasdf" + i + "\n"); } w.close(); 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 099a9f00..b0af89ce 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 @@ -53,13 +53,13 @@ public class JU_DataFile { // Token tok = df.new Token(1024000); // Field fld = tok.new Field('|'); // -// while(tok.nextLine()) { +// while (tok.nextLine()) { // ++count; // fld.reset(); // list.add(fld.at(0)); // } //// Collections.sort(list); -// for(String s: list) { +// for (String s: list) { // System.out.println(s); // // } 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 fadc3b67..d4330296 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 @@ -83,7 +83,7 @@ public class JU_TextIndex { 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 + for (int i = 0; i< 10; i++) { //Write lines to file w.write("a\nsdfasdfxasdf" + i + "\n"); } w.close(); 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 acbaa9c8..0786c134 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 @@ -59,10 +59,10 @@ public class NSAttribCompare extends RosettaCompare { @Override public void compare(NsAttribRequest t1, NsAttribRequest t2) { assertEquals(t1.getNs(),t2.getNs()); - for(Attrib a1 : t1.getAttrib()) { + for (Attrib a1 : t1.getAttrib()) { boolean ok = false; - for(Attrib a2 : t2.getAttrib()) { - if(a1.getKey().equals(a2.getKey()) && + for (Attrib a2 : t2.getAttrib()) { + if (a1.getKey().equals(a2.getKey()) && a1.getValue().equals(a2.getValue())) { ok = true; break; @@ -70,10 +70,10 @@ public class NSAttribCompare extends RosettaCompare { } assertTrue("a2 Attribs in a1",ok); } - for(Attrib a2 : t2.getAttrib()) { + for (Attrib a2 : t2.getAttrib()) { boolean ok = false; - for(Attrib a1 : t1.getAttrib()) { - if(a1.getKey().equals(a2.getKey()) && + for (Attrib a1 : t1.getAttrib()) { + if (a1.getKey().equals(a2.getKey()) && a1.getValue().equals(a2.getValue())) { ok = true; break; 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 53f78b7c..c3504216 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 @@ -56,10 +56,10 @@ public class NSCompare extends RosettaCompare { public void compare(NsRequest t1, NsRequest t2) { assertEquals(t1.getName(),t2.getName()); assertEquals(t1.getDescription(),t2.getDescription()); - for(String s : t1.getAdmin()) { + for (String s : t1.getAdmin()) { assertTrue(t2.getAdmin().contains(s)); } - for(String s : t2.getAdmin()) { + for (String s : t2.getAdmin()) { assertTrue(t1.getAdmin().contains(s)); } assertEquals(t1.getType(),t2.getType()); 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 5a581edc..c809c55f 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 @@ -286,7 +286,7 @@ public class JU_Validator { assertFalse(Validator.INST_CHARS.matcher("").matches()); - for( char c=0x20;c<0x7F;++c) { + for ( char c=0x20;c<0x7F;++c) { boolean b; switch(c) { case '?': 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 d9336d4e..4f2d9676 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 @@ -62,11 +62,11 @@ public class DefaultOrg implements Organization { String s; NAME=env.getProperty(realm + ".name","Default Organization"); mailHost = env.getProperty(s=(realm + ".mailHost"), null); - if(mailHost==null) { + if (mailHost==null) { throw new OrganizationException(s + PROPERTY_IS_REQUIRED); } mailFrom = env.getProperty(s=(realm + ".mailFrom"), null); - if(mailFrom==null) { + if (mailFrom==null) { throw new OrganizationException(s + PROPERTY_IS_REQUIRED); } @@ -88,16 +88,16 @@ public class DefaultOrg implements Organization { String defFile; String temp=env.getProperty(defFile = (getClass().getName()+".file")); File fIdentities=null; - if(temp==null) { + if (temp==null) { temp = env.getProperty(AAF_DATA_DIR); - if(temp!=null) { + 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()) { + if (!fIdentities.exists()) { env.warn().log("No",fIdentities.getCanonicalPath(),"exists. Creating."); - if(!dir.exists()) { + if (!dir.exists()) { dir.mkdirs(); } fIdentities.createNewFile(); @@ -105,18 +105,18 @@ public class DefaultOrg implements Organization { } } else { fIdentities = new File(temp); - if(!fIdentities.exists()) { + if (!fIdentities.exists()) { String dataDir = env.getProperty(AAF_DATA_DIR); - if(dataDir!=null) { + if (dataDir!=null) { fIdentities = new File(dataDir,temp); } } } - if(fIdentities!=null && fIdentities.exists()) { + if (fIdentities!=null && fIdentities.exists()) { identities = new Identities(fIdentities); } else { - if(fIdentities==null) { + if (fIdentities==null) { throw new OrganizationException("No Identities"); } else { throw new OrganizationException(fIdentities.getCanonicalPath() + " does not exist."); @@ -138,7 +138,7 @@ public class DefaultOrg implements Organization { static { typeSet = new HashSet<>(); - for(Types t : Types.values()) { + for (Types t : Types.values()) { typeSet.add(t.name()); } } @@ -185,9 +185,9 @@ public class DefaultOrg implements Organization { // have domain? int at = id.indexOf('@'); String sid; - if(at > 0) { + if (at > 0) { // Use this to prevent passwords to any but THIS domain. -// if(!id.regionMatches(at+1, domain, 0, id.length()-at-1)) { +// if (!id.regionMatches(at+1, domain, 0, id.length()-at-1)) { // return false; // } sid = id.substring(0,at); @@ -198,7 +198,7 @@ public class DefaultOrg implements Organization { return isValidID(trans, sid)==null; // Check Pattern (if checking existing is too long) - // if(id.endsWith(SUFFIX) && ID_PATTERN.matcher(id).matches()) { + // if (id.endsWith(SUFFIX) && ID_PATTERN.matcher(id).matches()) { // return true; // } // return false; @@ -232,13 +232,13 @@ public class DefaultOrg implements Organization { */ @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. + 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()) { + if (PASS_PATTERN.matcher(password).matches()) { return ""; } return "Password does not match " + NAME + " Password Standards"; @@ -430,7 +430,7 @@ public class DefaultOrg implements Organization { // 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)) { + if (rv.after(now)) { rv = now; } break; @@ -453,7 +453,7 @@ public class DefaultOrg implements Organization { // Delegations expire max in 2 months, renewable to 3 rv.add(GregorianCalendar.MONTH, 2); now.add(GregorianCalendar.MONTH, 3); - if(rv.after(now)) { + if (rv.after(now)) { rv = now; } break; @@ -483,9 +483,9 @@ public class DefaultOrg implements Organization { public List getApprovers(AuthzTrans trans, String user) throws OrganizationException { Identity orgIdentity = getIdentity(trans, user); List orgIdentitys = new ArrayList<>(); - if(orgIdentity!=null) { + if (orgIdentity!=null) { Identity supervisor = orgIdentity.responsibleTo(); - if(supervisor!=null) { + if (supervisor!=null) { orgIdentitys.add(supervisor); } } @@ -519,15 +519,15 @@ public class DefaultOrg implements Organization { switch(policy) { case OWNS_MECHID: case CREATE_MECHID: - if(vars.length>0) { + if (vars.length>0) { DefaultOrgIdentity thisID = getIdentity(trans,vars[0]); - if("a".equals(thisID.identity.status)) { // MechID + if ("a".equals(thisID.identity.status)) { // MechID DefaultOrgIdentity requestor = getIdentity(trans, trans.user()); - if(requestor!=null) { + if (requestor!=null) { Identity mechid = getIdentity(trans, vars[0]); - if(mechid!=null) { + if (mechid!=null) { Identity sponsor = mechid.responsibleTo(); - if(sponsor!=null && requestor.fullID().equals(sponsor.fullID())) { + if (sponsor!=null && requestor.fullID().equals(sponsor.fullID())) { return null; } else { return trans.user() + " is not the Sponsor of MechID " + vars[0]; @@ -558,19 +558,19 @@ public class DefaultOrg implements Organization { private String extractRealm(final String r) { int at; - if((at=r.indexOf('@'))>=0) { + 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)) { + if (r.endsWith(realm)) { return true; } else { String erealm = extractRealm(r); - for(String sr : supportedRealms) { - if(erealm.startsWith(sr)) { + for (String sr : supportedRealms) { + if (erealm.startsWith(sr)) { return true; } } @@ -588,8 +588,8 @@ public class DefaultOrg implements Organization { Boolean urgent) throws OrganizationException { if (mailer!=null) { List to = new ArrayList<>(); - for(String em : toList) { - if(em.indexOf('@')<0) { + for (String em : toList) { + if (em.indexOf('@')<0) { to.add(new DefaultOrgIdentity(trans, em, this).email()); } else { to.add(em); @@ -597,11 +597,11 @@ public class DefaultOrg implements Organization { } List cc = new ArrayList<>(); - if(ccList!=null) { - if(!ccList.isEmpty()) { + if (ccList!=null) { + if (!ccList.isEmpty()) { - for(String em : ccList) { - if(em.indexOf('@')<0) { + for (String em : ccList) { + if (em.indexOf('@')<0) { cc.add(new DefaultOrgIdentity(trans, em, this).email()); } else { cc.add(em); 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 25832620..ba616ade 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 @@ -62,7 +62,7 @@ public class DefaultOrgIdentity implements Identity { Reuse r = org.identities.reuse(); int at = key.indexOf(dorg.getDomain()); String search; - if(at>=0) { + if (at>=0) { search = key.substring(0,at); } else { search = key; @@ -71,7 +71,7 @@ public class DefaultOrgIdentity implements Identity { - if(identity==null) { + if (identity==null) { identity = Identities.NO_DATA; } } finally { @@ -84,7 +84,7 @@ public class DefaultOrgIdentity implements Identity { @Override public boolean equals(Object b) { - if(b instanceof DefaultOrgIdentity) { + if (b instanceof DefaultOrgIdentity) { return identity.id.equals(((DefaultOrgIdentity)b).identity.id); } return false; @@ -120,7 +120,7 @@ public class DefaultOrgIdentity implements Identity { @Override public Identity responsibleTo() throws OrganizationException { - if("".equals(identity.responsibleTo) && isFound()) { // cover the situation of Top Dog... reports to no-one. + if ("".equals(identity.responsibleTo) && isFound()) { // cover the situation of Top Dog... reports to no-one. return this; } else { return org.getIdentity(trans, identity.responsibleTo); @@ -151,9 +151,9 @@ public class DefaultOrgIdentity implements Identity { @Override public String mayOwn() { // Assume only Employees are responsible for Resources. - if(identity.status==null|| identity.status.length()==0) { + if (identity.status==null|| identity.status.length()==0) { return "Identity must have valid status"; - } else if(EMPLOYEE.equals(identity.status)) { + } else if (EMPLOYEE.equals(identity.status)) { return null; // This is "Yes, is Responsible" } else { return "Reponsible Party must be an Employee"; 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 345e6e82..9f65b418 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 @@ -134,7 +134,7 @@ public class Identities extends AbsData { r.reset(); // These are new, to allow for Thread Safety int rec = ti.find(key,r,0); - if(rec<0) { + if (rec<0) { return null; } r.pos(rec); 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 b8069ccc..ce34e2a1 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 @@ -56,7 +56,7 @@ public class JU_Identities { // AuthzTrans trans = env.newTransNoAvg(); // // Note: utilize TimeTaken, from trans.start if you want to time. // fids = new File(DATA_IDENTITIES); -// if(fids.exists()) { +// if (fids.exists()) { // ids = new Identities(fids); // ids.open(trans, 5000); // } else { @@ -72,7 +72,7 @@ public class JU_Identities { // @AfterClass // public static void tearDownAfterClass() throws Exception { // AuthzTrans trans = env.newTransNoAvg(); -// if(ids!=null) { +// if (ids!=null) { // ids.close(trans); // } // } 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 128c1f9b..e316e015 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 @@ -62,7 +62,7 @@ public class AAF_FS extends AbsService { 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) { + 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)); 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 9915082b..40105c6e 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 @@ -112,14 +112,14 @@ public class JU_AAF_FS { String[] strArr = {"aaf_component=aaf_com:po.nent"}; try { //AAF_FS.main(strArr); //Timeout caused in Jenkins but not in local - } catch(Exception e) { + } catch (Exception e) { //Failure expected until we understand how code is. } } @After public void cleanUp() { - for(File f : d.listFiles()) { + for (File f : d.listFiles()) { f.delete(); } d.delete(); 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 ecbd0a25..e533abbe 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 @@ -51,7 +51,7 @@ public class CUI extends HttpCode { int c; StringBuilder cmd = new StringBuilder(); - while((c=isr.read())>=0) { + while ((c=isr.read())>=0) { cmd.append((char)c); } 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 84ad1b1f..48164227 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 @@ -124,7 +124,7 @@ public class AAF_GUI extends AbsService implements State1) { + if (component.length>1) { deployedVersion =component[1]; } else { deployedVersion = "2.x"; @@ -217,7 +217,7 @@ public class AAF_GUI extends AbsService implements State fp, HTMLGen hgen, int indent) { - if(hgen!=null) { + if (hgen!=null) { String msg = aafCon.readableErrMsg(fp); hgen.incr(HTMLGen.P,"style=text-indent:"+indent*10+"px") .text("Error: ") 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 c5c14d3f..4f1a7e82 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 @@ -55,18 +55,18 @@ public class BreadCrumbs extends NamedCode { HttpServletRequest req = trans.get(gui.slot_httpServletRequest, null); StringBuilder key = new StringBuilder(); String value, hidden; - for(Page p : breadcrumbs) { + for (Page p : breadcrumbs) { hidden=""; // Add keys for page from commandline, where possible. - if(p.fields().length>0) { + if (p.fields().length>0) { boolean first = true; key.setLength(0); - for(String field : p.fields()) { - if((value=req.getParameter(field))==null) { + for (String field : p.fields()) { + if ((value=req.getParameter(field))==null) { hidden="style=display:none;"; break; } - if(first) { + if (first) { first = false; key.append('?'); } else { 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 d1817531..c25d6641 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 @@ -38,7 +38,7 @@ public class Display { 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();) { + for (Enumeration names = req.getParameterNames(); names.hasMoreElements();) { String key = names.nextElement(); - if(key.startsWith(field)) { + if (key.startsWith(field)) { try { int x = Integer.parseInt(key.substring(field.length())); - if(x>=array.length) { + if (x>=array.length) { String[] temp = new String[x+10]; System.arraycopy(temp, 0, temp, 0, array.length); array = temp; @@ -95,20 +95,20 @@ public class Display { @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();) { + for (Enumeration mm = req.getParameterNames();mm.hasMoreElements();) { String key = mm.nextElement(); - if(key.startsWith(field)) { + if (key.startsWith(field)) { try { int x = Integer.parseInt(key.substring(field.length())); - if(x>=array.length) { + if (x>=array.length) { String[] temp = new String[x+10]; System.arraycopy(temp, 0, temp, 0, array.length); array = temp; 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 cc51983b..40aef8fb 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 @@ -45,7 +45,7 @@ public class Form extends NamedCode { @Override public void code(final Cache cache, final HTMLGen hgen) throws APIException, IOException { - if(preamble!=null) { + if (preamble!=null) { hgen.incr("p","class=preamble").text(preamble).end(); } hgen.incr("form","method=post"); 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 37576008..435197c8 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 @@ -51,7 +51,7 @@ public abstract class NamedCode implements ContentCode { public void addAttr(boolean first, String attr) { String[] temp = new String[idattrs.length+1]; - if(first) { + if (first) { temp[0] = attr; System.arraycopy(idattrs, 0, temp, 1, idattrs.length); } else { 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 6010dd8b..deed77c0 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 @@ -48,16 +48,16 @@ public class OrgLookupFilter implements Filter { @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) { + if (req instanceof HttpServletRequest) { Principal p = ((HttpServletRequest)req).getUserPrincipal(); - if(p instanceof TaggedPrincipal) { + 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()) { + if (id!=null && id.isFound()) { return id.firstName(); } } catch (OrganizationException e) { 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 a44a4846..1e067c44 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 @@ -102,7 +102,7 @@ public class Page extends HTMLCacheGen { super(CacheGen.PRETTY, new PageCode(env, 1, content)); fields = new String[en.length]; int i=-1; - for(Enum p : en) { + for (Enum p : en) { fields[++i]=p.name(); } @@ -110,8 +110,8 @@ public class Page extends HTMLCacheGen { bcUrl = url; // Mark which fields must be "no_cache" boolean no_cacheTemp=false; - for(NamedCode nc : content) { - if(nc.no_cache()) { + for (NamedCode nc : content) { + if (nc.no_cache()) { no_cacheTemp=true; break; } @@ -124,7 +124,7 @@ public class Page extends HTMLCacheGen { 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) { + if (fields==null) { this.fields = new String[0]; } else { this.fields = fields; @@ -133,8 +133,8 @@ public class Page extends HTMLCacheGen { bcUrl = url; // Mark which fields must be "no_cache" boolean no_cacheTemp=false; - for(NamedCode nc : content) { - if(nc.no_cache()) { + for (NamedCode nc : content) { + if (nc.no_cache()) { no_cacheTemp=true; break; } @@ -220,7 +220,7 @@ public class Page extends HTMLCacheGen { // Obtain User Info, and print TaggedPrincipal p = trans.getUserPrincipal(); String user,secured; - if(p==null) { + if (p==null) { user = "please choose a Login Authority"; secured = "NOT Secure!"; } else { @@ -251,7 +251,7 @@ public class Page extends HTMLCacheGen { int cIdx; ContentCode nc; // If BreadCrumbs, put here - if(content.length>0 && content[0] instanceof BreadCrumbs) { + if (content.length>0 && content[0] instanceof BreadCrumbs) { nc = content[0]; Mark ctnt = hgen.divID(nc.idattrs()); nc.code(cache, hgen); @@ -265,7 +265,7 @@ public class Page extends HTMLCacheGen { Mark inner = hgen.divID("inner"); // Content - for(int i=cIdx;i=0) { msie+=5; @@ -379,14 +379,14 @@ public class Page extends HTMLCacheGen { protected static synchronized Permission getPerm(String instance, String action) { Map msp = perms.get(instance); Permission p; - if(msp==null) { + if (msp==null) { msp = new HashMap<>(); perms.put(instance, msp); p=null; } else { p = msp.get(instance); } - if(p==null) { + if (p==null) { p=new AAFPermission(PERM_NS, PERM_CA_TYPE,instance,action); msp.put(action, p); } 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 844270ed..7462de80 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 @@ -31,7 +31,7 @@ public abstract class SlotCode extends NamedCode { 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 extends NamedCode { } public T get(TRANS trans,int idx, T dflt) { - if(idx>slots.length) { + 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 079593c9..6451c4e7 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 @@ -57,15 +57,15 @@ public class Table, TRANS extends TransStore> extends Named public Table(String title, TRANS trans, Data data, String name, String ... attrs) { super(true,name); // prefix=postfix=null; - for(String a : attrs) { + 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)) { + for (String s : attrs) { + if ("class=std".equals(s) || "class=stdform".equals(s)) { alt=true; } } @@ -89,7 +89,7 @@ public class Table, TRANS extends TransStore> extends Named Mark tr = new Mark(); hgen.incr(table,TABLE); - if(title==null) { + 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 { @@ -100,7 +100,7 @@ public class Table, TRANS extends TransStore> extends Named hgen.leaf("caption", "class=title").text(title).end(); } hgen.incr(tr,TR); - for(String column : columns) { + for (String column : columns) { hgen.leaf("th").text(column).end(); } hgen.end(tr); @@ -110,7 +110,7 @@ public class Table, TRANS extends TransStore> extends Named // End Table hgen.end(table); - if(other!=null) { + if (other!=null) { other.code(cache,hgen); } @@ -119,10 +119,10 @@ public class Table, TRANS extends TransStore> extends Named @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) { + 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) { + } else if ((msg=trans.get(ROW_MSG_SLOT,null))!=null) { hgen.p(msg).br(); } } @@ -181,9 +181,9 @@ public class Table, TRANS extends TransStore> extends Named int alt = this.alt; Cells cells = data.get(trans,state); - if(cells.cells.length>0) { - for(AbsCell[] row : cells.cells) { - if(row.length==0) { + if (cells.cells.length>0) { + for (AbsCell[] row : cells.cells) { + if (row.length==0) { hgen.text("") .hr() .text(""); @@ -198,7 +198,7 @@ public class Table, TRANS extends TransStore> extends Named alt=1; hgen.incr(tr,TR,"class=alt"); } - for(AbsCell cell :row) { + for (AbsCell cell :row) { hgen.leaf(td, TD,cell.attrs()); cell.write(hgen); hgen.end(td); @@ -207,7 +207,7 @@ public class Table, TRANS extends TransStore> extends Named } } // Pass Msg back to Table code, in order to place after Table Complete - if(cells.msg!=null) { + if (cells.msg!=null) { trans.put(ROW_MSG_SLOT,cells.msg); } } else { 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 f362418e..cf3a6715 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 @@ -52,7 +52,7 @@ public class XFrameFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain fc) throws IOException, ServletException { - if(resp instanceof HttpServletResponse) { + if (resp instanceof HttpServletResponse) { @SuppressWarnings("unused") HttpServletResponse hresp = (HttpServletResponse)resp; ((HttpServletResponse)resp).addHeader("X-Frame-Options", xframe); 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 235683d5..7d57b3d8 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 @@ -176,11 +176,11 @@ public class ApiDocs extends Page { @Override public Void code(Rcli client) throws CadiException, ConnectException, APIException { Future fa = client.read("/api",gui.getDF(Api.class)); - if(fa.get(5000)) { + 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()) { + if (fa.value!=null)for (Route r : fa.value.getRoute()) { String path = r.getPath(); // Build info StringBuilder desc = new StringBuilder(); @@ -188,39 +188,39 @@ public class ApiDocs extends Page { desc.append("

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

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


Parameters

"); - for(String params : r.getParam()) { + 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])) { + if ("true".equalsIgnoreCase(param[2])) { desc.append(" (Required)"); } } } - if(r.getExpected()!=0) { + if (r.getExpected()!=0) { desc.append("

Expected HTTP Code

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

Explicit HTTP Error Codes

"); boolean first = true; - for(int ee : r.getExplicitErr()) { - if(first) { + for (int ee : r.getExplicitErr()) { + if (first) { first = false; } else { desc.append(", "); @@ -232,11 +232,11 @@ public class ApiDocs extends Page { desc.append("

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

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

rv, ArrayList ... all) { AbsCell lead; AbsCell[] row; - for(ArrayList al : all) { - if(al.size()>1) { + for (ArrayList al : all) { + if (al.size()>1) { row = al.get(0); lead = row[0]; row[0]=BLANK; @@ -312,7 +312,7 @@ public class ApiDocs extends Page { public int compare(AbsCell[] ca1, AbsCell[] ca2) { int meth = ((TextCell)ca1[2]).name.compareTo( ((TextCell)ca2[2]).name); - if(meth == 0) { + if (meth == 0) { return (HttpMethods.valueOf(((TextCell)ca1[1]).name).compareTo( HttpMethods.valueOf(((TextCell)ca2[1]).name))); } else { 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 3beed563..7da77607 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 @@ -79,7 +79,7 @@ public class ApiExample extends Page { "application/Void+json" ); Future fs2; - if(typecode.contains("Request+")) { + if (typecode.contains("Request+")) { fs2 = gui.client().read("/api/example/" + encoded+"?optional=true", "application/Void+json" ); @@ -88,19 +88,19 @@ public class ApiExample extends Page { } - if(fp.get(5000)) { + 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")) { + if (typecode.contains("+xml")) { xgen.xml(fp.body()); - if(fs2!=null && fs2.get(5000)) { + 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)) { + if (fs2!=null && fs2.get(5000)) { xgen.text(WITH_OPTIONAL_PARAMETERS); xgen.text(fs2.body()); } 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 507cb21a..8c90b491 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 @@ -63,16 +63,16 @@ public class ApprovalAction extends Page { lastPage += "?user="+user; } - if(appr==null) { + 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) { + for (String a : appr) { + if (a!=null) { int idx = a.indexOf('|'); - if(idx>=0) { + if (idx>=0) { app = new Approval(); app.setStatus(a.substring(0,idx)); app.setTicket(a.substring(++idx)); @@ -82,7 +82,7 @@ public class ApprovalAction extends Page { } } } - if(apps.getApprovals().isEmpty()) { + if (apps.getApprovals().isEmpty()) { hgen.p("No Approvals have been sent."); } else { TimeTaken tt = trans.start("AAF Update Approvals",Env.REMOTE); @@ -93,7 +93,7 @@ public class ApprovalAction extends Page { 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)) { + if (fa.get(AAF_GUI.TIMEOUT)) { // Do Remote Call fail2 = false; hgen.p(total + (total==1?" Approval has":" Approvals have") + " been Saved"); 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 14d434cb..27fd5274 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 @@ -146,9 +146,9 @@ public class ApprovalForm extends Page { 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.get(AAF_GUI.TIMEOUT)) { - if(fa.value!=null) { + if (fa.value!=null) { for (Approval appr : fa.value.getApprovals()) { if ("pending".equals(appr.getStatus())) { if (userParam!=null && !appr.getUser().equalsIgnoreCase(userParam)) { @@ -227,23 +227,23 @@ public class ApprovalForm extends Page { boolean userOK=true; for (Approval appr : currApproverList) { - if(++line0) { + if (numLeft>0) { msg = "After these, there will be " + numLeft + " approvals left to process"; } - if(rv.isEmpty()) { + if (rv.isEmpty()) { if (numLeft>0) { msg = "No Approvals to process at this time for user " + userParam +". You have " + numLeft + " other approvals to process."; 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 8088a700..d32c7dc3 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 @@ -77,34 +77,34 @@ trans.info().log("Step 1"); 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)) { + 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"))) { + if (!trans.fish(getPerm(ca,"ip"))) { boolean ok=true; - if(IPValidator.ip(machine)) { + if (IPValidator.ip(machine)) { ok=false; } - if(ok) { - for(String s: arti.getSans()) { - if(IPValidator.ip(s)) { + if (ok) { + for (String s: arti.getSans()) { + if (IPValidator.ip(s)) { ok=false; break; } } } - if(!ok) { + 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"))) { + if (machine.startsWith("*")) { // Domain set + if (!trans.fish(getPerm(ca, "domain"))) { hgen.p("Policy Failure: Domain Artifact Declarations are only allowed by Exception."); return; } @@ -119,8 +119,8 @@ trans.info().log("Step 1"); 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 fc; rv = fc = client.create("/cert/artifacts", gui.artifactsDF, artifacts); - if(fc.get(AAFcli.timeout())) { + 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())) { + if ((rv=fu).get(AAFcli.timeout())) { hgen.p("Artifact " + arti.getMechid() + " on " + arti.getMachine() + " is updated"); ok.set(true); } @@ -159,12 +159,12 @@ trans.info().log("Step 1"); 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, ""))) { + 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())) { + if (fup.get(AAFcli.timeout())) { hgen.p("Copied to " + newMachine); ok.set(true); } @@ -175,7 +175,7 @@ trans.info().log("Step 1"); case CMArtiChangeForm.DELETE: Future fv; rv = fv = client.delete("/cert/artifacts/"+arti.getMechid()+"/"+arti.getMachine(),"application/json"); - if(fv.get(AAFcli.timeout())) { + if (fv.get(AAFcli.timeout())) { hgen.p("Deleted " + arti.getMechid() + " on " + arti.getMachine()); ok.set(true); deleted.set(true); @@ -185,11 +185,11 @@ trans.info().log("Step 1"); return rv; } }); - if(!ok.get()) { - if(f==null) { + if (!ok.get()) { + if (f==null) { hgen.p("Unknown Command"); } else { - if(f.body().contains("%")) { + 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 { 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 0268f498..ee55fdbc 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 @@ -138,25 +138,25 @@ public class CMArtiChangeForm extends Page { @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()) { + if (fa.get(AAFcli.timeout())) { + for (Artifact arti : fa.value.getArtifact()) { return arti; // just need the first one } } return null; } }); - if(arti==null) { + if (arti==null) { Organization org = OrganizationFactory.get(trans); Identity user = org.getIdentity(trans, incomingID); - if(user==null) { + 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) { + if (managedBy == null) { arti.setSponsor("Unknown Sponsor"); } else { arti.setSponsor(managedBy.fullID()); @@ -173,7 +173,7 @@ public class CMArtiChangeForm extends Page { submitText = CREATE; delete = false; } else { - if(arti.getNotification()==null) { + if (arti.getNotification()==null) { Organization org = OrganizationFactory.get(trans); Identity user = org.getIdentity(trans, incomingID); arti.setNotification("mailto:"+user.email()); @@ -184,15 +184,15 @@ public class CMArtiChangeForm extends Page { .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) { +// 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"))) { + if (!trans.fish(getPerm(arti.getCa(),"ip"))) { hgen.text("NO "); } StringBuilder sb = null; - for(String s: arti.getSans()) { - if(sb==null) { + for (String s: arti.getSans()) { + if (sb==null) { sb = new StringBuilder(); } else { sb.append(", "); @@ -212,7 +212,7 @@ public class CMArtiChangeForm extends Page { .incr(HTMLGen.TR) .incr(HTMLGen.TD).leaf("label","for=types","required").text("Artifact Types").end(2) .incr(HTMLGen.TD); - for(int i=0;i action : actions) { + for (Action action : actions) { perm.setAction(action.getName()); - if(user.contains(perm)) { - if(action.exec(obj))return; + if (user.contains(perm)) { + if (action.exec(obj))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 83204d1b..a2642221 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 @@ -112,10 +112,10 @@ public class Agent { public static void main(String[] args) { int exitCode = 0; doExit = true; - if(args.length>0 && "cadi".equals(args[0])) { + 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) { + 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 []"); @@ -127,7 +127,7 @@ public class Agent { AAFSSO aafsso=null; PropAccess access; - if(args.length>1 && args[0].equals("validate") ) { + if (args.length>1 && args[0].equals("validate") ) { int idx = args[1].indexOf('='); aafsso = null; access = new PropAccess( @@ -138,7 +138,7 @@ public class Agent { aafsso= new AAFSSO(args, new AAFSSO.ProcessArgs() { @Override public Properties process(String[] args, Properties props) { - if(args.length>1) { + if (args.length>1) { if (!args[0].equals("keypairgen")) { props.put("aaf_id", args[1]); } @@ -149,23 +149,23 @@ public class Agent { access = aafsso.access(); } - if(aafsso!=null && aafsso.loginOnly()) { + 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)) { + for (String p : args) { + if ("-noexit".equalsIgnoreCase(p)) { doExit = false; - } else if(p.indexOf('=') < 0) { + } else if (p.indexOf('=') < 0) { cmds.add(p); } } - if(cmds.size()==0) { - if(aafsso!=null) { + 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 @@ -209,18 +209,18 @@ public class Agent { Trans trans = env.newTrans(); String token; - if((token=access.getProperty("oauth_token"))!=null) { + if ((token=access.getProperty("oauth_token"))!=null) { trans.setProperty("oauth_token", token); } try { - if(aafsso!=null) { + 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) { + if (cm_url!=null) { aafsso.addProp(Config.CM_URL, cm_url); } aafsso.writeFiles(); @@ -255,7 +255,7 @@ public class Agent { keypairGen(trans, access, cmds); break; case "config": - if(access.getProperty(Config.CADI_PROP_FILES)!=null) { + if (access.getProperty(Config.CADI_PROP_FILES)!=null) { // Get Properties from initialization Prop Files config(trans,access,null,cmds); } else { @@ -280,11 +280,11 @@ public class Agent { } finally { StringBuilder sb = new StringBuilder(); trans.auditTrail(4, sb, Trans.REMOTE); - if(sb.length()>0) { + if (sb.length()>0) { trans.info().log("Trans Info\n",sb); } } - if(aafsso!=null) { + if (aafsso!=null) { aafsso.close(); } } @@ -292,13 +292,13 @@ public class Agent { e.printStackTrace(); } } - if(exitCode != 0 && doExit) { + if (exitCode != 0 && doExit) { System.exit(exitCode); } } private static synchronized AAFCon aafcon(PropAccess access) throws APIException, CadiException, LocatorException { - if(aafcon==null) { + if (aafcon==null) { aafcon = new AAFConHttp(access,Config.CM_URL); } return aafcon; @@ -306,17 +306,17 @@ public class Agent { 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) { + 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) { + if (value!=null) { + if (value.length()>0) { pa.setProperty(tag,value); env.setProperty(tag,value); - } else if(def.length==1) { + } else if (def.length==1) { value=def[0].toString(); pa.setProperty(tag,value); env.setProperty(tag,value); @@ -327,7 +327,7 @@ public class Agent { } private static String fqi(Deque cmds) { - if(cmds.size()<1) { + if (cmds.size()<1) { String alias = env.getProperty(Config.CADI_ALIAS); return alias!=null?alias:AAFSSO.cons.readLine("AppID: "); } @@ -335,7 +335,7 @@ public class Agent { } private static String machine(Deque cmds) throws UnknownHostException { - if(cmds.size()>0) { + if (cmds.size()>0) { return cmds.removeFirst(); } else { String mach = env.getProperty(Config.HOSTNAME); @@ -345,7 +345,7 @@ public class Agent { private static String[] machines(Deque cmds) { String machines; - if(cmds.size()>0) { + if (cmds.size()>0) { machines = cmds.removeFirst(); } else { machines = AAFSSO.cons.readLine("Machines (sep by ','): "); @@ -365,11 +365,11 @@ public class Agent { 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)) { + for (String s : Split.splitTrim(',', resp)) { arti.getType().add(s); } // Always do Script - if(!resp.contains(SCRIPT)) { + if (!resp.contains(SCRIPT)) { arti.getType().add(SCRIPT); } @@ -384,7 +384,7 @@ public class Agent { TimeTaken tt = trans.start("Create Artifact", Env.REMOTE); try { Future future = aafcon.client(CM_VER).create("/cert/artifacts", artifactsDF, artifacts); - if(future.get(TIMEOUT)) { + 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", @@ -396,10 +396,10 @@ public class Agent { } private static String toNotification(String notification) { - if(notification==null) { + if (notification==null) { notification=""; - } else if(notification.length()>0) { - if(notification.indexOf(':')<0) { + } else if (notification.length()>0) { + if (notification.indexOf(':')<0) { notification = "mailto:" + notification; } } @@ -416,17 +416,17 @@ public class Agent { Future future = aafcon.client(CM_VER) .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF,"Authorization","Bearer " + trans.getProperty("oauth_token")); - if(future.get(TIMEOUT)) { + if (future.get(TIMEOUT)) { boolean printed = false; - for(Artifact a : future.value.getArtifact()) { + 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;} + for (String t : a.getType()) { + if (first) {first=false;} else{sb.append(',');} sb.append(t); } @@ -438,7 +438,7 @@ public class Agent { AAFSSO.cons.printf("Notification %s\n",a.getNotification()); printed = true; } - if(!printed) { + if (!printed) { AAFSSO.cons.printf("Artifact for %s %s does not exist\n", mechID, machine); } } else { @@ -453,7 +453,7 @@ public class Agent { String mechID = fqi(cmds); String machine = machine(cmds); String[] newmachs = machines(cmds); - if(machine==null || newmachs == null) { + if (machine==null || newmachs == null) { trans.error().log("No machines listed to copy to"); } else { TimeTaken tt = trans.start("Copy Artifact", Env.REMOTE); @@ -461,13 +461,13 @@ public class Agent { Future future = aafcon.client(CM_VER) .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF); - if(future.get(TIMEOUT)) { + if (future.get(TIMEOUT)) { boolean printed = false; - for(Artifact a : future.value.getArtifact()) { - for(String m : newmachs) { + 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)) { + 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", @@ -477,7 +477,7 @@ public class Agent { printed = true; } } - if(!printed) { + if (!printed) { AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine); } } else { @@ -498,9 +498,9 @@ public class Agent { Future fread = aafcon.client(CM_VER) .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF); - if(fread.get(TIMEOUT)) { + if (fread.get(TIMEOUT)) { Artifacts artifacts = new Artifacts(); - for(Artifact a : fread.value.getArtifact()) { + for (Artifact a : fread.value.getArtifact()) { Artifact arti = new Artifact(); artifacts.getArtifact().add(arti); @@ -510,18 +510,18 @@ public class Agent { 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;} + 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)) { + for (String s : Split.splitTrim(',', resp)) { arti.getType().add(s); } // Always do Script - if(!resp.contains(SCRIPT)) { + if (!resp.contains(SCRIPT)) { arti.getType().add(SCRIPT); } @@ -533,11 +533,11 @@ public class Agent { arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (%s):", a.getNotification()))); } - if(artifacts.getArtifact().size()==0) { + 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)) { + 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", @@ -562,7 +562,7 @@ public class Agent { Future future = aafcon.client(CM_VER) .delete("/cert/artifacts/"+mechid+"/"+machine,"application/json" ); - if(future.get(TIMEOUT)) { + 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", @@ -581,7 +581,7 @@ public class Agent { String machine = machine(cmds); String[] fqdns = Split.split(':', machine); String key; - if(fqdns.length>1) { + if (fqdns.length>1) { key = fqdns[0]; machine = fqdns[1]; } else { @@ -592,27 +592,27 @@ public class Agent { 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()) { + 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()) { + for (Artifact a : acf.value.getArtifact()) { String osID = System.getProperty("user.name"); - if(a.getOsUser().equals(osID)) { + 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)) { + if (f.get(TIMEOUT)) { CertInfo capi = certDF.newData().in(TYPE.JSON).load(f.body()).asObject(); - for(String type : a.getType()) { + for (String type : a.getType()) { PlaceArtifact pa = placeArtifact.get(type); - if(pa!=null) { - if(rv = pa.place(trans, capi, a,machine)) { + if (pa!=null) { + if (rv = pa.place(trans, capi, a,machine)) { notifyPlaced(a,rv); } } @@ -646,28 +646,28 @@ public class Agent { try { Future acf = aafcon.client(CM_VER) .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF); - if(acf.get(TIMEOUT)) { + if (acf.get(TIMEOUT)) { // Have to wait for JDK 1.7 source... //switch(artifact.getType()) { - if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) { + 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()) { + 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) { + if (!allowed) { Future pf = aafcon.client(CM_VER).read("/cert/may/" + a.getNs()+"|certman|"+a.getCa()+"|showpass","*/*"); - if(pf.get(TIMEOUT)) { + if (pf.get(TIMEOUT)) { allowed = true; } else { trans.error().log(errMsg.toMsg(pf)); } } - if(allowed) { + if (allowed) { File dir = new File(a.getDir()); Properties props = new Properties(); FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".cred.props")); @@ -681,12 +681,12 @@ public class Agent { } File f = new File(dir,a.getNs()+".keyfile"); - if(f.exists()) { + if (f.exists()) { Symm symm = Symm.obtain(f); - for(Iterator> iter = props.entrySet().iterator(); iter.hasNext();) { + for (Iterator> iter = props.entrySet().iterator(); iter.hasNext();) { Entry en = iter.next(); - if(en.getValue().toString().startsWith("enc:")) { + if (en.getValue().toString().startsWith("enc:")) { System.out.printf("%s=%s\n", en.getKey(), symm.depass(en.getValue().toString())); } } @@ -712,9 +712,9 @@ public class Agent { File dir = new File(access.getProperty(Config.CADI_ETCDIR,".")); // default to current Directory File f = new File(dir,ns+".key"); - if(f.exists()) { + if (f.exists()) { String line = AAFSSO.cons.readLine("%s exists. Overwrite? (y/n): ", f.getCanonicalPath()); - if(!"Y".equalsIgnoreCase(line)) { + if (!"Y".equalsIgnoreCase(line)) { System.out.println("Canceling..."); return; } @@ -733,9 +733,9 @@ public class Agent { final String fqi = fqi(cmds); final String rootFile = FQI.reverseDomain(fqi); final File dir = new File(pa.getProperty(Config.CADI_ETCDIR, ".")); - if(dir.exists()) { + if (dir.exists()) { System.out.println("Writing to " + dir.getCanonicalFile()); - } else if(dir.mkdirs()) { + } else if (dir.mkdirs()) { System.out.println("Created directory " + dir.getCanonicalFile()); } else { System.err.println("Unable to create or write to " + dir.getCanonicalPath()); @@ -751,14 +751,14 @@ public class Agent { PrintStream psProps; File fLocProps = new File(dir,rootFile + ".location.props"); - if(!fLocProps.exists()) { + 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) { + for (String tag : LOC_TAGS) { psProps.print(tag); psProps.print('='); psProps.println(getProperty(pa, trans, false, tag, "%s: ",tag)); @@ -789,7 +789,7 @@ public class Agent { psProps.println(fLocProps.getCanonicalPath()); File fkf = new File(dir,rootFile+".keyfile"); - if(!fkf.exists()) { + if (!fkf.exists()) { CmdLine.main(new String[] {"keygen",fkf.toString()}); } Symm filesymm = Symm.obtain(fkf); @@ -803,30 +803,30 @@ public class Agent { String cts = pa.getProperty(Config.CADI_TRUSTSTORE); - if(cts!=null) { + if (cts!=null) { File origTruststore = new File(cts); - if(!origTruststore.exists()) { + 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)) { + if (cpf!=null) { + for (String f : Split.split(File.pathSeparatorChar, cpf)) { File fcpf = new File(f); - if(fcpf.exists()) { + if (fcpf.exists()) { int lastSep = cts.lastIndexOf(File.pathSeparator); origTruststore = new File(fcpf.getParentFile(),lastSep>=0?cts.substring(lastSep):cts); - if(origTruststore.exists()) { + if (origTruststore.exists()) { break; } } } - if(!origTruststore.exists()) { + if (!origTruststore.exists()) { throw new CadiException(cts + " does not exist"); } } } File newTruststore = new File(dir,origTruststore.getName()); - if(!newTruststore.exists()) { + if (!newTruststore.exists()) { Files.copy(origTruststore.toPath(), newTruststore.toPath()); } @@ -834,31 +834,31 @@ public class Agent { directedPut(pa, filesymm, normal,creds, Config.CADI_TRUSTSTORE_PASSWORD,null); } - if(aafcon!=null) { // get Properties from Remote AAF + 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()) { + 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){ + } 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)) { + 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()) { + for (Entry prop : props.entrySet()) { directedPut(pa, filesymm, normal,creds, prop.getKey().toString(),prop.getValue().toString()); } } finally { @@ -868,21 +868,21 @@ public class Agent { } ok = true; } - if(ok) { - for(Entry es : normal.entrySet()) { + if (ok) { + for (Entry es : normal.entrySet()) { psProps.print(es.getKey()); psProps.print('='); psProps.println(es.getValue()); } - for(Entry es : creds.entrySet()) { + 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()) { + if (newFile.exists()) { File backup = new File(dir,rootFile+".props.backup"); newFile.renameTo(backup); System.out.println("Backed up to " + backup.getCanonicalPath()); @@ -891,7 +891,7 @@ public class Agent { System.out.println("Created " + newFile.getCanonicalPath()); fProps = newFile; - if(fSecureProps.exists()) { + if (fSecureProps.exists()) { File backup = new File(dir,fSecureProps.getName()+".backup"); fSecureProps.renameTo(backup); System.out.println("Backed up to " + backup.getCanonicalPath()); @@ -925,17 +925,17 @@ public class Agent { 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 + 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:")) { + 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)) { + if (CRED_TAGS.contains(tag)) { secured.put(tag, val); } else { main.put(tag, val); @@ -950,12 +950,12 @@ public class Agent { @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)) { + 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()) { + for (Perm p : fc.value.getPerm()) { System.out.print('\t'); System.out.print(p.getType()); System.out.print('|'); @@ -995,16 +995,16 @@ public class Agent { Future acf = aafcon.client(CM_VER) .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF); - if(acf.get(TIMEOUT)) { + if (acf.get(TIMEOUT)) { // Have to wait for JDK 1.7 source... //switch(artifact.getType()) { - if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) { + 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())) { + 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")); @@ -1017,14 +1017,14 @@ public class Agent { String prop; File f; - if((prop=trans.getProperty(Config.CADI_KEYFILE))==null || + 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) { + 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 { @@ -1040,7 +1040,7 @@ public class Agent { X509Certificate cert = (X509Certificate)ks.getCertificate(mechID); String msg = null; - if(cert==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); @@ -1049,7 +1049,7 @@ public class Agent { GregorianCalendar renew = new GregorianCalendar(); renew.setTime(cert.getNotAfter()); renew.add(GregorianCalendar.DAY_OF_MONTH,-1*a.getRenewDays()); - if(renew.after(now)) { + 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); @@ -1059,7 +1059,7 @@ public class Agent { a.getMechid(), a.getMachine(),cert.getNotAfter()); cmds.offerLast(mechID); cmds.offerLast(machine); - if(placeCerts(trans,aafcon,cmds)) { + 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 @@ -1070,7 +1070,7 @@ public class Agent { } } } - if(msg!=null) { + if (msg!=null) { FileOutputStream fos = new FileOutputStream(a.getDir()+'/'+a.getNs()+".msg"); try { fos.write(msg.getBytes()); 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 b5353828..7e91afae 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 @@ -65,10 +65,10 @@ public abstract class ArtifactDir implements PlaceArtifact { try { // Obtain/setup directory as required dir = new File(arti.getDir()); - if(processed.get("dir")==null) { - if(!dir.exists()) { + if (processed.get("dir")==null) { + if (!dir.exists()) { Chmod.to755.chmod(dir); - if(!dir.mkdirs()) { + if (!dir.mkdirs()) { throw new CadiException("Could not create " + dir); } } @@ -80,8 +80,8 @@ public abstract class ArtifactDir implements PlaceArtifact { // Obtain Issuers boolean first = true; StringBuilder issuers = new StringBuilder(); - for(String dn : certInfo.getCaIssuerDNs()) { - if(first) { + for (String dn : certInfo.getCaIssuerDNs()) { + if (first) { first=false; } else { issuers.append(':'); @@ -91,10 +91,10 @@ public abstract class ArtifactDir implements PlaceArtifact { addProperty(Config.CADI_X509_ISSUERS,issuers.toString()); } symm = (Symm)processed.get("symm"); - if(symm==null) { + if (symm==null) { // CADI Key Gen File f = new File(dir,arti.getNs() + ".keyfile"); - if(!f.exists()) { + if (!f.exists()) { write(f,Chmod.to400,Symm.keygen()); } symm = Symm.obtain(f); @@ -148,7 +148,7 @@ public abstract class ArtifactDir implements PlaceArtifact { FileOutputStream fos = new FileOutputStream(f); PrintStream ps = new PrintStream(fos); try { - for(String s : data) { + for (String s : data) { ps.print(s); } } finally { @@ -186,31 +186,31 @@ public abstract class ArtifactDir implements PlaceArtifact { private void validate(Artifact a) throws CadiException { StringBuilder sb = new StringBuilder(); - if(a.getDir()==null) { + if (a.getDir()==null) { sb.append("File Artifacts require a path"); } - if(a.getNs()==null) { - if(sb.length()>0) { + if (a.getNs()==null) { + if (sb.length()>0) { sb.append('\n'); } sb.append("File Artifacts require an AAF Namespace"); } - if(sb.length()>0) { + if (sb.length()>0) { throw new CadiException(sb.toString()); } } private boolean placeProperties(Artifact arti) throws CadiException { - if(encodeds.size()==0) { + 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) { + if (f.exists()) { + if (first) { File backup = File.createTempFile(f.getName()+'.', ".backup",dir); f.renameTo(backup); } else { @@ -222,8 +222,8 @@ public abstract class ArtifactDir implements PlaceArtifact { PrintWriter pw = new PrintWriter(new FileWriter(f,!first)); try { // Write a Header - if(first) { - for(int i=0;i<60;++i) { + if (first) { + for (int i=0;i<60;++i) { pw.print('#'); } pw.println(); @@ -233,12 +233,12 @@ public abstract class ArtifactDir implements PlaceArtifact { pw.print("# on "); pw.println(Chrono.dateStamp()); pw.println("# @copyright 2016, AT&T"); - for(int i=0;i<60;++i) { + for (int i=0;i<60;++i) { pw.print('#'); } pw.println(); - for(String prop : encodeds) { - if( prop.startsWith("cm_") + for (String prop : encodeds) { + if ( prop.startsWith("cm_") || prop.startsWith(Config.HOSTNAME) || prop.startsWith(Config.AAF_ENV)) { pw.println(prop); @@ -246,8 +246,8 @@ public abstract class ArtifactDir implements PlaceArtifact { } } - for(String prop : encodeds) { - if(prop.startsWith("cadi")) { + for (String prop : encodeds) { + if (prop.startsWith("cadi")) { pw.println(prop); } } @@ -256,16 +256,16 @@ public abstract class ArtifactDir implements PlaceArtifact { } Chmod.to644.chmod(f); - if(first) { + if (first) { // Challenge f = new File(dir,arti.getNs()+".chal"); - if(f.exists()) { + if (f.exists()) { f.delete(); } pw = new PrintWriter(new FileWriter(f)); try { - for(String prop : encodeds) { - if(prop.startsWith("Challenge")) { + for (String prop : encodeds) { + if (prop.startsWith("Challenge")) { pw.println(prop); } } @@ -274,7 +274,7 @@ public abstract class ArtifactDir implements PlaceArtifact { } Chmod.to400.chmod(f); } - } catch(Exception e) { + } catch (Exception e) { throw new CadiException(e); } return true; 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 40f31706..642b2d29 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 @@ -119,7 +119,7 @@ public class Factory { public static KeyPair generateKeyPair(Trans trans) { TimeTaken tt; - if(trans!=null) { + if (trans!=null) { tt = trans.start("Generate KeyPair", Env.SUB); } else { tt = null; @@ -127,7 +127,7 @@ public class Factory { try { return keygen.generateKeyPair(); } finally { - if(tt!=null) { + if (tt!=null) { tt.done(); } } @@ -146,7 +146,7 @@ public class Factory { base64.encode(bais, baos); sb.append(new String(baos.toByteArray())); - if(sb.charAt(sb.length()-1)!='\n') { + if (sb.charAt(sb.length()-1)!='\n') { sb.append('\n'); } sb.append("-----END "); @@ -215,7 +215,7 @@ public class Factory { public static Collection toX509Certificate(List x509s) throws CertificateException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { - for(String x509 : x509s) { + for (String x509 : x509s) { baos.write(x509.getBytes()); } } catch (IOException e) { @@ -246,16 +246,16 @@ public class Factory { } public static String toString(Trans trans, Certificate cert) throws IOException, CertException { - if(trans.debug().isLoggable()) { + if (trans.debug().isLoggable()) { StringBuilder sb = new StringBuilder("Certificate to String"); - if(cert instanceof X509Certificate) { + if (cert instanceof X509Certificate) { sb.append(" - "); sb.append(((X509Certificate)cert).getSubjectDN()); } trans.debug().log(sb); } try { - if(cert==null) { + if (cert==null) { throw new CertException("Certificate not built"); } return textBuilder("CERTIFICATE",cert.getEncoded()); @@ -283,18 +283,18 @@ public class Factory { ByteArrayOutputStream baos = new ByteArrayOutputStream(); String line; boolean notStarted = true; - while((line=br.readLine())!=null) { - if(notStarted) { - if(line.startsWith("-----")) { + while ((line=br.readLine())!=null) { + if (notStarted) { + if (line.startsWith("-----")) { notStarted = false; - if(hs!=null) { + if (hs!=null) { hs.set(line); } } else { continue; } } - if(line.length()>0 && + if (line.length()>0 && !line.startsWith("-----") && line.indexOf(':')<0) { // Header elements baos.write(line.getBytes()); @@ -310,7 +310,7 @@ public class Factory { private String line; public StripperInputStream(Reader rdr) { - if(rdr instanceof BufferedReader) { + if (rdr instanceof BufferedReader) { br = (BufferedReader)rdr; } else { br = new BufferedReader(rdr); @@ -330,16 +330,16 @@ public class Factory { @Override public int read() throws IOException { - if(line==null || idx>=line.length()) { - while((line=br.readLine())!=null) { - if(line.length()>0 && + 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) { + if (line==null) { return -1; } idx = 0; @@ -352,7 +352,7 @@ public class Factory { */ @Override public void close() throws IOException { - if(created!=null) { + if (created!=null) { created.close(); } } @@ -379,13 +379,13 @@ public class Factory { @Override public int read() throws IOException { - if(duo==null || idx>=duo.length) { + if (duo==null || idx>=duo.length) { int read = is.read(trio); - if(read==-1) { + if (read==-1) { return -1; } duo = Symm.base64.decode(trio); - if(duo==null || duo.length==0) { + if (duo==null || duo.length==0) { return -1; } idx=0; @@ -399,7 +399,7 @@ public class Factory { */ @Override public void close() throws IOException { - if(created!=null) { + if (created!=null) { created.close(); } } @@ -477,7 +477,7 @@ public class Factory { */ public static synchronized Provider getSecurityProvider(String providerType, String[][] params) throws CertException { Provider p = Security.getProvider(providerType); - if(p!=null) { + if (p!=null) { switch(providerType) { case "PKCS12": 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 e85b903f..b91e8734 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 @@ -53,7 +53,7 @@ public class PlaceArtifactInKeystore extends ArtifactDir { File fks = new File(dir,arti.getNs()+'.'+(kst==Agent.PKCS12?"p12":kst)); try { KeyStore jks = KeyStore.getInstance(kst); - if(fks.exists()) { + if (fks.exists()) { File backup = File.createTempFile(fks.getName()+'.', ".backup",dir); fks.renameTo(backup); } @@ -65,10 +65,10 @@ public class PlaceArtifactInKeystore extends ArtifactDir { X509Certificate x509; List chainList = new ArrayList<>(); Set caSet = new HashSet<>(); - for(Certificate c : certColl) { + for (Certificate c : certColl) { x509 = (X509Certificate)c; // Is a Root (self-signed, anyway) - if(x509.getSubjectDN().equals(x509.getIssuerDN())) { + if (x509.getSubjectDN().equals(x509.getIssuerDN())) { caSet.add(x509); } else { chainList.add(x509); @@ -98,7 +98,7 @@ public class PlaceArtifactInKeystore extends ArtifactDir { addEncProperty(Config.CADI_KEY_PASSWORD, keyPass); addProperty(Config.CADI_ALIAS, arti.getMechid()); // Set attribs = new HashSet<>(); -// if(kst.equals("pkcs12")) { +// if (kst.equals("pkcs12")) { // // Friendly Name // attribs.add(new PKCS12Attribute("1.2.840.113549.1.9.20", arti.getNs())); // } @@ -119,7 +119,7 @@ public class PlaceArtifactInKeystore extends ArtifactDir { // 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()) { + if (fks.exists()) { File backup = File.createTempFile(fks.getName()+'.', ".backup",dir); fks.renameTo(backup); } @@ -136,7 +136,7 @@ public class PlaceArtifactInKeystore extends ArtifactDir { // Add Trusted Certificates, but PKCS12 doesn't support Certificate[] trustCAs = new Certificate[caSet.size()]; caSet.toArray(trustCAs); - for(int i=0; i0) { + 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()) { + 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 2393c4c8..5ee1abe2 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 @@ -40,7 +40,7 @@ public class PlaceArtifactScripts extends ArtifactDir { String filename = arti.getNs()+".check.sh"; File f1 = new File(dir,filename); String email = arti.getNotification() + '\n'; - if(email.startsWith("mailto:")) { + if (email.startsWith("mailto:")) { email=email.substring(7); } else { email=arti.getOsUser() + '\n'; @@ -48,8 +48,8 @@ public class PlaceArtifactScripts extends ArtifactDir { StringBuilder classpath = new StringBuilder(); boolean first = true; - for(String pth : Split.split(File.pathSeparatorChar, System.getProperty("java.class.path"))) { - if(first) { + for (String pth : Split.split(File.pathSeparatorChar, System.getProperty("java.class.path"))) { + if (first) { first=false; } else { classpath.append(File.pathSeparatorChar); 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 38890681..f3ff3898 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 @@ -35,10 +35,10 @@ public class AAFToken { 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 @@ -54,11 +54,11 @@ public class AAFToken { public static final UUID fromToken(String token) { byte[] bytes = Hash.fromHexNo0x(token); - if(bytes==null) { + if (bytes==null) { return null; } ByteBuffer bb = ByteBuffer.wrap(bytes); - if(bb.capacity()!=CAPACITY ) { + if (bb.capacity()!=CAPACITY ) { return null; // not a CADI Token } byte b1 = bb.get(); @@ -68,14 +68,14 @@ public class AAFToken { 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) || + if (b1!=((byte)sum) || b2!=((byte)(sum>>8)) || b3!=((byte)((sum>>16)))) { return null; // not a CADI Token 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 26a8a69d..29d0933c 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 @@ -45,15 +45,15 @@ public abstract class AbsOTafLur { 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) { + 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) { + if (tokenClientPool==null) { tokenClientPool = new Pool(new TCCreator(access)); } try { @@ -76,7 +76,7 @@ public abstract class AbsOTafLur { throw new CadiException(e1); } - if((url = access.getProperty(Config.AAF_OAUTH2_TOKEN_URL,null))==null) { + if ((url = access.getProperty(Config.AAF_OAUTH2_TOKEN_URL,null))==null) { throw new CadiException(Config.AAF_OAUTH2_TOKEN_URL + REQUIRED_FOR_OAUTH2); } @@ -85,7 +85,7 @@ public abstract class AbsOTafLur { } catch (NumberFormatException e) { throw new CadiException("Bad format for " + Config.AAF_CONN_TIMEOUT, e); } - if((enc_secret= access.getProperty(Config.AAF_APPPASS,null))==null) { + if ((enc_secret= access.getProperty(Config.AAF_APPPASS,null))==null) { throw new CadiException(Config.AAF_APPPASS + REQUIRED_FOR_OAUTH2); } } 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 100b58ec..0e57dee8 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 @@ -54,14 +54,14 @@ public class HRenewingTokenSS extends HAuthorizationHeader { tc.client_creds(access); setUser(tc.client_id()); String defaultNS = FQI.reverseDomain(tc.client_id()); - if(nss.length>0) { + if (nss.length>0) { boolean hasDefault = false; - for(String ns : nss) { - if(ns.equals(defaultNS)) { + for (String ns : nss) { + if (ns.equals(defaultNS)) { hasDefault = true; } } - if(hasDefault) { + if (hasDefault) { scopes=nss; } else { String[] nssPlus = new String[nss.length+1]; @@ -86,7 +86,7 @@ public class HRenewingTokenSS extends HAuthorizationHeader { Result token; try { token = tc.getToken(Kind.OAUTH,scopes); - if(token.isOK()) { + if (token.isOK()) { return "Bearer " + token.value.getAccessToken(); } else { throw new IOException("Token cannot be obtained: " + token.code + '-' + token.error); 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 b4b4b1e3..27e92142 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 @@ -52,14 +52,14 @@ public class OAuth2HttpTaf implements HttpTaf { @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()) { + 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()) { + 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); 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 5f4009d5..1a1adcc5 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 @@ -55,16 +55,16 @@ public class OAuth2Lur implements Lur { public boolean fish(Principal bait, Permission ... pond) { boolean rv = false; - if(bait instanceof OAuth2Principal) { + if (bait instanceof OAuth2Principal) { OAuth2Principal oap = (OAuth2Principal)bait; for (Permission p : pond ) { AAFPermission apond = (AAFPermission)p; TokenPerm tp = oap.tokenPerm(); - if(tp==null) { + if (tp==null) { } else { - for(Permission perm : tp.perms()) { - if(perm.match(apond)) { + for (Permission perm : tp.perms()) { + if (perm.match(apond)) { return true; } } @@ -78,8 +78,8 @@ public class OAuth2Lur implements Lur { public void fishAll(Principal bait, List permissions) { OAuth2Principal oap = (OAuth2Principal)bait; TokenPerm tp = oap.tokenPerm(); - if(tp!=null) { - for(AAFPermission p : tp.perms()) { + if (tp!=null) { + for (AAFPermission p : tp.perms()) { permissions.add(p); } } @@ -96,7 +96,7 @@ public class OAuth2Lur implements Lur { @Override public boolean handles(Principal p) { - if(p!=null && p instanceof BearerPrincipal) { + if (p!=null && p instanceof BearerPrincipal) { return ((BearerPrincipal)p).getBearer()!=null; } return false; 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 3b4e074a..58ecaa84 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 @@ -80,7 +80,7 @@ public class TokenClient { ss = null; authn_method = am; synchronized(tcf) { - if(introspectDF==null) { + if (introspectDF==null) { tokenDF = tkCon.env().newDataFactory(Token.class); introspectDF = tkCon.env().newDataFactory(Introspect.class); } @@ -106,9 +106,9 @@ public class TokenClient { } public void client_creds(Access access) throws CadiException { - if(okind=='A') { + if (okind=='A') { String alias = access.getProperty(Config.CADI_ALIAS, null); - if(alias == null) { + if (alias == null) { client_creds(access.getProperty(Config.AAF_APPID, null),access.getProperty(Config.AAF_APPPASS, null)); } else { client_creds(alias,null); @@ -129,15 +129,15 @@ public class TokenClient { * @throws IOException */ public void client_creds(final String client_id, final String client_secret) throws CadiException { - if(client_id==null) { + 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) { + if (client_secret!=null) { try { - if(client_secret.startsWith("enc:")) { + 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()); @@ -159,7 +159,7 @@ public class TokenClient { }; } authn_method = AUTHN_METHOD.client_credentials; - } catch(IOException | NoSuchAlgorithmException e) { + } catch (IOException | NoSuchAlgorithmException e) { throw new CadiException(e); } } else { @@ -193,9 +193,9 @@ public class TokenClient { */ public void password(final String user, final String password) throws CadiException { this.username = user; - if(password!=null) { + if (password!=null) { try { - if(password.startsWith("enc:")) { + 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()); @@ -226,7 +226,7 @@ public class TokenClient { public void clearEndUser() { username = null; enc_password = null; - if(client_id!=null && enc_client_secret!=null) { + if (client_id!=null && enc_client_secret!=null) { authn_method = AUTHN_METHOD.client_credentials; } else { authn_method = AUTHN_METHOD.password; @@ -244,7 +244,7 @@ public class TokenClient { public void clearToken(final char kind, final String ... scopes) throws CadiException { final String scope = addScope(scopes); char c; - if(kind==Kind.OAUTH) { + if (kind==Kind.OAUTH) { c = okind; } else { c = kind; @@ -261,13 +261,13 @@ public class TokenClient { public Result getToken(final char kind, final String ... scopes) throws LocatorException, CadiException, APIException { final String scope = addScope(scopes); char c; - if(kind==Kind.OAUTH) { + if (kind==Kind.OAUTH) { c = okind; } else { c = kind; } final String key = TokenClientFactory.getKey(c,client_id,username,hash,scope); - if(ss==null) { + if (ss==null) { throw new APIException("client_creds(...) must be set before obtaining Access Tokens"); } @@ -285,7 +285,7 @@ public class TokenClient { 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)) { + if (f.get(timeout)) { return Result.ok(f.code(),f.value); } else { return Result.err(f.code(), f.body()); @@ -293,7 +293,7 @@ public class TokenClient { } }); - if(rt.isOK()) { + if (rt.isOK()) { try { return Result.ok(rt.code,factory.putTimedToken(key,rt.value, hash)); } catch (IOException e) { @@ -306,11 +306,11 @@ public class TokenClient { } } }); - if(rtt.isOK()) { // not validated for Expired + if (rtt.isOK()) { // not validated for Expired TimedToken tt = rtt.value; - if(tt.expired()) { + if (tt.expired()) { rtt = refreshToken(tt); - if(rtt.isOK()) { + 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 { @@ -328,7 +328,7 @@ public class TokenClient { } public Result refreshToken(Token token) throws APIException, LocatorException, CadiException { - if(ss==null) { + if (ss==null) { throw new APIException("client_creds(...) must be set before obtaining Access Tokens"); } final List params = new ArrayList<>(); @@ -344,7 +344,7 @@ public class TokenClient { 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)) { + if (f.get(timeout)) { return Result.ok(f.code(),f.value); } else { return Result.err(f.code(), f.body()); @@ -352,21 +352,21 @@ public class TokenClient { } }); String key = TokenClientFactory.getKey(okind,client_id, username, hash, scope); - if(rt.isOK()) { + 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) { + } 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) { + if (ss==null) { throw new APIException("client_creds(...) must be set before introspecting Access Tokens"); } @@ -380,7 +380,7 @@ public class TokenClient { 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)) { + if (f.get(timeout)) { return Result.ok(f.code(),f.value); } else { return Result.err(f.code(), f.body()); @@ -394,8 +394,8 @@ public class TokenClient { String rv = null; StringBuilder scope=null; boolean first = true; - for(String s : scopes) { - if(first) { + for (String s : scopes) { + if (first) { scope = new StringBuilder(); scope.append("scope="); first=false; @@ -404,7 +404,7 @@ public class TokenClient { } scope.append(s); } - if(scope!=null) { + if (scope!=null) { rv=scope.toString(); } return rv; @@ -432,11 +432,11 @@ public class TokenClient { // Set Credentials appropriate switch(authn_method) { case client_credentials: - if(client_id!=null) { + if (client_id!=null) { params.add("client_id="+client_id); } - if(enc_client_secret!=null) { + 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) { @@ -444,17 +444,17 @@ public class TokenClient { } } - if(username!=null) { + if (username!=null) { params.add("username="+username); } break; case refresh_token: - if(client_id!=null) { + if (client_id!=null) { params.add("client_id="+client_id); } - if(enc_client_secret!=null) { + 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) { @@ -464,22 +464,22 @@ public class TokenClient { break; case password: - if(client_id!=null) { + if (client_id!=null) { params.add("client_id="+client_id); } - if(enc_client_secret!=null) { + 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) { + if (username!=null) { params.add("username="+username); } - if(enc_password!=null) { + if (enc_password!=null) { try { params.add("password="+ URLEncoder.encode(new String(factory.symm.decode(enc_password)),UTF_8)); } catch (IOException e) { 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 8a7118c7..21b65f1a 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 @@ -63,10 +63,10 @@ public class TokenClientFactory extends Persist { 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) { + 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) { + 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); } @@ -75,7 +75,7 @@ public class TokenClientFactory extends Persist { } public synchronized static final TokenClientFactory instance(Access access) throws APIException, GeneralSecurityException, IOException, CadiException { - if(instance==null) { + if (instance==null) { instance = new TokenClientFactory(access); } return instance; @@ -96,16 +96,16 @@ public class TokenClientFactory extends Persist { public TokenClient newClient(final String tagOrURL, final int timeout) throws CadiException, LocatorException, APIException { AAFConHttp ach; - if(tagOrURL==null) { + if (tagOrURL==null) { throw new CadiException("parameter tagOrURL cannot be null."); } else { ach = aafcons.get(tagOrURL); - if(ach==null) { + if (ach==null) { aafcons.put(tagOrURL, ach=new AAFConHttp(access,tagOrURL)); } } char okind; - if( Config.AAF_OAUTH2_TOKEN_URL.equals(tagOrURL) || + 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)) @@ -136,19 +136,19 @@ public class TokenClientFactory extends Persist { try { StringBuilder sb = new StringBuilder(client_id); sb.append('_'); - if(username!=null) { + if (username!=null) { sb.append(username); } sb.append('_'); sb.append(tokenSource); byte[] tohash=scope.getBytes(); - if(hash!=null && hash.length>0) { + 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) { + if (scope!=null && scope.length()>0) { sb.append(Hash.toHexNo0x(Hash.hashSHA256(tohash))); } return sb.toString(); @@ -170,12 +170,12 @@ public class TokenClientFactory extends Persist { private static final Pattern locatePattern = Pattern.compile("https://.*/locate/.*"); public Locator bestLocator(final String locatorURL ) throws LocatorException, URISyntaxException { - if(locatorURL==null) { + if (locatorURL==null) { throw new LocatorException("Cannot have a null locatorURL in bestLocator"); } - if(locatorURL.startsWith("https://AAF_LOCATE_URL/") || locatePattern.matcher(locatorURL).matches()) { + 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 + } else if (locatorURL.indexOf(',')>0) { // multiple URLs is a Property Locator return new PropertyLocator(locatorURL); } else { return new SingleEndpointLocator(locatorURL); 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 147621fc..5a4e7f0c 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 @@ -55,12 +55,12 @@ public class TokenMgr extends Persist { 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) { + if (permsDF==null) { permsDF = env.newDataFactory(Perms.class); introspectDF = env.newDataFactory(Introspect.class); } } - if("dbToken".equals(tokenURL) && "dbIntrospect".equals(introspectURL)) { + if ("dbToken".equals(tokenURL) && "dbIntrospect".equals(introspectURL)) { tpLoader = new TokenPermLoader() { // null Loader @Override public Result load(String accessToken, byte[] cred) @@ -72,7 +72,7 @@ public class TokenMgr extends Persist { 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) { + 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); @@ -83,7 +83,7 @@ public class TokenMgr extends Persist { private TokenMgr(PropAccess access, TokenPermLoader tpl) throws APIException, CadiException { super(access,new RosettaEnv(access.getProperties()),Introspect.class,"incoming"); synchronized(access) { - if(permsDF==null) { + if (permsDF==null) { permsDF = env.newDataFactory(Perms.class); introspectDF = env.newDataFactory(Introspect.class); } @@ -94,7 +94,7 @@ public class TokenMgr extends Persist { 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) { + if (tm==null) { tmmap.put(key, tm=new TokenMgr(access,tokenURL,introspectURL)); } return tm; @@ -111,7 +111,7 @@ public class TokenMgr extends Persist { } } }); - if(tp.isOK()) { + if (tp.isOK()) { return Result.ok(200, new OAuth2Principal(tp.value,hash)); } else { return Result.err(tp); @@ -143,7 +143,7 @@ public class TokenMgr extends Persist { int timeout = Integer.parseInt(access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF)); tokenCL = tcf.newClient(tokenURL, timeout); - if(introspectURL.equals(tokenURL)) { + if (introspectURL.equals(tokenURL)) { introCL = tokenCL; } else { introCL = tcf.newClient(introspectURL, @@ -159,7 +159,7 @@ public class TokenMgr extends Persist { long start = System.currentTimeMillis(); try { Result ri = introCL.introspect(accessToken); - if(ri.isOK()) { + if (ri.isOK()) { return Result.ok(ri.code, new TokenPerm(TokenMgr.this,permsDF,ri.value,cred,getPath(accessToken))); } else { return Result.err(ri); @@ -172,7 +172,7 @@ public class TokenMgr extends Persist { public void clear(Principal p, StringBuilder report) { TokenPerm tp = tpmap.remove(p.getName()); - if(tp==null) { + if (tp==null) { report.append("Nothing to clear"); } else { report.append("Cleared "); 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 daac8f43..6efd9ce3 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 @@ -49,7 +49,7 @@ public class TokenPerm extends Persisting{ 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) { + if (ti.getContent()==null || ti.getContent().length()==0) { perms = NULL_PERMS; } else { LoadPermissions lp; @@ -96,7 +96,7 @@ public class TokenPerm extends Persisting{ InJson ij = new InJson(); Parsed pd = ij.newParsed(); boolean inPerms = false, inPerm = false; - while((pd = ij.parse(r,pd.reuse())).valid()) { + while ((pd = ij.parse(r,pd.reuse())).valid()) { switch(pd.event) { case Parse.START_DOC: perms = new ArrayList<>(); @@ -105,22 +105,22 @@ public class TokenPerm extends Persisting{ inPerms = "perm".equals(pd.name); break; case '{': - if(inPerms) { + if (inPerms) { inPerm=true; pi.clear(); } break; case ',': - if(inPerm) { + if (inPerm) { pi.eval(pd); } break; case '}': - if(inPerms) { - if(inPerm) { + if (inPerms) { + if (inPerm) { pi.eval(pd); AAFPermission perm = pi.create(); - if(perm!=null) { + if (perm!=null) { perms.add(perm); } } @@ -128,7 +128,7 @@ public class TokenPerm extends Persisting{ } break; case Parse.END_ARRAY: - if(inPerms) { + if (inPerms) { inPerms=false; } break; @@ -146,7 +146,7 @@ public class TokenPerm extends Persisting{ ns=type=instance=action=null; } public void eval(Parsed pd) { - if(pd.hasName()) { + if (pd.hasName()) { switch(pd.name) { case "ns": ns=pd.sb.toString(); @@ -164,7 +164,7 @@ public class TokenPerm extends Persisting{ } } public AAFPermission create() { - if(type!=null && instance!=null && action !=null) { + if (type!=null && instance!=null && action !=null) { return new AAFPermission(ns,type, instance, action); } else { return null; 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 77348390..c07332d1 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 @@ -69,10 +69,10 @@ public class TzHClient extends TzClient { } public RET best (Retryable retryable) throws CadiException, LocatorException, APIException { - if(token == null || tokenSS==null) { + if (token == null || tokenSS==null) { throw new CadiException("OAuth2 Token has not been set"); } - if(token.expired()) { + if (token.expired()) { //TODO Refresh? throw new CadiException("Expired Token"); } else { 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 688f30b1..8c2cc82d 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 @@ -87,20 +87,20 @@ public class OBasicHttpTaf extends AbsOTafLur implements HttpTaf { final String user; String password=null; byte[] cred=null; - if(req instanceof BasicCred) { + 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()) { + 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) { + if (colon>0) { user = temp.substring(0,colon); password = temp.substring(colon+1); } else { @@ -108,7 +108,7 @@ public class OBasicHttpTaf extends AbsOTafLur implements HttpTaf { 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)) { + 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); } @@ -122,10 +122,10 @@ public class OBasicHttpTaf extends AbsOTafLur implements HttpTaf { } try { - if(password==null && cred!=null) { + if (password==null && cred!=null) { password = new String(cred); cred = Hash.hashSHA256(cred); - } else if(password!=null && cred==null) { + } else if (password!=null && cred==null) { cred = Hash.hashSHA256(password.getBytes()); } Pooled pclient = tokenClientPool.get(); @@ -133,13 +133,13 @@ public class OBasicHttpTaf extends AbsOTafLur implements HttpTaf { 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()) { + 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()) { + 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); @@ -159,7 +159,7 @@ public class OBasicHttpTaf extends AbsOTafLur implements HttpTaf { protected String buildMsg(Principal pr, HttpServletRequest req, Object ... msg) { StringBuilder sb = new StringBuilder(); - if(pr!=null) { + if (pr!=null) { sb.append("user="); sb.append(pr.getName()); sb.append(','); @@ -168,9 +168,9 @@ public class OBasicHttpTaf extends AbsOTafLur implements HttpTaf { sb.append(req.getRemoteAddr()); sb.append(",port="); sb.append(req.getRemotePort()); - if(msg.length>0) { + if (msg.length>0) { sb.append(",msg=\""); - for(Object s : msg) { + for (Object s : msg) { sb.append(s.toString()); } sb.append('"'); @@ -180,9 +180,9 @@ public class OBasicHttpTaf extends AbsOTafLur implements HttpTaf { @Override public Resp revalidate(CachedPrincipal prin, Object state) { -// if(prin instanceof BasicPrincipal) { +// if (prin instanceof BasicPrincipal) { // BasicPrincipal ba = (BasicPrincipal)prin; -// if(DenialOfServiceTaf.isDeniedID(ba.getName())!=null) { +// if (DenialOfServiceTaf.isDeniedID(ba.getName())!=null) { // return Resp.UNVALIDATED; // } // return rbac.validate(ba.getName(), Type.PASSWORD, ba.getCred(), state)?Resp.REVALIDATED:Resp.UNVALIDATED; 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 c67f986e..b85e311d 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 @@ -56,13 +56,13 @@ public class OLur extends AbsOTafLur implements Lur { @Override public boolean fish(Principal bait, Permission ... pond) { TokenPerm tp; - if(bait instanceof OAuth2Principal) { + if (bait instanceof OAuth2Principal) { OAuth2Principal oa2p = (OAuth2Principal)bait; tp = oa2p.tokenPerm(); } else { tp=null; } - if(tp==null) { + if (tp==null) { // if no Token Perm preset, get try { Pooled tcp = tokenClientPool.get(); @@ -73,7 +73,7 @@ public class OLur extends AbsOTafLur implements Lur { scopeSet.add(tc.defaultScope()); AAFPermission ap; for (Permission p : pond) { - if(p instanceof AAFPermission) { + if (p instanceof AAFPermission) { ap = (AAFPermission)p; scopeSet.add(ap.getNS()); } @@ -82,9 +82,9 @@ public class OLur extends AbsOTafLur implements Lur { scopeSet.toArray(scopes); Result rtt = tc.getToken(Kind.getKind(bait),scopes); - if(rtt.isOK()) { + if (rtt.isOK()) { Result rtp = tkMgr.get(rtt.value.getAccessToken(), bait.getName().getBytes()); - if(rtp.isOK()) { + if (rtp.isOK()) { tp = rtp.value; } } @@ -97,8 +97,8 @@ public class OLur extends AbsOTafLur implements Lur { } boolean rv = false; - if(tp!=null) { - if(tkMgr.access.willLog(Level.DEBUG)) { + 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 "); @@ -117,7 +117,7 @@ public class OLur extends AbsOTafLur implements Lur { access.log(Level.DEBUG, sb); } for (Permission p : pond) { - if(rv) { + if (rv) { break; } for (AAFPermission perm : tp.perms()) { @@ -135,7 +135,7 @@ public class OLur extends AbsOTafLur implements Lur { */ @Override public void fishAll(Principal bait, List permissions) { - if(bait instanceof OAuth2Principal) { + if (bait instanceof OAuth2Principal) { for (AAFPermission p : ((OAuth2Principal)bait).tokenPerm().perms()) { permissions.add(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 d87ee780..472bb529 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 @@ -67,7 +67,7 @@ public abstract class Persist> extends PersistFile { df = env.newDataFactory(cls); tmap = new ConcurrentHashMap<>(); synchronized(Persist.class) { - if(clean==null) { + if (clean==null) { clean = new Timer(true); clean.schedule(new Clean(access), 20000, CLEAN_CHECK); } @@ -85,14 +85,14 @@ public abstract class Persist> extends PersistFile { return df; } public Result get(final String key, final byte[] hash, Loader rl) throws CadiException, APIException, LocatorException { - if(key==null) { + 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()) { + 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"); @@ -100,12 +100,12 @@ public abstract class Persist> extends PersistFile { } // If not currently in memory, check with Disk (which might have been updated by other processes) - if(ct==null) { + if (ct==null) { Holder hl = new Holder(0L); T t; - if((t = readDisk(df, hash, key, hp, hl))!=null) { + if ((t = readDisk(df, hash, key, hp, hl))!=null) { try { - if((ct = newCacheable(t,hl.get(),hash,hp.get()))!=null) { + if ((ct = newCacheable(t,hl.get(),hash,hp.get()))!=null) { tmap.put(key, ct); } access.log(Level.DEBUG,"Read Token from",key); @@ -115,16 +115,16 @@ public abstract class Persist> extends PersistFile { } // 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()) { + if (ct==null || ct.checkReloadable()) { // Load from external (if makes sense) Result rtp = rl.load(key); - if(rtp.isOK()) { + 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) { + } catch (CadiException e) { throw e; } catch (Exception e) { throw new CadiException(e); @@ -134,7 +134,7 @@ public abstract class Persist> extends PersistFile { } } - if(ct!=null) { + if (ct!=null) { tmap.put(key, ct); } } else { @@ -186,23 +186,23 @@ public abstract class Persist> extends PersistFile { final long now = System.currentTimeMillis(); final long dayFromNow = now + ONE_DAY; final Metrics metrics = new Metrics(); - for(final Persist persist : allPersists) { + for (final Persist persist : allPersists) { // Clear memory - if(access.willLog(Level.DEBUG)) { + if (access.willLog(Level.DEBUG)) { access.log(Level.DEBUG, "Persist: Cleaning memory cache for",persist.tokenPath.toAbsolutePath()); } - for(Entry es : persist.tmap.entrySet()) { + for (Entry es : persist.tmap.entrySet()) { ++metrics.mexists; Persistable p = (Persistable)es.getValue(); - if(p.checkSyncTime()) { - if(p.count()==0) { + 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())) { + } else if (Files.exists(p.path())) { } } @@ -220,19 +220,19 @@ public abstract class Persist> extends PersistFile { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - if(attrs.isRegularFile()) { + if (attrs.isRegularFile()) { ++metrics.dexists; try { long exp = persist.readExpiration(file)*1000; // readExpiration is seconds from 1970 - if(now > exp) { // cover for bad token + 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) { + } else if (exp > dayFromNow) { sb.append("\n\tFile "); sb.append(file.toString()); sb.append(" data corrupted."); @@ -273,14 +273,14 @@ public abstract class Persist> extends PersistFile { // 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)) { + if (access.willLog(Level.INFO)) { go = true; level=Level.INFO; - } else if(access.willLog(Level.WARN)) { + } else if (access.willLog(Level.WARN)) { go = metrics.mremoved>0 || metrics.dremoved>0 || --hourly <= 0; } - if(go) { + 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; 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 7aab519d..c7d71488 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 @@ -63,8 +63,8 @@ public class PersistFile { this.access = access; tokenPath = Paths.get(access.getProperty(Config.CADI_TOKEN_DIR,"tokens"), sub_dir); try { - if(!Files.exists(tokenPath)) { - if(isWindows) { + if (!Files.exists(tokenPath)) { + if (isWindows) { // Sorry Windows users, you need to secure your own paths Files.createDirectories(tokenPath); } else { @@ -77,7 +77,7 @@ public class PersistFile { throw new CadiException(e); } synchronized(LOCK) { - if(symm==null) { + if (symm==null) { symm = Symm.obtain(access); } } @@ -94,7 +94,7 @@ public class PersistFile { 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)); } @@ -104,10 +104,10 @@ public class PersistFile { CipherOutputStream os = enc.outputStream(dos, true); try { int size = cred==null?0:cred.length; - for(int i=0;i>i)&0xFF)); } - if(cred!=null) { + if (cred!=null) { os.write(cred); } df.newData().load(t).to(os); @@ -128,7 +128,7 @@ public class PersistFile { return null; } }); - } catch(Exception e) { + } catch (Exception e) { throw new CadiException(e); } finally { dos.close(); @@ -141,7 +141,7 @@ public class PersistFile { } public T readDisk(final RosettaDF df, final byte[] cred, final String filename,final Holder hp, final Holder hl) throws CadiException { - if(hp.get()==null) { + if (hp.get()==null) { hp.set(Paths.get(tokenDir,filename)); } return readDisk(df,cred,hp.get(),hl); @@ -150,13 +150,13 @@ public class PersistFile { 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)) { + if (Files.exists(target)) { try { final InputStream is = Files.newInputStream(target,StandardOpenOption.READ); try { // Read Expired unencrypted long exp=0; - for(int i=0;i256) { + if (size>256) { throw new CadiException("Invalid size in Token Persistence"); - } else if(cred!=null && size!=cred.length) { + } else if (cred!=null && size!=cred.length) { throw new CadiException(HASH_NO_MATCH); } - if(cred!=null) { + if (cred!=null) { byte[] array = new byte[size]; - if(dis.read(array)>0) { - for(int i=0;i0) { + for (int i=0;i hp) throws IOException { Path p = hp.get(); - if(p==null) { + 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/Persisting.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/Persisting.java index dd136a2a..bde60777 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 @@ -54,7 +54,7 @@ public class Persisting implements Persistable { } count=0; nextCheck=0; - if(hash==null) { + if (hash==null) { this.hash = EMPTY; } else { this.hash = hash; @@ -80,7 +80,7 @@ public class Persisting implements Persistable { public boolean hasBeenTouched() { try { FileTime modT = Files.getLastModifiedTime(path); - if(lastTouched==null) { + if (lastTouched==null) { lastTouched = modT; return true; } else { @@ -98,7 +98,7 @@ public class Persisting implements Persistable { @Override public synchronized boolean checkSyncTime() { long temp=System.currentTimeMillis(); - if(nextCheck==0 || nextCheck implements Persistable { @Override public boolean match(byte[] hashIn) { - if(hash==null || hashIn==null || hash.length!=hashIn.length) { + if (hash==null || hashIn==null || hash.length!=hashIn.length) { return false; } - for(int i=0;i { timer = new Timer(REGISTRAR,true); timer.schedule(new RegistrationTimerTask(env), START, INTERVAL); - if(shutdownHook) { + if (shutdownHook) { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { close(env); @@ -61,18 +61,18 @@ public class Registrar { } @Override public void run() { - for(Iterator> iter = registrants.iterator(); iter.hasNext();) { + for (Iterator> iter = registrants.iterator(); iter.hasNext();) { Registrant reg = iter.next(); Result rv = reg.update(env); synchronized(LOCK) { - if(rv.isOK()) { - if(erroringTimer!=null) { + if (rv.isOK()) { + if (erroringTimer!=null) { erroringTimer.cancel(); erroringTimer = null; } } else { // Account for different Registrations not being to same place - if(erroringTimer==null) { + if (erroringTimer==null) { erroringTimer = new Timer(REGISTRAR + " error re-check ",true); erroringTimer.schedule(new RegistrationTimerTask(env),20000,20000); } @@ -94,7 +94,7 @@ public class Registrar { timer.cancel(); Registrant r; - while(registrants.peek()!=null) { + 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 ae7ded3a..49d40ab4 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 @@ -67,12 +67,12 @@ public class RemoteRegistrant implements Registrant { } 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) { + 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) { + if (aaf_locate.indexOf(',')>=0) { locator = new PropertyLocator(aaf_locate); } else { locator = new SingleEndpointLocator(aaf_locate); @@ -88,23 +88,23 @@ public class RemoteRegistrant implements Registrant { try { String hostnameToRegister = access.getProperty(Config.AAF_REGISTER_AS, null); - if(hostnameToRegister==null) { + if (hostnameToRegister==null) { hostnameToRegister = access.getProperty(Config.HOSTNAME, null); } - if(hostnameToRegister==null) { + if (hostnameToRegister==null) { hostnameToRegister = Inet4Address.getLocalHost().getHostName(); } mep.setHostname(hostnameToRegister); String latitude = access.getProperty(Config.CADI_LATITUDE, null); - if(latitude==null) { + if (latitude==null) { latitude = access.getProperty("AFT_LATITUDE", null); } String longitude = access.getProperty(Config.CADI_LONGITUDE, null); - if(longitude==null) { + if (longitude==null) { longitude = access.getProperty("AFT_LONGITUDE", null); } - if(latitude==null || 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)); @@ -117,11 +117,11 @@ public class RemoteRegistrant implements Registrant { mep.setMajor(split.length>0?Integer.parseInt(split[0]):0); String subprotocols = access.getProperty(Config.CADI_PROTOCOLS, null); - if(subprotocols==null) { + if (subprotocols==null) { mep.setProtocol("http"); } else { mep.setProtocol("https"); - for(String s : Split.split(',', subprotocols)) { + for (String s : Split.split(',', subprotocols)) { mep.getSubprotocol().add(s); } } @@ -130,7 +130,7 @@ public class RemoteRegistrant implements Registrant { } meps = new MgmtEndpoints(); meps.getMgmtEndpoint().add(mep); - for(RemoteRegistrant rr : others) { + for (RemoteRegistrant rr : others) { meps.getMgmtEndpoint().add(rr.mep); } } @@ -141,7 +141,7 @@ public class RemoteRegistrant implements Registrant { Rcli client = aafcon.client(locator); try { Future fup = client.update("/registration",mgmtEndpointsDF,meps); - if(fup.get(timeout)) { + if (fup.get(timeout)) { access.log(Level.INFO, "Registration complete to",client.getURI()); return Result.ok(fup.code(),null); } else { @@ -164,7 +164,7 @@ public class RemoteRegistrant implements Registrant { Rcli client = aafcon.client(locator); try { Future fup = client.delete("/registration",mgmtEndpointsDF,meps); - if(fup.get(timeout)) { + if (fup.get(timeout)) { access.log(Level.INFO, "Deregistration complete on",client.getURI()); return Result.ok(fup.code(),null); } else { 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 77be3449..38d4852f 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 @@ -95,7 +95,7 @@ public class AAFSSO { System.setErr(os); sso = new File(dot_aaf, "sso.props"); - if(sso.exists()) { + if (sso.exists()) { InputStream propStream = new FileInputStream(sso); try { diskprops.load(propStream); @@ -114,8 +114,8 @@ public class AAFSSO { if (sso.exists()) { Properties temp = new Properties(); // Keep only these - for(Entry es : diskprops.entrySet()) { - if(Config.CADI_LATITUDE.equals(es.getKey()) || + 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()); @@ -143,15 +143,15 @@ public class AAFSSO { } } - for(Entry es : diskprops.entrySet()) { + 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, + 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); @@ -159,7 +159,7 @@ public class AAFSSO { 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}) { +// for (String tag : new String[] {Config.AAF_APPPASS,Config.CADI_KEYSTORE_PASSWORD,Config.CADI_KEY_PASSWORD}) { // access.getProperties().remove(tag); // diskprops.remove(tag); // } @@ -175,7 +175,7 @@ public class AAFSSO { String alias, appID; alias = access.getProperty(Config.CADI_ALIAS); - if(alias==null) { + if (alias==null) { appID = access.getProperty(Config.AAF_APPID); user=appID; } else { @@ -183,7 +183,7 @@ public class AAFSSO { appID=null; } - if(appID!=null && access.getProperty(Config.AAF_APPPASS)==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); @@ -193,7 +193,7 @@ public class AAFSSO { 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))) { + if (user==null || (alias!=null && (keystore==null || keystore_pass==null))) { String select = null; String name; for (File tsf : dot_aaf.listFiles()) { @@ -201,7 +201,7 @@ public class AAFSSO { 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)) { + if ("y".equalsIgnoreCase(select)) { keystore = tsf.getCanonicalPath(); access.setProperty(Config.CADI_KEYSTORE, keystore); addProp(Config.CADI_KEYSTORE, keystore); @@ -218,7 +218,7 @@ public class AAFSSO { } } } - if(alias==null) { + if (alias==null) { user = appID = cons.readLine(Config.AAF_APPID + ": "); access.setProperty(Config.AAF_APPID, appID); addProp(Config.AAF_APPID, appID); @@ -229,7 +229,7 @@ public class AAFSSO { } } else { encrypted_pass = access.getProperty(Config.CADI_KEYSTORE_PASSWORD); - if(encrypted_pass == null) { + if (encrypted_pass == null) { keystore_pass = null; encrypted_pass = access.getProperty(Config.AAF_APPPASS); } else { @@ -298,9 +298,9 @@ public class AAFSSO { } String locateUrl = access.getProperty(Config.AAF_LOCATE_URL); - if(locateUrl==null) { + if (locateUrl==null) { locateUrl=AAFSSO.cons.readLine("AAF Locator URL=https://"); - if(locateUrl==null || locateUrl.length()==0) { + if (locateUrl==null || locateUrl.length()==0) { err = new StringBuilder(Config.AAF_LOCATE_URL); err.append(" is required."); ok = false; @@ -315,10 +315,10 @@ public class AAFSSO { 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) { + 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()) { + if (cadiLatitude==null || cadiLatitude.isEmpty()) { cadiLatitude="0.000"; } access.setProperty(Config.CADI_LATITUDE, cadiLatitude); @@ -326,9 +326,9 @@ public class AAFSSO { } String cadiLongitude = access.getProperty(Config.CADI_LONGITUDE); - if(cadiLongitude==null) { + if (cadiLongitude==null) { cadiLongitude=AAFSSO.cons.readLine("cadi_longitude[0.000]="); - if(cadiLongitude==null || cadiLongitude.isEmpty()) { + if (cadiLongitude==null || cadiLongitude.isEmpty()) { cadiLongitude="0.000"; } access.setProperty(Config.CADI_LONGITUDE, cadiLongitude); @@ -336,7 +336,7 @@ public class AAFSSO { } String cadi_truststore = access.getProperty(Config.CADI_TRUSTSTORE); - if(cadi_truststore==null) { + if (cadi_truststore==null) { String name; String select; for (File tsf : dot_aaf.listFiles()) { @@ -344,7 +344,7 @@ public class AAFSSO { 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)) { + if ("y".equalsIgnoreCase(select)) { cadi_truststore=tsf.getCanonicalPath(); access.setProperty(Config.CADI_TRUSTSTORE, cadi_truststore); addProp(Config.CADI_TRUSTSTORE, cadi_truststore); @@ -353,12 +353,12 @@ public class AAFSSO { } } } - if(cadi_truststore!=null) { - if(cadi_truststore.indexOf(File.separatorChar)<0) { + 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) { + 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); @@ -381,7 +381,7 @@ public class AAFSSO { } public void setLogDefault(Level level) { - if(access!=null) { + if (access!=null) { access.setLogLevel(level); } System.setOut(stdOutOrig); @@ -392,7 +392,7 @@ public class AAFSSO { } public void addProp(String key, String value) { - if(key==null || value==null) { + if (key==null || value==null) { return; } touchDiskprops=true; @@ -400,7 +400,7 @@ public class AAFSSO { } public void writeFiles() throws IOException { - if(touchDiskprops) { + if (touchDiskprops) { // Store Creds, if they work if (diskprops != null) { if (!dot_aaf.exists()) { 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 8cb4e906..5e642c67 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 @@ -44,14 +44,14 @@ public class TestHClient { try { PropAccess access = new PropAccess(args); String aaf_url = access.getProperty(Config.AAF_URL); - if(aaf_url == null) { + 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)) { + for (Item item = loc.first(); item!=null; item=loc.next(item)) { System.out.println(loc.get(item)); } @@ -62,7 +62,7 @@ public class TestHClient { @Override public Void code(Rcli cli) throws APIException, CadiException { Future ft = cli.read(path,"application/json"); - if(ft.get(10000)) { + if (ft.get(10000)) { System.out.println("Hurray,\n"+ft.body()); } else { System.out.println("not quite: " + ft.code()); @@ -70,7 +70,7 @@ public class TestHClient { return null; }}); } finally { - if(hman!=null) { + if (hman!=null) { hman.close(); } } 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 70550451..60e5b44a 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 @@ -110,14 +110,14 @@ public class JU_ArtifactDir { try { ArtifactDir.write(writableFile, Chmod.to755, (String[])null); fail("Should've thrown an exception"); - } catch(NullPointerException e) { + } 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) { + } catch (CadiException e) { } ks.load(null, null); 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 76c31b8d..69709d9f 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 @@ -331,8 +331,8 @@ public class JU_Factory { private String join(String delim, List rawLines) { StringBuilder sb = new StringBuilder(); boolean first = true; - for(String s : rawLines) { - if(first) { + for (String s : rawLines) { + if (first) { first = false; } else { sb.append(delim); 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 1a653ab2..777ca16d 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 @@ -141,8 +141,8 @@ public class JU_PlaceArtifactInKeystore { baos.write(br.readLine().getBytes()); // Here comes the hacky part baos.write("\n".getBytes()); - while((line=br.readLine())!=null) { - if(line.length()>0) { + while ((line=br.readLine())!=null) { + if (line.length()>0) { baos.write(line.getBytes()); baos.write("\n".getBytes()); } 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 537e218f..24e30a46 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 @@ -49,7 +49,7 @@ public class JU_AAFToken { @Test public void testRandom() throws CadiException { - for(int i=0;i<100;++i) { + for (int i=0;i<100;++i) { UUID uuid = UUID.randomUUID(); String token = AAFToken.toToken(uuid); UUID uuid2 = AAFToken.fromToken(token); 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 ef22b792..03c99d2a 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 @@ -109,21 +109,21 @@ public class JU_OAuthTest { TokenClient tc; Result rtt; - if(true) { + 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()) { + if (rtt.isOK()) { print(rtt.value); rtt = tc.refreshToken(rtt.value); - if(rtt.isOK()) { + 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()) { + if (ri.isOK()) { print(ri.value); } else { System.out.println(ri.code + ' ' + ri.error); @@ -145,28 +145,28 @@ public class JU_OAuthTest { } // ISAM Test - if(true) { + 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) { + 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()) { + if (rtt.isOK()) { print(rtt.value); rtt = tc.refreshToken(rtt.value); - if(rtt.isOK()) { + 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()) { + if (rti.isOK()) { System.out.print("Normal ISAM "); print(rti.value); } else { @@ -177,12 +177,12 @@ public class JU_OAuthTest { tc = tcf.newClient(tokenIntrospectURL, 3000); tc.client_creds(client_id, client_secret); rti = tc.introspect(rtt.value.getAccessToken()); - if(rti.isOK()) { + 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) { + if (rti.code!=404) { Assert.fail(rti.code + ' ' + rti.error); } } @@ -214,14 +214,14 @@ public class JU_OAuthTest { // 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) { +// if (user!=null && password!=null) { // tclient.password(user,password); // } // Result rt = tclient.getToken(scope); -// if(rt.isOK()) { +// if (rt.isOK()) { // print(rt.value); // Result rti = tclient.introspect(rt.value.getAccessToken()); -// if(rti.isOK()) { +// if (rti.isOK()) { // print(rti.value); // } else { // printAndFail(rti); @@ -237,7 +237,7 @@ public class JU_OAuthTest { @Override public String code(Rcli client) throws CadiException, ConnectException, APIException { Future future = client.read(null,"text/plain"); - if(future.get(3000)) { + if (future.get(3000)) { return future.value; } else { throw new APIException(future.code() + future.body()); @@ -263,7 +263,7 @@ public class JU_OAuthTest { } private void print(Introspect ti) { - if(ti==null || ti.getClientId()==null) { + if (ti==null || ti.getClientId()==null) { System.out.println("Empty Introspect"); return; } 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 8881e76e..4e51579d 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 @@ -70,7 +70,7 @@ public class Sample { */ public Principal checkUserPass(String fqi, String pass) throws IOException, CadiException { String ok = aafAuthn.validate(fqi, pass); - if(ok==null) { + if (ok==null) { System.out.println("Success!"); /* UnAuthPrincipal means that it is not coming from the official Authorization chain. @@ -127,14 +127,14 @@ public class Sample { String user = myAccess.getProperty("user_fqi"); String pass= myAccess.getProperty("user_pass"); - if(user==null || pass==null) { + 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) { + 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); @@ -146,10 +146,10 @@ public class Sample { // note, default String for perm String permS = myAccess.getProperty("perm","org.osaaf.aaf.access|*|read"); String[] permA = Split.splitTrim('|', permS); - if(permA.length>2) { + 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)) { + 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); @@ -160,11 +160,11 @@ public class Sample { // 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) { + 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) { + for (Permission p : permL) { System.out.printf("\t%s has %s\n",fqi.getName(),p.getKey()); } } 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 cce7b5f3..da85702d 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 @@ -76,7 +76,7 @@ public abstract class AbsAuthentication implements SecuritySetter implements SecuritySetter0 && lastMiss>System.currentTimeMillis()) { + if (lastMiss>0 && lastMiss>System.currentTimeMillis()) { return true; } else { lastMiss=0L; @@ -102,17 +102,17 @@ public abstract class AbsAuthentication implements SecuritySetterMAX_TEMP_COUNT) { + if (lastMiss==0L && count>MAX_TEMP_COUNT) { lastMiss=System.currentTimeMillis()+WAIT_TIME; } - // if(count>MAX_SPAM_COUNT) { + // 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) { + 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); } 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 0c38bd90..baac6daa 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 @@ -56,7 +56,7 @@ public abstract class AbsTransferSS implements SecuritySetter { private void init(TaggedPrincipal principal, String app) { this.principal=principal; - if(principal==null) { + if (principal==null) { return; } else { value = principal.getName() + ':' + 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 b414487b..6b486b8e 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 @@ -268,20 +268,20 @@ public abstract class Rcli { @Override public void transfer(OutputStream os) throws IOException, APIException { PrintStream ps; - if(os instanceof PrintStream) { + if (os instanceof PrintStream) { ps = (PrintStream)os; } else { ps = new PrintStream(os); } boolean first = true; - for(String fp : formParam) { - if(fp!=null) { - if(first) { + for (String fp : formParam) { + if (fp!=null) { + if (first) { first = false; } else { ps.print('&'); } - if(fp.endsWith("=")) { + if (fp.endsWith("=")) { first = true; } ps.print(fp); @@ -376,7 +376,7 @@ public abstract class Rcli { client.setMethod(GET); client.addHeader(ACCEPT, accept); - for(int i=1;i { EClient client = client(); client.setMethod(GET); client.addHeader(ACCEPT, accept); - for(int i=1;i { EClient client = client(); client.setMethod(GET); client.addHeader(ACCEPT, typeString(df.getTypeClass())); - for(int i=1;i { throw new CadiException("Invalid incoming URI",e); } String name; - for(Enumeration en = req.getHeaderNames();en.hasMoreElements();) { + for (Enumeration en = req.getHeaderNames();en.hasMoreElements();) { name = en.nextElement(); client.addHeader(name,req.getHeader(name)); } @@ -673,7 +673,7 @@ public abstract class Rcli { client.setPathInfo(pathParam); String meth = req.getMethod(); client.setMethod(meth); - if(!"GET".equals(meth)) { + if (!"GET".equals(meth)) { client.setPayload(new EClient.Transfer() { @Override public void transfer(OutputStream os) throws IOException, APIException { @@ -682,7 +682,7 @@ public abstract class Rcli { // reuse Buffers Pooled pbuff = buffPool.get(); try { - while((read=is.read(pbuff.content))>=0) { + while ((read=is.read(pbuff.content))>=0) { os.write(pbuff.content,0,read); } } finally { @@ -704,21 +704,21 @@ public abstract class Rcli { public ParsePath(final String origPath) { path = origPath; - if(origPath==null) { + 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) { + if (oneCallQueryParams==null) { + if (query>=0) { queryParams = path.substring(query+1,queryEnd); } else { queryParams=null; } } else { - if(query>=0) { + if (query>=0) { queryParams = oneCallQueryParams + '&' + path.substring(query+1,queryEnd); } else { queryParams = oneCallQueryParams; @@ -729,12 +729,12 @@ public abstract class Rcli { } public String path() { - if(query>=0) { - if(pound>=0) { + if (query>=0) { + if (pound>=0) { return path.substring(pound+1); } return path.substring(0,query); - } else if(pound>=0) { + } else if (pound>=0) { return path.substring(0,pound); } else { return path; @@ -746,7 +746,7 @@ public abstract class Rcli { } public String frag() { - if(pound>=0) { + if (pound>=0) { return path.substring(pound+1); } else { return null; 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 e9de27e7..0e2a4b16 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 @@ -51,7 +51,7 @@ public class Result { public String toString() { StringBuilder sb = new StringBuilder("Code: "); sb.append(code); - if(error!=null) { + if (error!=null) { sb.append(" = "); sb.append(error); } 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 3c38ff8d..c2f56458 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 @@ -38,7 +38,7 @@ public class HAuthorizationHeader extends AbsAuthentication { @Override public void setSecurity(HttpURLConnection huc) throws CadiException { - if(isDenied()) { + if (isDenied()) { throw new CadiException(REPEAT_OFFENDER); } try { @@ -46,7 +46,7 @@ public class HAuthorizationHeader extends AbsAuthentication { } catch (IOException e) { throw new CadiException(e); } - if(securityInfo!=null && huc instanceof HttpsURLConnection) { + 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 e4ab6d72..7e5cbd3b 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 @@ -48,7 +48,7 @@ public class HBasicAuthSS extends HAuthorizationHeader implements BasicAuth { public HBasicAuthSS(SecurityInfoC si, String user, String pass, boolean asDefault) throws IOException { this(si, user,pass); - if(asDefault) { + if (asDefault) { si.set(this); } } @@ -59,7 +59,7 @@ public class HBasicAuthSS extends HAuthorizationHeader implements BasicAuth { public HBasicAuthSS(BasicPrincipal bp, SecurityInfoC si, boolean asDefault) throws IOException { this(si, bp.getName(),new String(bp.getCred())); - if(asDefault) { + 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 1d3d9547..d8852834 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 @@ -111,13 +111,13 @@ public class HClient implements EClient { public void send() throws APIException { try { // Build URL from given URI plus current Settings - if(uri.getPath()==null) { + if (uri.getPath()==null) { throw new APIException("Invalid URL entered for HClient"); } StringBuilder pi=null; - if(pathinfo!=null) { // additional pathinfo + if (pathinfo!=null) { // additional pathinfo pi = new StringBuilder(uri.getPath()); - if(!pathinfo.startsWith("/")) { + if (!pathinfo.startsWith("/")) { pi.append('/'); } pi.append(pathinfo); @@ -133,7 +133,7 @@ public class HClient implements EClient { ); huc = getConnection(sendURI, pi); huc.setRequestMethod(meth); - if(ss!=null) { + if (ss!=null) { ss.setSecurity(huc); } if (headers != null) @@ -153,7 +153,7 @@ public class HClient implements EClient { throw new APIException(e); } finally { // ensure all these are reset after sends meth=pathinfo=null; - if(headers!=null) { + if (headers!=null) { headers.clear(); } pathinfo = query = fragment = ""; @@ -200,7 +200,7 @@ public class HClient implements EClient { huc.setReadTimeout(timeout); respCode = huc.getResponseCode(); ss.setLastResponse(respCode); - if(evalInfo(huc)) { + if (evalInfo(huc)) { return true; } else { extractError(); @@ -216,13 +216,13 @@ public class HClient implements EClient { private void extractError() { InputStream is = huc.getErrorStream(); try { - if(is==null) { + if (is==null) { is = huc.getInputStream(); } - if(is!=null) { + if (is!=null) { errContent = new StringBuilder(); int c; - while((c=is.read())>=0) { + while ((c=is.read())>=0) { errContent.append((char)c); } } @@ -274,7 +274,7 @@ public class HClient implements EClient { } public void close() { - if(huc!=null) { + if (huc!=null) { huc.disconnect(); } } @@ -382,12 +382,12 @@ public class HClient implements EClient { int read; InputStream is; OutputStream os = resp.getOutputStream(); - if(respCode==expected) { + if (respCode==expected) { is = huc.getInputStream(); // reuse Buffers Pooled pbuff = Rcli.buffPool.get(); try { - while((read=is.read(pbuff.content))>=0) { + while ((read=is.read(pbuff.content))>=0) { os.write(pbuff.content,0,read); } } finally { @@ -396,14 +396,14 @@ public class HClient implements EClient { return true; } else { is = huc.getErrorStream(); - if(is==null) { + if (is==null) { is = huc.getInputStream(); } - if(is!=null) { + if (is!=null) { errContent = new StringBuilder(); Pooled pbuff = Rcli.buffPool.get(); try { - while((read=is.read(pbuff.content))>=0) { + while ((read=is.read(pbuff.content))>=0) { os.write(pbuff.content,0,read); } } finally { 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 da349efc..8e3138af 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 @@ -49,7 +49,7 @@ public class HMangr { public HMangr(Access access, Locator loc) throws LocatorException { readTimeout = 10000; connectionTimeout=3000; - if(loc == null) { + if (loc == null) { throw new LocatorException("Null Locator passed"); } this.loc = loc; @@ -79,20 +79,20 @@ public class HMangr { do { Item item; // if no previous state, get the best - if(retryable.item()==null) { + if (retryable.item()==null) { item = loc.best(); - if(item==null) { + if (item==null) { throw new LocatorException("No Services Found for " + loc); } retryable.item(item); retryable.lastClient = null; } - if(client==null) { + if (client==null) { item = retryable.item(); URI uri=loc.get(item); - if(uri==null) { + if (uri==null) { loc.invalidate(retryable.item()); - if(loc.hasItems()) { + if (loc.hasItems()) { retryable.item(loc.next(retryable.item())); continue; } else { @@ -116,22 +116,22 @@ public class HMangr { retryable.item(loc.next(item)); try { Throwable ec = e.getCause(); - if(ec instanceof java.net.ConnectException) { - if(client!=null && loc.hasItems()) { + 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()) { + } 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())) { + } 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); @@ -148,7 +148,7 @@ public class HMangr { loc.invalidate(item); retryable.item(loc.next(item)); } - } while(retry); + } while (retry); } finally { retryable.lastClient = client; } @@ -172,9 +172,9 @@ public class HMangr { RET ret = null; // make sure we have all current references: loc.refresh(); - for(Item li=loc.first();li!=null;li=loc.next(li)) { + for (Item li=loc.first();li!=null;li=loc.next(li)) { URI uri=loc.get(li); - if(host!=null && !host.equals(uri.getHost())) { + if (host!=null && !host.equals(uri.getHost())) { break; } try { @@ -182,14 +182,14 @@ public class HMangr { 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) { + 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) { + } 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())) { + } 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); @@ -203,7 +203,7 @@ public class HMangr { } } - if(ret == null && notify) + if (ret == null && notify) throw new LocatorException("No available clients to call"); return ret; } 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 0f1c8b41..1fecce2b 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 @@ -37,7 +37,7 @@ public class HNoAuthSS extends AbsAuthentication { @Override public void setSecurity(HttpURLConnection client) throws CadiException { - if(securityInfo!=null && client instanceof HttpsURLConnection) { + 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 674936d7..cbd7b33e 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 @@ -81,9 +81,9 @@ public class HRcli extends Rcli { */ protected EClient client() throws CadiException { try { - if(uri==null) { + if (uri==null) { Item item = hman.loc.best(); - if(item==null) { + if (item==null) { throw new CadiException("No service available for " + hman.loc.toString()); } uri = hman.loc.get(item); 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 d792be49..3f3517f2 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 @@ -41,9 +41,9 @@ public class HSecurityInfoInit implements SecurityInfoInit { @Override public SecuritySetter bestDefault(SecurityInfoC si) throws CadiException { try { - if(si.defaultAlias!=null) { + if (si.defaultAlias!=null) { si.set(new HX509SS(si)); - } else if(si.access.getProperty(Config.AAF_APPID, null)!=null && + } else if (si.access.getProperty(Config.AAF_APPID, null)!=null && si.access.getProperty(Config.AAF_APPPASS, null)!=null) { si.set(new HBasicAuthSS(si)); } 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 c527ed02..f68c1f61 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 @@ -44,14 +44,14 @@ public class HTransferSS extends AbsTransferSS { @Override public void setSecurity(HttpURLConnection huc) throws CadiException { - if(defSS==null) { + if (defSS==null) { throw new CadiException("Need App Credentials to send message"); } defSS.setSecurity(huc); - if(value!=null) { + if (value!=null) { huc.addRequestProperty(Config.CADI_USER_CHAIN, value); } - if(securityInfo!=null) { + if (securityInfo!=null) { securityInfo.setSocketFactoryOn((HttpsURLConnection)huc); } } 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 cb8e6ce0..f441186e 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 @@ -68,8 +68,8 @@ public class HX509SS implements SecuritySetter { public HX509SS(final String sendAlias, SecurityInfoC si, boolean asDefault) throws APIException, CadiException { securityInfo = si; - if((alias=sendAlias) == null) { - if(si.defaultAlias == null) { + 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; @@ -78,16 +78,16 @@ public class HX509SS implements SecuritySetter { priv=null; X509KeyManager[] xkms = si.getKeyManagers(); - if(xkms==null || xkms.length==0) { + 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) { + if (chain!=null&&chain.length>0) { algo = chain[0].getSigAlgName(); pub = chain[0].getEncoded(); ByteArrayOutputStream baos = new ByteArrayOutputStream(pub.length*2); @@ -99,17 +99,17 @@ public class HX509SS implements SecuritySetter { } catch (CertificateEncodingException | IOException e) { throw new CadiException(e); } - if(algo==null) { + if (algo==null) { throw new APIException("X509 Security Setter not configured"); } } @Override public void setSecurity(HttpURLConnection huc) throws CadiException { - if(huc instanceof HttpsURLConnection) { + if (huc instanceof HttpsURLConnection) { securityInfo.setSocketFactoryOn((HttpsURLConnection)huc); } - if(alias==null) { // must be a one-way + if (alias==null) { // must be a one-way huc.setRequestProperty(AbsAuthentication.AUTHORIZATION, cert); // Test Signed content 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 1fc4b83e..8357129f 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 @@ -46,7 +46,7 @@ public class DNSLocator implements Locator { this.protocol = protocol; this.access = access; int dash = range.indexOf('-'); - if(dash<0) { + if (dash<0) { startPort = endPort = Integer.parseInt(range); } else { startPort = Integer.parseInt(range.substring(0,dash)); @@ -57,15 +57,15 @@ public class DNSLocator implements Locator { public DNSLocator(Access access, String aaf_locate) throws LocatorException { this.access = access; - if(aaf_locate==null) { + if (aaf_locate==null) { throw new LocatorException("Null passed into DNSLocator constructor"); } int start, port; - if(aaf_locate.startsWith("https:")) { + if (aaf_locate.startsWith("https:")) { protocol = "https:"; start = 9; // https:// port = 443; - } else if(aaf_locate.startsWith("http:")) { + } else if (aaf_locate.startsWith("http:")) { protocol = "http:"; start = 8; // http:// port = 80; @@ -83,8 +83,8 @@ public class DNSLocator implements Locator { @Override public boolean hasItems() { - for(Host h : hosts) { - if(h.status==Status.OK) { + for (Host h : hosts) { + if (h.status==Status.OK) { return true; } } @@ -100,7 +100,7 @@ public class DNSLocator implements Locator { @Override public Item best() throws LocatorException { // not a good "best" - for(int i=0;i { break; case UNTRIED: try { - if(hosts[i].ia.isReachable(CHECK_TIME)) { + if (hosts[i].ia.isReachable(CHECK_TIME)) { hosts[i].status = Status.OK; return new DLItem(i); } @@ -133,7 +133,7 @@ public class DNSLocator implements Locator { @Override public Item next(Item item) throws LocatorException { DLItem di = (DLItem)item; - if(++di.cnt { 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 { private void parsePorts(String aaf_locate, int defaultPort) throws LocatorException { int slash, start; int colon = aaf_locate.indexOf(':'); - if(colon > 0) { + if (colon > 0) { start = colon + 1; int left = aaf_locate.indexOf('[', start); - if(left > 0) { + 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 + ')'); @@ -176,7 +176,7 @@ public class DNSLocator implements Locator { if (dash == (right - 1) || dash == (left + 1)) { throw new LocatorException("Missing ports in brackets in DNSLocator constructor. (requested URL " + aaf_locate + ')'); } - if(dash < 0) { + if (dash < 0) { startPort = endPort = Integer.parseInt(aaf_locate.substring(left + 1, right)); } else { startPort = Integer.parseInt(aaf_locate.substring(left + 1, dash)); @@ -188,7 +188,7 @@ public class DNSLocator implements Locator { if (slash == start) { throw new LocatorException("Missing port before '/' in DNSLocator constructor. (requested URL " + aaf_locate + ')'); } - if(slash < 0) { + if (slash < 0) { startPort = endPort = Integer.parseInt(aaf_locate.substring(start)); } else { startPort = endPort = Integer.parseInt(aaf_locate.substring(start, slash)); 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 26b8817b..93cefc58 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 @@ -74,15 +74,15 @@ public abstract class HotPeerLocator implements Locator { this.invalidateTime = invalidateTime; double distance = Double.MAX_VALUE; - for(int i=0;i implements Locator { distances[i]=d; // find preferred server - if(d implements Locator { @Override public Item best() throws LocatorException { - if(failures[preferred]==0L) { + if (failures[preferred]==0L) { return new HPItem(preferred); } else { long now = System.currentTimeMillis(); @@ -125,9 +125,9 @@ public abstract class HotPeerLocator implements Locator { int best = -1; boolean tickle = false; // try for best existing client - for(int i=0;i implements Locator { } } } - if(best<0 && tickle) { + if (best<0 && tickle) { tickle=false; - if(refresh()) { + if (refresh()) { // try again - for(int i=0;i implements Locator { * If a valid client is available, but there are some that can refresh, return the client immediately * but start a Thread to do the background Client setup. */ - if(tickle) { + if (tickle) { synchronized(clients) { - if(refreshThread==null) { + if (refreshThread==null) { refreshThread = new Thread(new Runnable(){ @Override public void run() { @@ -170,7 +170,7 @@ public abstract class HotPeerLocator implements Locator { } } - if(best<0) { + if (best<0) { throw new LocatorException("No Clients available"); } @@ -183,8 +183,8 @@ public abstract class HotPeerLocator implements Locator { 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()) { + if (c==null) { + if (failures[hpi.idx]>System.currentTimeMillis()) { throw new LocatorException("Client requested is invalid"); } else { synchronized(clients) { @@ -192,7 +192,7 @@ public abstract class HotPeerLocator implements Locator { failures[hpi.idx]=0L; } } - } else if(failures[hpi.idx]>0){ + } else if (failures[hpi.idx]>0){ throw new LocatorException("Client requested is invalid"); } return c; @@ -200,7 +200,7 @@ public abstract class HotPeerLocator implements Locator { public String info(Item item) { HPItem hpi = (HPItem)item; - if(hpi!=null && hpi.idx implements Locator { @Override public boolean hasItems() { - for(int i=0;i implements Locator { @Override public Item next(Item item) throws LocatorException { HPItem hpi = (HPItem)item; - if(++hpi.idx>=clients.length) { + if (++hpi.idx>=clients.length) { return null; } return hpi; @@ -244,11 +244,11 @@ public abstract class HotPeerLocator implements Locator { 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] implements Locator { @Override public void destroy() { - for(int i=0;i implements Locator { } public boolean invalidate(CLIENT client) throws LocatorException { - for(int i=0;i { minRefresh = minRefreshMillis; backgroundRefresh = backgroundRefreshMillis; lastRefreshed=0L; - if(locList==null) { + if (locList==null) { throw new LocatorException("No Location List given for PropertyLocator"); } String[] locarray = Split.split(',',locList); @@ -69,10 +69,10 @@ public class PropertyLocator implements Locator { random = new SecureRandom(); - for(int i=0;i { int slash = locarray[i].indexOf('/',brac); int start = Integer.parseInt(locarray[i].substring(range+2, dash)); int end = Integer.parseInt(locarray[i].substring(dash+1, brac)); - for(int port=start;port<=end;++port) { + for (int port=start;port<=end;++port) { uriList.add(new URI(mach_colon+port + (slash>=0?locarray[i].substring(slash):""))); } } @@ -106,7 +106,7 @@ public class PropertyLocator implements Locator { @Override public URI get(Item item) throws LocatorException { synchronized(orig) { - if(item==null) { + if (item==null) { return null; } else { return resolved[((PLItem)item).idx]; @@ -126,31 +126,31 @@ public class PropertyLocator implements Locator { @Override public Item next(Item item) throws LocatorException { - if(item==null) { + if (item==null) { return null; } else { int spot; - if((spot=(((PLItem)item).order+1))>=end)return null; + if ((spot=(((PLItem)item).order+1))>=end)return null; return current[spot]; } } @Override public synchronized void invalidate(Item item) throws LocatorException { - if(--end<0) { + if (--end<0) { refresh(); return; } - if(item==null) { + if (item==null) { return; } PLItem pli = (PLItem)item; int i,order; - for(i=0;i { @Override public Item best() throws LocatorException { - if(current.length==0) { + if (current.length==0) { refresh(); } switch(current.length) { @@ -175,27 +175,27 @@ public class PropertyLocator implements Locator { @Override public synchronized boolean refresh() { - if(System.currentTimeMillis()>lastRefreshed) { + if (System.currentTimeMillis()>lastRefreshed) { // Build up list List resolve = new ArrayList<>(); String realname; - for(int i = 0; i < orig.length ; ++i) { + for (int i = 0; i < orig.length ; ++i) { try { InetAddress ia[] = InetAddress.getAllByName(orig[i].getHost()); URI o,n; - for(int j=0;j { } } catch (IOException e) { } finally { - if(!socket.isClosed()) { + if (!socket.isClosed()) { try { socket.close(); } catch (IOException e) { @@ -227,14 +227,14 @@ public class PropertyLocator implements Locator { } end=resolve.size(); PLItem[] newCurrent; - if(current==null || current.length!=end) { + if (current==null || current.length!=end) { newCurrent = new PLItem[end]; } else { newCurrent = current; } - for(int i=0; i< end; ++i) { - if(newCurrent[i]==null){ + for (int i=0; i< end; ++i) { + if (newCurrent[i]==null){ newCurrent[i]=new PLItem(i); } else { newCurrent[i].idx=newCurrent[i].order=i; @@ -271,18 +271,18 @@ public class PropertyLocator implements Locator { public String toString() { StringBuilder sb = new StringBuilder(); boolean first = true; - for(URI uri : orig) { + for (URI uri : orig) { boolean isResolved=false; - if(uri!=null) { - if(first) { + if (uri!=null) { + if (first) { first = false; } else { sb.append(", "); } sb.append(uri.toString()); sb.append(" ["); - for(URI u2 : resolved) { - if(uri.equals(u2)) { + for (URI u2 : resolved) { + if (uri.equals(u2)) { isResolved = true; break; } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/locator/SingleEndpointLocator.java b/cadi/client/src/main/java/org/onap/aaf/cadi/locator/SingleEndpointLocator.java index 816dec82..3b79dba5 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/locator/SingleEndpointLocator.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/locator/SingleEndpointLocator.java @@ -47,8 +47,8 @@ public class SingleEndpointLocator implements Locator { @Override public boolean hasItems() { - if(noRetryUntil!=null) { - if(new Date().after(noRetryUntil)) { + if (noRetryUntil!=null) { + if (new Date().after(noRetryUntil)) { noRetryUntil = null; } else { return false; 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 3bce5245..27eb507f 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 @@ -87,7 +87,7 @@ public class GreatCircle { switch(coords.length) { case 1: array = Split.split(',',coords[0]); - if(array.length!=4)return -1; + if (array.length!=4)return -1; return calc( Double.parseDouble(array[0]), Double.parseDouble(array[1]), @@ -97,7 +97,7 @@ public class GreatCircle { case 2: array = Split.split(',',coords[0]); String [] array2 = Split.split(',',coords[1]); - if(array.length!=2 || array2.length!=2)return -1; + if (array.length!=2 || array2.length!=2)return -1; return calc( Double.parseDouble(array[0]), Double.parseDouble(array[1]), 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 7b61e398..0eae1198 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 @@ -107,7 +107,7 @@ public class JU_PropertyLocator { private int countItems(PropertyLocator pl) throws LocatorException { int count = 0; - for(Item i = pl.first(); i != null; i = pl.next(i)) { + for (Item i = pl.first(); i != null; i = pl.next(i)) { ++count; } return count; 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 142dde26..c4f3d504 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 @@ -100,7 +100,7 @@ public class AES implements Encryption { public CipherOutputStream outputStream(OutputStream os, boolean encrypt) { try { Cipher c = Cipher.getInstance(AES); - if(encrypt) { + if (encrypt) { c.init(Cipher.ENCRYPT_MODE,aeskeySpec); } else { c.init(Cipher.DECRYPT_MODE,aeskeySpec); @@ -116,7 +116,7 @@ public class AES implements Encryption { public CipherInputStream inputStream(InputStream is, boolean encrypt) { try { Cipher c = Cipher.getInstance(AES); - if(encrypt) { + if (encrypt) { c.init(Cipher.ENCRYPT_MODE,aeskeySpec); } else { c.init(Cipher.DECRYPT_MODE,aeskeySpec); 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 d9d4474d..e6d24dab 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 @@ -76,10 +76,10 @@ public abstract class AbsUserCache { userMap = new ConcurrentHashMap<>(); - if(cleanInterval>0) { + if (cleanInterval>0) { cleanInterval = Math.max(MIN_INTERVAL, cleanInterval); synchronized(AbsUserCache.class) { // Lazy instantiate.. in case there is no cleanup needed - if(timer==null) { + if (timer==null) { timer = new Timer("CADI Cleanup Timer",true); } @@ -96,14 +96,14 @@ public abstract class AbsUserCache { missEncrypt = cache.missEncrypt; synchronized(AbsUserCache.class) { - if(cache.clean!=null && cache.clean.lur==null && this instanceof CachingLur) { + 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; + if (clean!=null)clean.lur = lur; } @@ -111,11 +111,11 @@ public abstract class AbsUserCache { Principal p = user.principal; String key; try { - if(p instanceof GetCred) { + if (p instanceof GetCred) { key = missKey(p.getName(), ((GetCred)p).getCred()); } else { byte[] cred; - if((cred=user.getCred())==null) { + if ((cred=user.getCred())==null) { key = user.name + NO_CRED; } else { key = missKey(user.name,cred); @@ -152,7 +152,7 @@ public abstract class AbsUserCache { return false; } Miss miss = missMap.get(mkey); - if(miss==null) { + if (miss==null) { missMap.put(mkey, new Miss(bs,clean==null?MIN_INTERVAL:clean.timeInterval,key)); return true; } @@ -165,7 +165,7 @@ public abstract class AbsUserCache { protected User getUser(Principal principal) { String key; - if(principal instanceof GetCred) { + if (principal instanceof GetCred) { GetCred gc = (GetCred)principal; try { key = missKey(principal.getName(), gc.getCred()); @@ -177,7 +177,7 @@ public abstract class AbsUserCache { key = principal.getName()+NO_CRED; } User u = userMap.get(key); - if(u!=null) { + if (u!=null) { u.incCount(); } return u; @@ -197,8 +197,8 @@ public abstract class AbsUserCache { return null; } u = userMap.get(key); - if(u!=null) { - if(u.permExpired()) { + if (u!=null) { + if (u.permExpired()) { userMap.remove(key); u=null; } else { @@ -223,7 +223,7 @@ public abstract class AbsUserCache { */ public void remove(String user) { Object o = userMap.remove(user); - if(o!=null) { + if (o!=null) { access.log(Level.INFO, user,"removed from Client Cache by Request"); } } @@ -237,7 +237,7 @@ public abstract class AbsUserCache { public final List dumpInfo() { List rv = new ArrayList<>(); - for(User user : userMap.values()) { + for (User user : userMap.values()) { rv.add(new DumpInfo(user)); } return rv; @@ -256,7 +256,7 @@ public abstract class AbsUserCache { * If overloading in Derived class, be sure to call "super.destroy()" */ public void destroy() { - if(timer!=null) { + if (timer!=null) { timer.purge(); timer.cancel(); } @@ -318,13 +318,13 @@ public abstract class AbsUserCache { ArrayList> al = new ArrayList<>(userMap.values().size()); al.addAll(0, userMap.values()); long now = System.currentTimeMillis() + advance; - for(User user : al) { + for (User user : al) { ++total; - if(user.count>usageTriggerCount) { + if (user.count>usageTriggerCount) { boolean touched = false, removed=false; - if(user.principal instanceof CachedPrincipal) { + if (user.principal instanceof CachedPrincipal) { CachedPrincipal cp = (CachedPrincipal)user.principal; - if(cp.expires() < now) { + if (cp.expires() < now) { switch(cp.revalidate(null)) { case INACCESSIBLE: access.log(Level.AUDIT, "AAF Inaccessible. Keeping credentials"); @@ -343,20 +343,20 @@ public abstract class AbsUserCache { } } - if(!removed && lur!=null && user.permExpires<= now ) { - if(lur.reload(user).equals(Resp.REVALIDATED)) { + 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) { + if (touched) { ++renewed; } } else { - if(user.permExpired()) { + if (user.permExpired()) { remove(user); ++count; } @@ -366,14 +366,14 @@ public abstract class AbsUserCache { // Clean out Misses int missTotal = missMap.keySet().size(); int miss = 0; - if(missTotal>0) { + if (missTotal>0) { ArrayList keys = new ArrayList<>(missTotal); keys.addAll(missMap.keySet()); - for(String key : keys) { + for (String key : keys) { Miss m = missMap.get(key); - if(m!=null) { + if (m!=null) { long timeLeft = m.timestamp - System.currentTimeMillis(); - if(timeLeft<0) { + if (timeLeft<0) { synchronized(missMap) { missMap.remove(key); } @@ -386,14 +386,14 @@ public abstract class AbsUserCache { } } - if(count+renewed+miss>0) { + 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) { + if (total>high) { // advance cleanup by 10%, without getting greater than timeInterval. advance = Math.min(timeInterval, advance+(timeInterval/10)); } else { @@ -432,10 +432,10 @@ public abstract class AbsUserCache { public synchronized boolean mayContinue() { long ts = System.currentTimeMillis(); - if(ts>timestamp) { + if (ts>timestamp) { tries = 0; timestamp = ts + timetolive; - } else if(MAX_TRIES <= ++tries) { + } else if (MAX_TRIES <= ++tries) { return false; } return true; 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 76d9bb2a..a673ab4f 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 @@ -57,7 +57,7 @@ public interface Access { } public int toggle(int mask) { - if(inMask(mask)) { + if (inMask(mask)) { return delFromMask(mask); } else { return addToMask(mask); @@ -67,8 +67,8 @@ public interface Access { public int maskOf() { int mask=0; - for(Level l : values()) { - if(ordinal()<=l.ordinal() && l!=NONE) { + for (Level l : values()) { + if (ordinal()<=l.ordinal() && l!=NONE) { mask|=l.bit; } } 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 3f47351b..8202183d 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 @@ -63,19 +63,19 @@ public class BufferedServletInputStream extends ServletInputStream { public int read() throws IOException { int value=-1; - if(capacitor==null) { + if (capacitor==null) { value=is.read(); } else { switch(state) { case STORE: value = is.read(); - if(value>=0) { + if (value>=0) { capacitor.put((byte)value); } break; case READ: value = capacitor.read(); - if(value<0) { + if (value<0) { capacitor.done(); capacitor=null; // all done with buffer value = is.read(); @@ -92,27 +92,27 @@ public class BufferedServletInputStream extends ServletInputStream { public int read(byte[] b, int off, int len) throws IOException { int count = -1; - if(capacitor==null) { + if (capacitor==null) { count = is.read(b,off,len); } else { switch(state) { case STORE: count = is.read(b, off, len); - if(count>0) { + if (count>0) { capacitor.put(b, off, count); } break; case READ: count = capacitor.read(b, off, len); - if(count<=0) { + if (count<=0) { capacitor.done(); capacitor=null; // all done with buffer } - if(count0) { // watch for -1 + if (temp>0) { // watch for -1 count+=temp; - } else if(count<=0) { + } else if (count<=0) { count = temp; // must account for Stream coming back -1 } } @@ -124,7 +124,7 @@ public class BufferedServletInputStream extends ServletInputStream { public long skip(long n) throws IOException { long skipped = capacitor.skip(n); - if(skipped)lur).remove(id); } } 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 5ca1ce30..f3a2a7fa 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 @@ -46,7 +46,7 @@ public class Capacitor { public void put(byte b) { - if(curr == null || curr.remaining()==0) { // ensure we have a "curr" buffer ready for data + if (curr == null || curr.remaining()==0) { // ensure we have a "curr" buffer ready for data curr = ringGet(); bbs.add(curr); } @@ -54,10 +54,10 @@ public class Capacitor { } public int read() { - if(curr!=null) { - if(curr.remaining()>0) { // have a buffer, use it! + 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 + while (length>0) { // 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; @@ -87,7 +87,7 @@ public class Capacitor { count+=len; offset+=len; length-=len; - if(idx0) { - if((len=curr.remaining())>length) { + while (length>0) { + if ((len=curr.remaining())>length) { curr.put(array,offset,length); length=0; } else { @@ -130,10 +130,10 @@ public class Capacitor { * Move state from Storage mode into Read mode, changing all internal buffers to read mode, etc */ public void setForRead() { - for(ByteBuffer bb : bbs) { + for (ByteBuffer bb : bbs) { bb.flip(); } - if(bbs.isEmpty()) { + if (bbs.isEmpty()) { curr = null; idx = 0; } else { @@ -146,7 +146,7 @@ public class Capacitor { * reuse all the buffers */ public void done() { - for(ByteBuffer bb : bbs) { + for (ByteBuffer bb : bbs) { ringPut(bb); } bbs.clear(); @@ -160,7 +160,7 @@ public class Capacitor { */ public int available() { int count = 0; - for(ByteBuffer bb : bbs) { + for (ByteBuffer bb : bbs) { count+=bb.remaining(); } return count; @@ -174,11 +174,11 @@ public class Capacitor { public long skip(long n) { long skipped=0L; int skip; - if(curr==null) { + if (curr==null) { return 0; } - while(n>0) { - if(n<(skip=curr.remaining())) { + while (n>0) { + if (n<(skip=curr.remaining())) { curr.position(curr.position()+(int)n); skipped+=skip; n=0; @@ -186,7 +186,7 @@ public class Capacitor { curr.position(curr.limit()); skipped-=skip; - if(idx15)start=0; + if (bb!=null && ++start>15)start=0; } - if(bb==null) { + if (bb==null) { bb=ByteBuffer.allocate(DEFAULT_CHUNK); } else { bb.clear();// refresh reused buffer @@ -234,7 +234,7 @@ public class Capacitor { 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; + 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 7ca9fac2..68a8db05 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 @@ -48,18 +48,18 @@ public class CmdLine { * @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))) { + 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) { + if (args.length>2) { password = args[1]; keyfile = args[2]; - if("-i".equals(password)) { + if ("-i".equals(password)) { int c; StringBuilder sb = new StringBuilder(); try { - while((c=System.in.read())>=0) { + while ((c=System.in.read())>=0) { sb.append((char)c); } } catch (IOException e) { @@ -86,7 +86,7 @@ public class CmdLine { return; /* testing code... don't want it exposed System.out.println(" ******** Testing *********"); - for(int i=0;i<100000;++i) { + for (int i=0;i<100000;++i) { System.out.println(args[1]); ByteArrayOutputStream baos = new ByteArrayOutputStream(); b64.enpass(args[1], baos); @@ -96,7 +96,7 @@ public class CmdLine { b64.depass(pass, reconstituted); String r = reconstituted.toString(); System.out.println(r); - if(!r.equals(args[1])) { + if (!r.equals(args[1])) { System.err.println("!!!!! STOP - ERROR !!!!!"); return; } @@ -113,7 +113,7 @@ public class CmdLine { // 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) { + } else if ("regurgitate".equalsIgnoreCase(args[0]) && args.length>2) { try { Symm symm; FileInputStream fis = new FileInputStream(args[2]); @@ -123,10 +123,10 @@ public class CmdLine { fis.close(); } boolean isFile = false; - if("-i".equals(args[1]) || (isFile="-f".equals(args[1]))) { + if ("-i".equals(args[1]) || (isFile="-f".equals(args[1]))) { BufferedReader br; - if(isFile) { - if(args.length<4) { + if (isFile) { + if (args.length<4) { System.err.println("Filename in 4th position"); return; } @@ -139,10 +139,10 @@ public class CmdLine { boolean cont = false; StringBuffer sb = new StringBuffer(); JsonOutputStream jw = new JsonOutputStream(System.out); - while((line=br.readLine())!=null) { - if(cont) { + while ((line=br.readLine())!=null) { + if (cont) { int end; - if((end=line.indexOf('"'))>=0) { + if ((end=line.indexOf('"'))>=0) { sb.append(line,0,end); cont=false; } else { @@ -150,34 +150,34 @@ public class CmdLine { } } else { int idx; - if((idx = line.indexOf(' '))>=0 + 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) { + if ((end=line.indexOf('"',start))<0) { end = line.length(); cont = true; } sb.append(line,start,end); } } - if(sb.length()>0) { + if (sb.length()>0) { symm.depass(sb.toString(),jw); - if(!cont) { + if (!cont) { System.out.println(); } } System.out.flush(); sb.setLength(0); - if(!cont) { + if (!cont) { jw.resetIndent(); } } } finally { - if(isFile) { + if (isFile) { br.close(); } } @@ -191,7 +191,7 @@ public class CmdLine { System.err.println("Cannot regurgitate password"); System.err.println(" \""+ e.getMessage() + '"'); } - } else if("encode64".equalsIgnoreCase(args[0]) && args.length>1) { + } else if ("encode64".equalsIgnoreCase(args[0]) && args.length>1) { try { Symm.base64.encode(args[1], System.out); System.out.println(); @@ -201,7 +201,7 @@ public class CmdLine { System.err.println("Cannot encode Base64 with " + args[1]); System.err.println(" \""+ e.getMessage() + '"'); } - } else if("decode64".equalsIgnoreCase(args[0]) && args.length>1) { + } else if ("decode64".equalsIgnoreCase(args[0]) && args.length>1) { try { Symm.base64.decode(args[1], System.out); System.out.println(); @@ -211,7 +211,7 @@ public class CmdLine { System.err.println("Cannot decode Base64 text from " + args[1]); System.err.println(" \""+ e.getMessage() + '"'); } - } else if("encode64url".equalsIgnoreCase(args[0]) && args.length>1) { + } else if ("encode64url".equalsIgnoreCase(args[0]) && args.length>1) { try { Symm.base64url.encode(args[1], System.out); System.out.println(); @@ -221,7 +221,7 @@ public class CmdLine { System.err.println("Cannot encode Base64url with " + args[1]); System.err.println(" \""+ e.getMessage() + '"'); } - } else if("decode64url".equalsIgnoreCase(args[0]) && args.length>1) { + } else if ("decode64url".equalsIgnoreCase(args[0]) && args.length>1) { try { Symm.base64url.decode(args[1], System.out); System.out.println(); @@ -231,7 +231,7 @@ public class CmdLine { System.err.println("Cannot decode Base64url text from " + args[1]); System.err.println(" \""+ e.getMessage() + '"'); } - } else if("md5".equalsIgnoreCase(args[0]) && args.length>1) { + } else if ("md5".equalsIgnoreCase(args[0]) && args.length>1) { try { System.out.println(Hash.hashMD5asStringHex(args[1])); System.out.flush(); @@ -240,11 +240,11 @@ public class CmdLine { System.err.println(" \""+ e.getMessage() + '"'); } return; - } else if("sha256".equalsIgnoreCase(args[0]) && args.length>1) { + } else if ("sha256".equalsIgnoreCase(args[0]) && args.length>1) { try { - if(args.length>2) { + if (args.length>2) { int max = args.length>7?7:args.length; - for(int i=2;i1) { + if (args.length>1) { File f = new File(args[1]); FileOutputStream fos = new FileOutputStream(f); try { @@ -280,13 +280,13 @@ public class CmdLine { System.err.println(" \""+ e.getMessage() + '"'); } - } else if("passgen".equalsIgnoreCase(args[0])) { + } else if ("passgen".equalsIgnoreCase(args[0])) { int numDigits; - if(args.length <= 1) { + if (args.length <= 1) { numDigits = 24; } else { numDigits = Integer.parseInt(args[1]); - if(numDigits<8)numDigits = 8; + if (numDigits<8)numDigits = 8; } String pass; boolean noLower,noUpper,noDigits,noSpecial,repeatingChars,missingChars; @@ -295,33 +295,33 @@ public class CmdLine { missingChars=noLower=noUpper=noDigits=noSpecial=true; repeatingChars=false; int c=-1,last; - for(int i=0;i=0x61 && c<=0x7A); } - if(noUpper) { + if (noUpper) { noUpper=!(c>=0x41 && c<=0x5A); } - if(noDigits) { + if (noDigits) { noDigits=!(c>=0x30 && c<=0x39); } - if(noSpecial) { + if (noSpecial) { noSpecial = "+!@#$%^&*(){}[]?:;,.".indexOf(c)<0; } missingChars = (noLower || noUpper || noDigits || noSpecial); } - } while(missingChars || repeatingChars); + } while (missingChars || repeatingChars); System.out.println(pass.substring(0,numDigits)); - } else if("urlgen".equalsIgnoreCase(args[0])) { + } else if ("urlgen".equalsIgnoreCase(args[0])) { int numDigits; - if(args.length <= 1) { + if (args.length <= 1) { numDigits = 24; } else { numDigits = Integer.parseInt(args[1]); 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 acd45019..3027fd74 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 @@ -132,9 +132,9 @@ public class Hash { * @return */ public static boolean isEqual(byte ba1[], byte ba2[]) { - if(ba1.length!=ba2.length)return false; - for(int i = 0;i=0x30 && c<=0x39) { + if (c>=0x30 && c<=0x39) { b=(byte)(c-0x30); - } else if(c>=0x61 && c<=0x66) { + } else if (c>=0x61 && c<=0x66) { b=(byte)(c-0x57); // account for "A" - } else if(c>=0x41 && c<=0x46) { + } 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) { + if (high) { ba[idx]=(byte)(b<<4); high = false; } else { @@ -222,7 +222,7 @@ public class Hash { byte[] ba; boolean high; int start; - if(s.length()%2==0) { + if (s.length()%2==0) { ba = new byte[s.length()/2]; high=true; start=0; @@ -232,19 +232,19 @@ public class Hash { start=1; } int idx; - for(int i=start;i=0x30 && c<=0x39) { + if (c>=0x30 && c<=0x39) { b=(byte)(c-0x30); - } else if(c>=0x61 && c<=0x66) { + } else if (c>=0x61 && c<=0x66) { b=(byte)(c-0x57); // account for "A" - } else if(c>=0x41 && c<=0x46) { + } else if (c>=0x41 && c<=0x46) { b=(byte)(c-0x37); } else { return null; } idx = i/2; - if(high) { + if (high) { ba[idx]=(byte)(b<<4); high = false; } else { 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 a35777f8..8467c7c6 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 @@ -89,8 +89,8 @@ public class PropAccess implements Access { this.logIt = logIt; Properties nprops=new Properties(); int eq; - for(String arg : args) { - if((eq=arg.indexOf('='))>0) { + for (String arg : args) { + if ((eq=arg.indexOf('='))>0) { nprops.setProperty(arg.substring(0, eq),arg.substring(eq+1)); } } @@ -104,16 +104,16 @@ public class PropAccess implements Access { props = new Properties(); // First, load related System Properties - for(Entry es : System.getProperties().entrySet()) { + for (Entry es : System.getProperties().entrySet()) { String key = es.getKey().toString(); - for(String start : new String[] {"cadi_","aaf_","cm_"}) { - if(key.startsWith(start)) { + 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) { + if (p!=null) { props.putAll(p); } @@ -121,11 +121,11 @@ public class PropAccess implements Access { load(props.getProperty(Config.CADI_PROP_FILES)); String sLevel = props.getProperty(Config.CADI_LOGLEVEL); - if(sLevel!=null) { + if (sLevel!=null) { level=Level.valueOf(sLevel).maskOf(); } // Setup local Symmetrical key encryption - if(symm==null) { + if (symm==null) { try { symm = Symm.obtain(this); } catch (CadiException e) { @@ -142,18 +142,18 @@ public class PropAccess implements Access { 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) { + 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) { + 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")) + 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); } @@ -161,20 +161,20 @@ public class PropAccess implements Access { } private void load(String cadi_prop_files) { - if(cadi_prop_files==null) { + 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)) { + if (!recursionProtection.contains(chainProp)) { recursionProtection.add(chainProp); load(chainProp); // recurse } @@ -205,23 +205,23 @@ public class PropAccess implements Access { } // Trim - for(Entry es : props.entrySet()) { + for (Entry es : props.entrySet()) { Object value = es.getValue(); - if(value instanceof String) { + 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) { + if (l>0) { switch(s.charAt(l-1)) { case ' ': break; @@ -313,7 +313,7 @@ public class PropAccess implements Access { @Override public void printf(Level level, String fmt, Object... elements) { - if(willLog(level)) { + if (willLog(level)) { log(level,String.format(fmt, elements)); } } @@ -362,9 +362,9 @@ public class PropAccess implements Access { } public void setProperty(String tag, String value) { - if(value!=null) { + if (value!=null) { props.put(tag, value); - if(Config.CADI_KEYFILE.equals(tag)) { + if (Config.CADI_KEYFILE.equals(tag)) { // reset decryption too try { symm = Symm.obtain(this); 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 518ea6dd..998b87c9 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 @@ -34,7 +34,7 @@ public class ServletContextAccess extends PropAccess { super(filterConfig); // protected constructor... does not have "init" called. context = filterConfig.getServletContext(); - for(Enumeration en = filterConfig.getInitParameterNames();en.hasMoreElements();) { + for (Enumeration en = filterConfig.getInitParameterNames();en.hasMoreElements();) { String name = (String)en.nextElement(); setProperty(name, filterConfig.getInitParameter(name)); } @@ -46,7 +46,7 @@ public class ServletContextAccess extends PropAccess { */ @Override public void log(Level level, Object... elements) { - if(willLog(level)) { + if (willLog(level)) { StringBuilder sb = buildMsg(level, elements); context.log(sb.toString()); } 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 fd60b0c1..28af03cd 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 @@ -139,12 +139,12 @@ public class Symm { // 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) { + if (la.size()>codeset.length/3) { convert = new Unordered(codeset); } else { // too random to get speed enhancement from range algorithm int[][] range = new int[la.size()][]; @@ -210,10 +210,10 @@ public class Symm { public T exec(SyncExec exec) throws Exception { synchronized(LOCK) { - if(keyBytes == null) { + 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=0) { - if(line>=splitLinesAt) { + if (go = read>=0) { + if (line>=splitLinesAt) { os.write('\n'); line = 0; } @@ -362,7 +362,7 @@ public class Symm { // 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 + if (line==splitLinesAt) { // deal with line splitting for two characters os.write('\n'); line=0; } @@ -376,21 +376,21 @@ public class Symm { switch(idx) { case 1: // just the last 2 bits of prev os.write(codeset[(prev & 0x03)<<4]); - if(endEquals)os.write(DOUBLE_EQ); + 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('='); + if (endEquals)os.write('='); break; } idx = 0; } - } while(go); + } while (go); } public void decode(InputStream is, OutputStream os, int skip) throws IOException { - if(is.skip(skip)!=skip) { + if (is.skip(skip)!=skip) { throw new IOException("Error skipping on IOStream in Symm"); } decode(is,os); @@ -405,9 +405,9 @@ public class Symm { public void decode(InputStream is, OutputStream os) throws IOException { int read, idx=0; int prev=0, index; - while((read = is.read())>=0) { + while ((read = is.read())>=0) { index = convert.convert(read); - if(index>=0) { + if (index>=0) { switch(++idx) { // 1 based cases, slightly faster ++ case 1: // index goes into first 6 bits of prev prev = index<<2; @@ -459,8 +459,8 @@ public class Symm { case '\r': return -1; } - for(int i=0;i= range[i][0] && read<=range[i][1]) { + for (int i=0;i= range[i][0] && read<=range[i][1]) { return read-range[i][2]; } } @@ -487,8 +487,8 @@ public class Symm { case '\r': return -1; } - for(int i=0;i=0) { + while (filled>=0) { index = o.next(); - if(index<0 || index>=codeset.length) { + 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) { + for (int j=index;j>=0;--j) { + if (seq[j]==0) { seq[j]=codeset[filled]; --filled; break; @@ -859,7 +859,7 @@ public class Symm { 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 { } public void add(LocalPermission permission) { - if(perms==NULL_MAP) { + if (perms==NULL_MAP) { perms=newMap(); } perms.put(permission.getKey(),permission); @@ -157,8 +157,8 @@ public final class User { sb.append('|'); boolean first = true; synchronized(perms) { - for(Permission gp : perms.values()) { - if(first) { + for (Permission gp : perms.values()) { + if (first) { first = false; sb.append(':'); } else { 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 4784d1ee..088227ed 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 @@ -233,9 +233,9 @@ public class Config { ///////////////////////////////////////////////////// Class aafConClass = loadClass(access,CADI_AAF_CON_DEF); Object aafcon = null; - if(con!=null && aafConClass!=null && aafConClass.isAssignableFrom(con.getClass())) { + if (con!=null && aafConClass!=null && aafConClass.isAssignableFrom(con.getClass())) { aafcon = con; - } else if(lur != null) { + } else if (lur != null) { Field f; try { f = lur.getClass().getField("aaf"); @@ -248,14 +248,14 @@ public class Config { 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) { + 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) { + if (hostname==null) { try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e1) { @@ -279,10 +279,10 @@ public class Config { ///////////////////////////////////////////////////// X509Taf x509TAF = null; String truststore = logProp(access, CADI_TRUSTSTORE,null); - if(truststore!=null) { + if (truststore!=null) { String truststorePwd = access.getProperty(CADI_TRUSTSTORE_PASSWORD,null); - if(truststorePwd!=null) { - if(truststorePwd.startsWith(Symm.ENC)) { + if (truststorePwd!=null) { + if (truststorePwd.startsWith(Symm.ENC)) { try { access.decrypt(truststorePwd,false); } catch (IOException e) { @@ -314,17 +314,17 @@ public class Config { long userExp = Long.parseLong(aafCleanup); boolean basicWarn = "TRUE".equals(access.getProperty(BASIC_WARN,"FALSE")); - if(!hasDirectAAF) { + if (!hasDirectAAF) { HttpTaf aaftaf=null; - if(!hasOAuthDirectTAF) { - if(basicRealm!=null) { + if (!hasOAuthDirectTAF) { + if (basicRealm!=null) { @SuppressWarnings("unchecked") Class obasicCls = (Class)loadClass(access,CADI_OBASIC_HTTP_TAF_DEF); - if(obasicCls!=null) { + 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) { + 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); @@ -333,20 +333,20 @@ public class Config { } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { access.log(Level.INIT, e); } - } else if(up!=null) { + } 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) { + 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) { + for (Object o : additionalTafLurs) { + if (o instanceof CredValDomain) { bht.add((CredValDomain)o); } } - if(x509TAF!=null) { + if (x509TAF!=null) { x509TAF.add(bht); } htlist.add(bht); @@ -359,28 +359,28 @@ public class Config { ///////////////////////////////////////////////////// // Configure AAF Driven Basic Auth ///////////////////////////////////////////////////// - if(aafcon==null) { + if (aafcon==null) { access.log(Level.INIT,"AAF Connection (AAFcon) is null. Cannot create an AAF TAF"); - } else if(aafURL==null) { + } 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)) { + if (AAF_TAF_CLASS_DEF.equals(aafTafClassName)) { try { Class aafTafClass = loadClass(access,aafTafClassName); - if(aafTafClass!=null) { + if (aafTafClass!=null) { Constructor cstr = aafTafClass.getConstructor(Connector.class,boolean.class,AbsUserCache.class); - if(cstr!=null) { - if(lur instanceof AbsUserCache) { + 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) { + if (cstr!=null) { aaftaf = (HttpTaf)cstr.newInstance(aafcon,basicWarn); } } - if(aaftaf==null) { + if (aaftaf==null) { access.log(Level.INIT,"ERROR! AAF TAF Failed construction. NOT Configured"); } else { access.log(Level.INIT,"AAF TAF Configured to ",aafURL); @@ -390,7 +390,7 @@ public class Config { } else { access.log(Level.INIT, "There is no AAF TAF class available: %s. AAF TAF not configured.",aafTafClassName); } - } catch(Exception e) { + } catch (Exception e) { access.log(Level.INIT,"ERROR! AAF TAF Failed construction. NOT Configured",e); } } @@ -400,7 +400,7 @@ public class Config { ///////////////////////////////////////////////////// // Configure OAuth TAF ///////////////////////////////////////////////////// - if(!hasOAuthDirectTAF) { + if (!hasOAuthDirectTAF) { String oauthTokenUrl = logProp(access,Config.AAF_OAUTH2_TOKEN_URL,null); Class oadtClss; try { @@ -409,21 +409,21 @@ public class Config { oadtClss = null; access.log(Level.INIT, e1); } - if(additionalTafLurs!=null && additionalTafLurs.length>0 && (oadtClss!=null && additionalTafLurs[0].getClass().isAssignableFrom(oadtClss))) { + 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) { + 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) { + } 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) { + if (oaTCls!=null) { Class oaTTmgrCls = loadClass(access, OAUTH_TOKEN_MGR); - if(oaTTmgrCls!=null) { + 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); @@ -444,7 +444,7 @@ public class Config { // Adding BasicAuth (AAF) last, after other primary Cookie Based // Needs to be before Cert... see below ///////////////////////////////////////////////////// - if(aaftaf!=null) { + if (aaftaf!=null) { htlist.add(aaftaf); } } @@ -452,22 +452,22 @@ public class Config { ///////////////////////////////////////////////////// // Any Additional Lurs passed in Constructor ///////////////////////////////////////////////////// - if(additionalTafLurs!=null) { - for(Object additional : additionalTafLurs) { - if(additional instanceof BasicHttpTaf) { + if (additionalTafLurs!=null) { + for (Object additional : additionalTafLurs) { + if (additional instanceof BasicHttpTaf) { BasicHttpTaf ht = (BasicHttpTaf)additional; - for(Object cv : additionalTafLurs) { - if(cv instanceof CredValDomain) { + 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) { + } 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) { + } else if (hasOAuthDirectTAF) { Class daupCls; try { daupCls = Class.forName("org.onap.aaf.auth.direct.DirectAAFUserPass"); @@ -475,7 +475,7 @@ public class Config { daupCls = null; access.log(Level.INIT, e); } - if(daupCls != null && additional.getClass().isAssignableFrom(daupCls)) { + 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()); } @@ -484,9 +484,9 @@ public class Config { } // Add BasicAuth, if any, to x509Taf - if(x509TAF!=null) { - for( HttpTaf ht : htlist) { - if(ht instanceof BasicHttpTaf) { + if (x509TAF!=null) { + for ( HttpTaf ht : htlist) { + if (ht instanceof BasicHttpTaf) { x509TAF.add((BasicHttpTaf)ht); } } @@ -494,7 +494,7 @@ public class Config { ///////////////////////////////////////////////////// // Create EpiTaf from configured TAFs ///////////////////////////////////////////////////// - if(htlist.size()==1) { + if (htlist.size()==1) { // just return the one taf = htlist.get(0); } else { @@ -504,7 +504,7 @@ public class Config { taf = new HttpEpiTaf(access,locator, tc, htarray); // ok to pass locator == null String level = logProp(access, CADI_LOGLEVEL, null); - if(level!=null) { + if (level!=null) { access.setLogLevel(Level.valueOf(level)); } } @@ -514,7 +514,7 @@ public class Config { public static String logProp(Access access,String tag, String def) { String rv = access.getProperty(tag, def); - if(rv == null) { + if (rv == null) { access.log(Level.INIT,tag,"is not explicitly set"); } else { access.log(Level.INIT,tag,"is set to",rv); @@ -533,14 +533,14 @@ public class Config { String users = access.getProperty(USERS,null); String groups = access.getProperty(GROUPS,null); - if(groups!=null || users!=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) { + if (writeto!=null) { String msg = UsersDump.updateUsers(writeto, ll); - if(msg!=null) { + if (msg!=null) { access.log(Level.INIT,"ERROR! Error Updating ",writeto,"with roles and users:",msg); } } @@ -554,10 +554,10 @@ public class Config { ///////////////////////////////////////////////////// String tokenUrl = logProp(access,AAF_OAUTH2_TOKEN_URL, null); String introspectUrl = logProp(access,AAF_OAUTH2_INTROSPECT_URL, null); - if(tokenUrl!=null && introspectUrl !=null) { + if (tokenUrl!=null && introspectUrl !=null) { try { Class olurCls = loadClass(access, CADI_OLUR_CLASS_DEF); - if(olurCls!=null) { + if (olurCls!=null) { Constructor olurCnst = olurCls.getConstructor(PropAccess.class,String.class,String.class); Lur olur = (Lur)olurCnst.newInstance(access,tokenUrl,introspectUrl); lurs.add(olur); @@ -567,7 +567,7 @@ public class Config { } } catch (NoSuchMethodException| SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { String msg = e.getMessage(); - if(msg==null && e.getCause()!=null) { + if (msg==null && e.getCause()!=null) { msg = e.getCause().getMessage(); } access.log(Level.INIT,"AAF/OAuth LUR is not instantiated.",msg,e); @@ -576,7 +576,7 @@ public class Config { access.log(Level.INIT, "OAuth2 Lur disabled"); } - if(con!=null) { // try to reutilize connector + if (con!=null) { // try to reutilize connector lurs.add(con.newLur()); } else { ///////////////////////////////////////////////////// @@ -584,12 +584,12 @@ public class Config { ///////////////////////////////////////////////////// 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 + if (aafEnv == null && aafURL!=null && access instanceof PropAccess) { // set AAF_ENV from AAF_URL int ec = aafURL.indexOf("envContext="); - if(ec>0) { + if (ec>0) { ec += 11; // length of envContext= int slash = aafURL.indexOf('/', ec); - if(slash>0) { + 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); @@ -598,30 +598,30 @@ public class Config { } // Don't configure AAF if it is using DirectAccess - if(!hasDirect("DirectAAFLur",additionalTafLurs)) { - if(aafURL==null) { + 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)) { + if (aafLurClassStr!=null && aafLurClassStr.startsWith(AAF_V2_0)) { try { Object aafcon = loadAAFConnector(si, aafURL); - if(aafcon==null) { + 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) { + if (aafAbsAAFCon!=null) { Method mNewLur = aafAbsAAFCon.getMethod("newLur"); Object aaflur = mNewLur.invoke(aafcon); - if(aaflur==null) { + 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) { + if (debugIDs !=null && aaflur instanceof CachingLur) { ((CachingLur)aaflur).setDebug(debugIDs); } } @@ -638,9 +638,9 @@ public class Config { ///////////////////////////////////////////////////// // Any Additional passed in Constructor ///////////////////////////////////////////////////// - if(additionalTafLurs!=null) { - for(Object additional : additionalTafLurs) { - if(additional instanceof Lur) { + if (additionalTafLurs!=null) { + for (Object additional : additionalTafLurs) { + if (additional instanceof Lur) { lurs.add((Lur)additional); access.log(Level.INIT, additional); } @@ -666,9 +666,9 @@ public class Config { } private static boolean hasDirect(String simpleClassName, Object[] additionalTafLurs) { - if(additionalTafLurs!=null) { - for(Object tf : additionalTafLurs) { - if(tf.getClass().getSimpleName().equals(simpleClassName)) { + if (additionalTafLurs!=null) { + for (Object tf : additionalTafLurs) { + if (tf.getClass().getSimpleName().equals(simpleClassName)) { return true; } } @@ -746,15 +746,15 @@ public class Config { public static Locator loadLocator(SecurityInfoC si, final String _url) throws LocatorException { Access access = si.access; Locator locator = null; - if(_url==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)) { + 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")) { + if (!replacement.endsWith("/locate")) { sb.append("/locate"); } sb.append(_url,idxAAFLocateUrl+AAF_LOCATE_URL_TAG.length(),_url.length()); @@ -763,7 +763,7 @@ public class Config { try { Class lcls = loadClass(access,AAF_LOCATOR_CLASS_DEF); - if(lcls==null) { + if (lcls==null) { throw new CadiException("Need to include aaf-cadi-aaf jar for AAFLocator"); } // First check for preloaded @@ -773,7 +773,7 @@ public class Config { } catch (Exception e) { access.log(Level.INIT, e); } - if(locator==null) { + if (locator==null) { URI locatorURI = new URI(url); Constructor cnst = lcls.getConstructor(SecurityInfoC.class,URI.class); locator = (Locator)cnst.newInstance(new Object[] {si,locatorURI}); @@ -785,7 +785,7 @@ public class Config { access.log(Level.INFO, "AAFLocator enabled using preloaded " + locator.getClass().getSimpleName()); } } catch (InvocationTargetException e) { - if(e.getTargetException() instanceof LocatorException) { + if (e.getTargetException() instanceof LocatorException) { throw (LocatorException)e.getTargetException(); } access.log(Level.INIT,e.getTargetException().getMessage(),"AAFLocator for",url,"could not be created.",e); 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 56ac4dd5..b48dd74d 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 @@ -59,7 +59,7 @@ public interface Get { } // Take def if nothing else - if(str==null) { + if (str==null) { str = def; // don't log defaults } else { @@ -83,8 +83,8 @@ public interface Get { } public String get(String name, String def, boolean print) { String gotten = access.getProperty(name, def); - if(print) { - if(gotten == null) { + if (print) { + if (gotten == null) { access.log(Level.INIT,name, "is not set"); } else { access.log(Level.INIT,name, "is set to", 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 4655dfa1..30adcc97 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 @@ -38,7 +38,7 @@ public class GetAccess extends PropAccess { public String getProperty(String tag, String def) { String rv; rv = super.getProperty(tag, null); - if(rv==null && getter!=null) { + if (rv==null && getter!=null) { rv = getter.get(tag, null, true); } return rv==null?def:rv; diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/config/MultiGet.java b/cadi/core/src/main/java/org/onap/aaf/cadi/config/MultiGet.java index a73df14e..c5e5a50e 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/config/MultiGet.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/config/MultiGet.java @@ -31,9 +31,9 @@ public class MultiGet implements Get { @Override public String get(String name, String def, boolean print) { String str; - for(Get getter : getters) { + for (Get getter : getters) { str = getter.get(name, null, print); - if(str!=null) + if (str!=null) return str; } return def; 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 45e1dd1c..4e365fba 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 @@ -44,7 +44,7 @@ public class SecurityInfoC extends SecurityInfo { @SuppressWarnings("unchecked") public static synchronized SecurityInfoC instance(Access access, Class cls) throws CadiException { SecurityInfoInit sii; - if(cls.isAssignableFrom(HttpURLConnection.class)) { + if (cls.isAssignableFrom(HttpURLConnection.class)) { try { @SuppressWarnings("rawtypes") Class initCls = (Class)Class.forName("org.onap.aaf.cadi.http.HSecurityInfoInit"); @@ -62,7 +62,7 @@ public class SecurityInfoC extends SecurityInfo { } SecurityInfoC sic = (SecurityInfoC) sicMap.get(cls); - if(sic==null) { + if (sic==null) { sic = new SecurityInfoC(access); sic.set(sii.bestDefault(sic)); sicMap.put(cls, sic); 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 de25cb7f..98ab4706 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 @@ -41,7 +41,7 @@ public class UsersDump { */ public static boolean write(OutputStream os, AbsUserCache lur) { PrintStream ps; - if(os instanceof PrintStream) { + if (os instanceof PrintStream) { ps = (PrintStream)os; } else { ps = new PrintStream(os); @@ -59,14 +59,14 @@ public class UsersDump { // Obtain all unique role names HashSet groups = new HashSet<>(); - for(AbsUserCache.DumpInfo di : lur.dumpInfo()) { + for (AbsUserCache.DumpInfo di : lur.dumpInfo()) { sb.append("\n "); @@ -104,15 +104,15 @@ public class UsersDump { */ public static String updateUsers(String writeto, LocalLur up) { // Dump a Tomcat-user.xml lookalike (anywhere) - if(writeto!=null) { + if (writeto!=null) { // First read content ByteArrayOutputStream baos = new ByteArrayOutputStream(); - if(UsersDump.write(baos, up)) { + if (UsersDump.write(baos, up)) { byte[] postulate = baos.toByteArray(); // now get contents of file File file = new File(writeto); boolean writeIt; - if(file.exists()) { + if (file.exists()) { try { FileInputStream fis = new FileInputStream(file); byte[] orig = new byte[(int)file.length()]; @@ -122,17 +122,17 @@ public class UsersDump { } finally { fis.close(); } - if(read<=0) { + if (read<=0) { writeIt = false; } else { // Starting at third "<" ( line) int startA=0, startB=0; - for(int i=0;startA ctc = (Class) Class.forName("org.onap.aaf.cadi.aaf.v2_0.AAFTrustChecker"); - if(ctc!=null) { + if (ctc!=null) { Constructor contc = ctc.getConstructor(Access.class); - if(contc!=null) { + if (contc!=null) { tc = contc.newInstance(access); } } @@ -184,8 +184,8 @@ public class CadiFilter implements Filter { // 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) { + if (httpChecker == null) { + if (access==null) { access = new PropAccess(); } try { @@ -193,16 +193,16 @@ public class CadiFilter implements Filter { } catch (CadiException | LocatorException e1) { throw new ServletException(e1); } - } else if(access==null) { + } else if (access==null) { access= httpChecker.getAccess(); } /* * Setup Authn Path Exceptions */ - if(pathExceptions==null) { + if (pathExceptions==null) { String str = getter.get(Config.CADI_NOAUTHN, null, true); - if(str!=null) { + if (str!=null) { pathExceptions = str.split("\\s*:\\s*"); } } @@ -210,22 +210,22 @@ public class CadiFilter implements Filter { /* * SETUP Permission Converters... those that can take Strings from a Vendor Product, and convert to appropriate AAF Permissions */ - if(mapPairs==null) { + if (mapPairs==null) { String str = getter.get(Config.AAF_PERM_MAP, null, true); - if(str!=null) { + if (str!=null) { String mstr = getter.get(Config.AAF_PERM_MAP, null, true); - if(mstr!=null) { + if (mstr!=null) { String map[] = mstr.split("\\s*:\\s*"); - if(map.length>0) { + 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 + 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) { + 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"); @@ -248,7 +248,7 @@ public class CadiFilter implements Filter { public void destroy() { // Synchronize, in case multiCadiFilters are used. synchronized(CadiHTTPManip.noAdditional) { - if(--count<=0 && httpChecker!=null) { + if (--count<=0 && httpChecker!=null) { httpChecker.destroy(); httpChecker=null; access=null; @@ -272,7 +272,7 @@ public class CadiFilter implements Filter { String tag = ""; try { HttpServletRequest hreq = (HttpServletRequest)request; - if(noAuthn(hreq)) { + if (noAuthn(hreq)) { startCode=System.nanoTime(); chain.doFilter(request, response); code = Timing.millis(startCode); @@ -281,11 +281,11 @@ public class CadiFilter implements Filter { startValidate=System.nanoTime(); TafResp tresp = httpChecker.validate(hreq, hresp, hreq); validate = Timing.millis(startValidate); - if(tresp.isAuthenticated()==RESP.IS_AUTHENTICATED) { + 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)) { + if (httpChecker.notCadi(cw, hresp)) { startCode=System.nanoTime(); oauthFilter.doFilter(cw,response,chain); code = Timing.millis(startCode); @@ -308,11 +308,11 @@ public class CadiFilter implements Filter { * @return */ private boolean noAuthn(HttpServletRequest hreq) { - if(pathExceptions!=null) { + 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; + if (pi==null) return false; // JBoss sometimes leaves null + for (String pe : pathExceptions) { + if (pi.startsWith(pe))return true; } } return false; @@ -322,11 +322,11 @@ public class CadiFilter implements Filter { * Get Converter by Path */ private PermConverter getConverter(HttpServletRequest hreq) { - if(mapPairs!=null) { + if (mapPairs!=null) { String pi = hreq.getPathInfo(); - if(pi !=null) { - for(Pair p: mapPairs) { - if(pi.startsWith(p.name))return p.pc; + if (pi !=null) { + for (Pair p: mapPairs) { + if (pi.startsWith(p.name))return p.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 3c0f139b..bab758ec 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 @@ -78,18 +78,18 @@ public class CadiHTTPManip { Config.setDefaultRealm(access); aaf_id = access.getProperty(Config.CADI_ALIAS,access.getProperty(Config.AAF_APPID, null)); - if(aaf_id==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) { + if (ns!=null) { thisPerm = ns+ACCESS_CADI_CONTROL; int dot = ns.indexOf('.'); - if(dot>=0) { + if (dot>=0) { int dot2=ns.indexOf('.',dot+1); - if(dot2<0) { + if (dot2<0) { dot2=dot; } companyPerm = ns.substring(0, dot2)+ACCESS_CADI_CONTROL; @@ -105,9 +105,9 @@ public class CadiHTTPManip { lur = Config.configLur(si, con, additionalTafLurs); tc.setLur(lur); - if(lur instanceof EpiLur) { + if (lur instanceof EpiLur) { up = ((EpiLur)lur).getUserPassImpl(); - } else if(lur instanceof CredVal) { + } else if (lur instanceof CredVal) { up = (CredVal)lur; } else { up = null; @@ -160,20 +160,20 @@ public class CadiHTTPManip { 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)) { + 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)) { + if (pathInfo.contains(CADI_CACHE_PRINT)) { resp.getOutputStream().println(lur.toString()); resp.setStatus(200); return false; - } else if(pathInfo.contains(CADI_CACHE_CLEAR)) { + } 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)) { + } else if (pathInfo.contains(CADI_LOG_SET)) { Level l; int slash = pathInfo.lastIndexOf('/'); String level = pathInfo.substring(slash+1); @@ -200,7 +200,7 @@ public class CadiHTTPManip { public void destroy() { access.log(Level.INFO,"CadiHttpChecker destroyed."); - if(lur!=null) { + if (lur!=null) { lur.destroy(); lur=null; } 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 f56cbf27..cf7c922d 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 @@ -49,25 +49,25 @@ class FCGet implements Get { public String get(String name, String def, boolean print) { String str = null; // Try Server Context First - if(context!=null) { + if (context!=null) { str = context.getInitParameter(name); } // Try Filter Context next - if(str==null && filterConfig != null) { + if (str==null && filterConfig != null) { str = filterConfig.getInitParameter(name); } - if(str==null) { + if (str==null) { str = access.getProperty(name, def); } // Take def if nothing else - if(str==null) { + 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) { + if (print) { access.log(Level.INFO,"Setting", name, "to", str); } } 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 c1b477b1..a41c5eb7 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 @@ -57,10 +57,10 @@ public class ConfigPrincipal implements Principal, GetCred { } public String getAsBasicAuthHeader() throws IOException { - if(content ==null) { + 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 + } else if (!content.startsWith("Basic ")) { // content is the saved password from construction String s = name + ':' + content; content = "Basic " + Symm.base64.encode(s); } 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 2c5e1957..5443dec2 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 @@ -57,30 +57,30 @@ public final class EpiLur implements Lur { */ public EpiLur(Lur ... lurs) throws CadiException{ this.lurs = lurs; - if(lurs.length==0) throw new CadiException("Need at least one Lur implementation in constructor"); + 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) { + if (pond==null) { return false; } boolean rv = false; Lur lur; - for(int i=0;!rv && i permissions) { - for(Lur lur : lurs) { + for (Lur lur : lurs) { lur.fishAll(bait, permissions); } } public void destroy() { - for(Lur lur : lurs) { + for (Lur lur : lurs) { lur.destroy(); } } @@ -90,8 +90,8 @@ public final class EpiLur implements Lur { * @return */ public CredVal getUserPassImpl() { - for(Lur lur : lurs) { - if(lur instanceof CredVal) { + for (Lur lur : lurs) { + if (lur instanceof CredVal) { return (CredVal)lur; } } @@ -109,15 +109,15 @@ public final class EpiLur implements Lur { * @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)) { + for (Lur l : lurs) { + if (l.getClass().isAssignableFrom(cls)) { return l; } } @@ -151,14 +151,14 @@ public final class EpiLur implements Lur { */ @Override public void clear(Principal p, StringBuilder report) { - for(Lur lur : lurs) { + for (Lur lur : lurs) { lur.clear(p, report); } } public String toString() { StringBuilder sb = new StringBuilder(); - for(Lur lur : lurs) { + for (Lur lur : lurs) { sb.append(lur.getClass().getSimpleName()); sb.append(": Report\n"); sb.append(lur.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 d2b6f1aa..f8fa02e5 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 @@ -98,7 +98,7 @@ public final class LocalLur extends AbsUserCache implements Lur if (pond == null) { return false; } - for(Permission p : pond) { + for (Permission p : pond) { if (handles(bait) && p instanceof LocalPermission) { // local Users only have LocalPermissions User user = getUser(bait); if (user != null) { @@ -134,7 +134,7 @@ public final class LocalLur extends AbsUserCache implements Lur public boolean handlesExclusively(Permission ... pond) { boolean rv = false; for (Permission p : pond) { - if(rv=supportingGroups.contains(p.getKey())) { + if (rv=supportingGroups.contains(p.getKey())) { break; } } 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 d3c1e236..746e67d8 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 @@ -45,8 +45,8 @@ public class BasicPrincipal extends BearerPrincipal implements GetCred { created = System.currentTimeMillis(); ByteArrayInputStream bis = new ByteArrayInputStream(content.getBytes()); // Read past "Basic ", ensuring it starts with it. - for(int i=0;i0) { + if ((at=name.indexOf('@'))>0) { domain=name.substring(at+1); shortName=name.substring(0, at); } else { @@ -83,7 +83,7 @@ public class BasicPrincipal extends BearerPrincipal implements GetCred { @Override public void write(int b) throws IOException { - if(b==':' && first) { + if (b==':' && first) { first = false; name = new String(baos.toByteArray()); baos.reset(); // 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 f81e160d..4a6e4cda 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 @@ -54,7 +54,7 @@ public class CachedBasicPrincipal extends BasicPrincipal implements CachedPrinci public CachedPrincipal.Resp revalidate(Object state) { Resp resp = creator.revalidate(this, state); - if(resp.equals(Resp.REVALIDATED))expires = System.currentTimeMillis()+timeToLive; + if (resp.equals(Resp.REVALIDATED))expires = System.currentTimeMillis()+timeToLive; return resp; } 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 8c75701f..20f22846 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 @@ -33,19 +33,19 @@ public class Kind { public static char getKind(final Principal principal) { Principal check; - if(principal instanceof TrustPrincipal) { + if (principal instanceof TrustPrincipal) { check = ((TrustPrincipal)principal).original(); } else { check = principal; } - if(check instanceof X509Principal) { + if (check instanceof X509Principal) { return X509; } - if(check instanceof OAuth2FormPrincipal) { + if (check instanceof OAuth2FormPrincipal) { // Note: if AAF, will turn into 'A' return OAUTH; } - if(check instanceof BasicPrincipal) { + 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 4d13de87..01326054 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 @@ -49,7 +49,7 @@ public class OAuth2FormPrincipal extends TaggedPrincipal { @Override public String personalName() { - if(username!=null && username!=client_id) { + if (username!=null && username!=client_id) { StringBuilder sb = new StringBuilder(); sb.append(username); sb.append('|'); 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 9dddcd63..7bb4ff52 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 @@ -47,7 +47,7 @@ public abstract class TaggedPrincipal implements Principal { } public String personalName() { - if(tagLookup == null) { + if (tagLookup == null) { return getName(); } try { 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 5d4a0586..7e92aaca 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 @@ -33,10 +33,10 @@ public class TrustPrincipal extends BearerPrincipal implements UserChain { public TrustPrincipal(final Principal actual, final String asName) { this.original = actual; name = asName.trim(); - if(actual instanceof UserChain) { + if (actual instanceof UserChain) { UserChain uc = (UserChain)actual; userChain = uc.userChain(); - } else if(actual instanceof TaggedPrincipal) { + } else if (actual instanceof TaggedPrincipal) { userChain=((TaggedPrincipal)actual).tag(); } else { userChain = actual.getClass().getSimpleName(); 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 1cd114a0..0348cd1f 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 @@ -55,17 +55,17 @@ public class X509Principal extends BearerPrincipal implements GetCred { String _name = null; String subj = cert.getSubjectDN().getName(); int cn = subj.indexOf("OU="); - if(cn>=0) { + if (cn>=0) { cn+=3; int space = subj.indexOf(',',cn); - if(space>=0) { + if (space>=0) { String id = subj.substring(cn, space); - if(pattern.matcher(id).matches()) { + if (pattern.matcher(id).matches()) { _name = id; } } } - if(_name==null) { + if (_name==null) { throw new IOException("X509 does not have Identity as CN"); } name = _name; @@ -74,7 +74,7 @@ public class X509Principal extends BearerPrincipal implements GetCred { public String getAsHeader() throws IOException { try { - if(content==null) { + if (content==null) { content=cert.getEncoded(); } } catch (CertificateEncodingException e) { 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 b248e553..d2cbf3fa 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 @@ -47,7 +47,7 @@ public class EpiTaf implements Taf { */ public EpiTaf(Taf ... tafs) throws CadiException{ this.tafs = tafs; - if(tafs.length==0) throw new CadiException("Need at least one Taf implementation in constructor"); + if (tafs.length==0) throw new CadiException("Need at least one Taf implementation in constructor"); } /** @@ -63,13 +63,13 @@ public class EpiTaf implements Taf { */ public TafResp validate(LifeForm reading, String... info) { TafResp tresp,firstTryAuth=null; - for(Taf taf : tafs) { + 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; + if (firstTryAuth==null)firstTryAuth=tresp; break; default: return tresp; 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 b0f56603..6334164e 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 @@ -94,7 +94,7 @@ public class HttpEpiTaf implements HttpTaf { TafResp firstTry = null; List redirectables = null; List log; - if(access.willLog(Level.DEBUG)) { + if (access.willLog(Level.DEBUG)) { log = new ArrayList<>(); } else { log = null; 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 21830b01..d5f6b032 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 @@ -85,23 +85,23 @@ public class BasicHttpTaf implements HttpTaf { */ 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) { + 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) { + 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) { + 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)) { + 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 @@ -112,25 +112,25 @@ public class BasicHttpTaf implements HttpTaf { } // Get User/Password from Authorization Header value String authz = req.getHeader("Authorization"); - if(authz != null && authz.startsWith("Basic ")) { - if(warn&&!req.isSecure()) { + 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) { + 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) { + 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)) { + 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 @@ -148,7 +148,7 @@ public class BasicHttpTaf implements HttpTaf { protected String buildMsg(Principal pr, HttpServletRequest req, Object ... msg) { StringBuilder sb = new StringBuilder(); - if(pr!=null) { + if (pr!=null) { sb.append("user="); sb.append(pr.getName()); sb.append(','); @@ -157,9 +157,9 @@ public class BasicHttpTaf implements HttpTaf { sb.append(req.getRemoteAddr()); sb.append(",port="); sb.append(req.getRemotePort()); - if(msg.length>0) { + if (msg.length>0) { sb.append(",msg=\""); - for(Object s : msg) { + for (Object s : msg) { sb.append(s.toString()); } sb.append('"'); @@ -173,7 +173,7 @@ public class BasicHttpTaf implements HttpTaf { public CredVal getCredVal(String key) { CredVal cv = rbacs.get(key); - if(cv==null) { + if (cv==null) { cv = rbac; } return cv; @@ -181,9 +181,9 @@ public class BasicHttpTaf implements HttpTaf { @Override public Resp revalidate(CachedPrincipal prin, Object state) { - if(prin instanceof BasicPrincipal) { + if (prin instanceof BasicPrincipal) { BasicPrincipal ba = (BasicPrincipal)prin; - if(DenialOfServiceTaf.isDeniedID(ba.getName())!=null) { + if (DenialOfServiceTaf.isDeniedID(ba.getName())!=null) { return Resp.UNVALIDATED; } return rbac.validate(ba.getName(), Type.PASSWORD, ba.getCred(), state)?Resp.REVALIDATED:Resp.UNVALIDATED; 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 d0034c76..0f252e39 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 @@ -81,18 +81,18 @@ public class X509Taf implements HttpTaf { 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) { + 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(":")) { + 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) { + if (dci==null) { certIdents = cis; } else { CertIdentity temp[] = new CertIdentity[cis.length+1]; @@ -129,28 +129,28 @@ public class X509Taf implements HttpTaf { // Check for Mutual SSL try { X509Certificate[] certarr = (X509Certificate[])req.getAttribute("javax.servlet.request.X509Certificate"); - if(certarr!=null && certarr.length>0) { + 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)) { + 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) { + if (at>=0) { int start = subject.lastIndexOf(',', at); - if(start<0) { + if (start<0) { start = 0; } int end = subject.indexOf(',', at); - if(end<0) { + if (end<0) { end=subject.length(); } int temp; - if(((temp=subject.indexOf("OU=",start))>=0 && temp=0 && temp=0 && temp1 && env!=null && env.equals(sa[1]))) { // Check Environment + if (sa.length==1 || (sa.length>1 && 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); @@ -168,10 +168,10 @@ public class X509Taf implements HttpTaf { 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 + 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); } } @@ -179,9 +179,9 @@ public class X509Taf implements HttpTaf { 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 ")) { + if (authHeader != null) { + for (String auth : Split.splitTrim(',',authHeader)) { + if (auth.startsWith("x509 ")) { ByteArrayOutputStream baos = new ByteArrayOutputStream(auth.length()); try { array = auth.getBytes(); @@ -197,10 +197,10 @@ public class X509Taf implements HttpTaf { // cert.checkValidity(); // cert.--- GET FINGERPRINT? String stuff = req.getHeader("Signature"); - if(stuff==null) + 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) + // 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 " " @@ -215,7 +215,7 @@ public class X509Taf implements HttpTaf { Signature sig = Signature.getInstance(cert.getSigAlgName()); sig.initVerify(cert.getPublicKey()); sig.update(data.getBytes()); - if(!sig.verify(array)) { + 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); } @@ -227,21 +227,21 @@ public class X509Taf implements HttpTaf { } } } - if(cert==null) { + 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.put(ip, new Counter(ip)); // Noted duplicated for minimum time spent rv= true; - } else if(deniedIP.get(ip)==null) { + } else if (deniedIP.get(ip)==null) { deniedIP.put(ip, new Counter(ip)); rv = true; } - if(rv) { + if (rv) { writeIP(); } return rv; } private static void writeIP() { - if(dosIP!=null && deniedIP!=null) { - if(deniedIP.isEmpty()) { - if(dosIP.exists()) { + if (dosIP!=null && deniedIP!=null) { + if (deniedIP.isEmpty()) { + if (dosIP.exists()) { dosIP.delete(); } } else { @@ -150,7 +150,7 @@ public class DenialOfServiceTaf implements HttpTaf { try { fos = new PrintStream(new FileOutputStream(dosIP,false)); try { - for(String ip: deniedIP.keySet()) { + for (String ip: deniedIP.keySet()) { fos.println(ip); } } finally { @@ -164,17 +164,17 @@ public class DenialOfServiceTaf implements HttpTaf { } private static void readIP() { - if(dosIP!=null && dosIP.exists()) { + if (dosIP!=null && dosIP.exists()) { BufferedReader br; try { br = new BufferedReader(new FileReader(dosIP)); try { - if(deniedIP==null) { + if (deniedIP==null) { deniedIP=new HashMap<>(); } String line; - while((line=br.readLine())!=null) { + while ((line=br.readLine())!=null) { deniedIP.put(line, new Counter(line)); } } finally { @@ -195,9 +195,9 @@ public class DenialOfServiceTaf implements HttpTaf { * @return */ public static synchronized boolean removeDenyIP(String ip) { - if(deniedIP!=null && deniedIP.remove(ip)!=null) { + if (deniedIP!=null && deniedIP.remove(ip)!=null) { writeIP(); - if(deniedIP.isEmpty()) { + if (deniedIP.isEmpty()) { deniedIP=null; } return true; @@ -214,15 +214,15 @@ public class DenialOfServiceTaf implements HttpTaf { */ public static synchronized boolean denyID(String id) { boolean rv = false; - if(deniedID==null) { + 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) { + } else if (deniedID.get(id)==null) { deniedID.put(id, new Counter(id)); rv = true; } - if(rv) { + if (rv) { writeID(); } return rv; @@ -230,9 +230,9 @@ public class DenialOfServiceTaf implements HttpTaf { } private static void writeID() { - if(dosID!=null && deniedID!=null) { - if(deniedID.isEmpty()) { - if(dosID.exists()) { + if (dosID!=null && deniedID!=null) { + if (deniedID.isEmpty()) { + if (dosID.exists()) { dosID.delete(); } } else { @@ -240,7 +240,7 @@ public class DenialOfServiceTaf implements HttpTaf { try { fos = new PrintStream(new FileOutputStream(dosID,false)); try { - for(String ip: deniedID.keySet()) { + for (String ip: deniedID.keySet()) { fos.println(ip); } } finally { @@ -254,17 +254,17 @@ public class DenialOfServiceTaf implements HttpTaf { } private static void readID() { - if(dosID!=null && dosID.exists()) { + if (dosID!=null && dosID.exists()) { BufferedReader br; try { br = new BufferedReader(new FileReader(dosID)); try { - if(deniedID==null) { + if (deniedID==null) { deniedID=new HashMap<>(); } String line; - while((line=br.readLine())!=null) { + while ((line=br.readLine())!=null) { deniedID.put(line, new Counter(line)); } } finally { @@ -284,9 +284,9 @@ public class DenialOfServiceTaf implements HttpTaf { * @return */ public static synchronized boolean removeDenyID(String id) { - if(deniedID!=null && deniedID.remove(id)!=null) { + if (deniedID!=null && deniedID.remove(id)!=null) { writeID(); - if(deniedID.isEmpty()) { + if (deniedID.isEmpty()) { deniedID=null; } @@ -297,16 +297,16 @@ public class DenialOfServiceTaf implements HttpTaf { public List report() { int initSize = 0; - if(deniedIP!=null)initSize+=deniedIP.size(); - if(deniedID!=null)initSize+=deniedID.size(); + 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()) { + if (deniedID!=null) { + for (Counter c : deniedID.values()) { al.add(c.toString()); } } - if(deniedIP!=null) { - for(Counter c : deniedIP.values()) { + if (deniedIP!=null) { + for (Counter c : deniedIP.values()) { al.add(c.toString()); } } @@ -344,13 +344,13 @@ public class DenialOfServiceTaf implements HttpTaf { private synchronized void inc() { ++count; last = System.currentTimeMillis(); - if(first==null) { + if (first==null) { first = new Date(last); } } public String toString() { - if(count==0) + if (count==0) return name + " is on the denied list, but has not attempted Access"; else return 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 f0b8d38d..07389aad 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 @@ -31,14 +31,14 @@ public class FQI { StringBuilder sb = null; String[] split = Split.split('.',fqi); int at; - for(int i=split.length-1;i>=0;--i) { - if(sb == null) { + for (int i=split.length-1;i>=0;--i) { + if (sb == null) { sb = new StringBuilder(); } else { sb.append('.'); } - if((at = split[i].indexOf('@'))>0) { + if ((at = split[i].indexOf('@'))>0) { sb.append(split[i].subSequence(at+1, split[i].length())); } else { sb.append(split[i]); 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 7c3ac30d..e790766b 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 @@ -39,11 +39,11 @@ public class JsonOutputStream extends OutputStream { @Override public void write(int b) throws IOException { - if(ret=='\n') { + if (ret=='\n') { ret = 0; - if(prev!=',' || (b!='{' && b!='[')) { + 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) { + if (check && bits>32) { throw new MaskFormatException("Invalid Mask Offset in IPV4 Address"); } int prev = 0; long lbyte; - while(prev255 || lbyte<0)) { + if (check && (lbyte>255 || lbyte<0)) { throw new MaskFormatException("Invalid Byte in IPV4 Address"); } rv|=lbyte<=0 && idx=0 && idx=0 && idx=0 && idx=0 && idx=0 && idx=0 && idx=0 && idx=0 && count=0 && count0) { + if (idx>0) { rv[++count]=value.substring(last,idx).trim(); } else { rv[++count]=value.substring(last).trim(); 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 5cab15f6..a85020ff 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 @@ -40,7 +40,7 @@ public class SubStandardConsole implements MyConsole { try { System.out.printf(fmt,args); rv = br.readLine(); - if(args.length==1 && rv.length()==0) { + if (args.length==1 && rv.length()==0) { rv = args[0].toString(); } } catch (IOException e) { 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 9ddd0626..da99d06d 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 @@ -25,7 +25,7 @@ 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) { + if (args.length>0 && args[0]!=null && rv.length()==0) { rv = args[0].toString(); } return rv; 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 ff74f39c..d42aaf55 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 @@ -31,7 +31,7 @@ public class UserChainManip { */ public static StringBuilder build(StringBuilder sb, String app, String id, UserChain.Protocol proto, boolean as) { boolean mayAs; - if(!(mayAs=sb.length()==0)) { + if (!(mayAs=sb.length()==0)) { sb.append(','); } sb.append(app); @@ -39,34 +39,34 @@ public class UserChainManip { sb.append(id); sb.append(':'); sb.append(proto.name()); - if(as && mayAs) { + if (as && mayAs) { sb.append(":AS"); } return sb; } public static String idToNS(String id) { - if(id==null) { + 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=0;--idx) { + if ((c = id.charAt(idx))=='@' || c=='.') { + if (idx=0) { + while ((idx=text.indexOf('%',prev))>=0) { replace = false; - if(clearIndex) { + if (clearIndex) { index=0; } - if(sb!=null) { + if (sb!=null) { sb.append(text,prev,idx); } - if(holder!=null) { + if (holder!=null) { holder.append(text,prev,idx); } boolean go = true; - while(go) { - if(text.length()>++idx) { + 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': @@ -87,19 +87,19 @@ public class Vars { } prev = idx; go=false; - if(replace) { - if(sb!=null) { + if (replace) { + if (sb!=null) { sb.append('%'); sb.append(index); } - if(index<=vars.length) { - if(holder!=null) { + if (index<=vars.length) { + if (holder!=null) { holder.append(vars[index-1]); } } } else { - for(StringBuilder s : sbs) { - if(s!=null) { + for (StringBuilder s : sbs) { + if (s!=null) { s.append("%"); } } @@ -107,10 +107,10 @@ public class Vars { } } - if(sb!=null) { + if (sb!=null) { sb.append(text,prev,text.length()); } - if(holder!=null) { + if (holder!=null) { holder.append(text,prev,text.length()); } 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 38322307..d0a7da47 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 @@ -57,42 +57,42 @@ public class Match { 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; + 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()) { + 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)) { + for (Match m : next) { + if (e_qname.equals(m.qname)) { match=true; - if(m.onMatch(output, reader)==null) { + 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 + 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())) { + 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)) { + if (event.asEndElement().getName().equals(qname)) { return prev; } break; 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 b7cc40ad..aa46bec5 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 @@ -66,7 +66,7 @@ public class XReader { } public boolean hasNext() throws XMLStreamException { - if(curr==null) { + if (curr==null) { curr = parse(); } return curr!=null; @@ -106,7 +106,7 @@ public class XReader { 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 + 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. @@ -115,15 +115,15 @@ public class XReader { int c=0; try { - while(go && (c=is.read())>=0) { + 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 + 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 + if (chars.length()>0) { // don't send if Characters were only whitespace cxe = new XEvent.Characters(chars); baos.reset(); go = false; @@ -145,7 +145,7 @@ public class XReader { default: ns = ""; } - if(ns==null) + if (ns==null) throw new XMLStreamException("Invalid Namespace Prefix at " + count); go = false; switch(t.state) { // based on @@ -165,9 +165,9 @@ public class XReader { 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 (last=='/')another = new XEvent.EndElement(ns,t.name); } - if(cxe!=null) { // if there is a Character Event, it actually should go first. ow. + 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 } @@ -175,12 +175,12 @@ public class XReader { case ' ': case '\t': case '\n': - if((state&BEGIN_DOC)==BEGIN_DOC) { // if Whitespace before doc, just ignore + 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 + 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 @@ -190,7 +190,7 @@ public class XReader { } 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 + 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 } @@ -214,15 +214,15 @@ public class XReader { String prefix=null,name=null,value=null; baos.reset(); - while(go && (c=is.read())>=0) { + 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!='\\') { + 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 + } 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. @@ -244,7 +244,7 @@ public class XReader { } break; case '>': // Tag indicator has been found, do we have all the comment characters in line? - if((state&COMPLETE_COMMENT)==COMPLETE_COMMENT) { + if ((state&COMPLETE_COMMENT)==COMPLETE_COMMENT) { byte ba[] = baos.toByteArray(); tag = new Tag(null,null, new String(ba,0,ba.length-2)); baos.reset(); @@ -254,7 +254,7 @@ public class XReader { // 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 + 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 @@ -273,7 +273,7 @@ public class XReader { } break; case '!': - if(last=='<') { + if (last=='<') { state|=COMMENT|COMMENT_E; // likely a comment, continue processing in Comment Loop } baos.write(c); @@ -296,15 +296,15 @@ public class XReader { case ' ': case '\t': case '\n': // white space indicates change in internal tag state, ex between name and between attributes - if((state&VALUE)==VALUE) { + if ((state&VALUE)==VALUE) { value = baos.toString(); // we're in VALUE state, add characters to Value - } else if(name==null) { + } 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... + 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 + 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); @@ -314,7 +314,7 @@ public class XReader { break; case '\'': // is the character one of two kinds of quote? case '"': - if(last!='\\') { + if (last!='\\') { quote=c; break; } @@ -327,10 +327,10 @@ public class XReader { 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) { + if (type==0) { type=START_TAG; } - if(tag!=null) { + if (tag!=null) { tag.state|=type; // add the appropriate Tag States } return tag; @@ -350,20 +350,20 @@ public class XReader { */ 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) { + 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); + 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) { + if (newnss==null) { + if (nss==null) { newnss = new HashMap<>(); } else { newnss = nss; @@ -399,7 +399,7 @@ public class XReader { * @param tag */ public void add(Tag attrib) { - if(attribs == null) { + if (attribs == null) { attribs = new ArrayList<>(); } attribs.add(attrib); @@ -407,14 +407,14 @@ public class XReader { public String toString() { StringBuffer sb = new StringBuffer(); - if(prefix!=null) { + if (prefix!=null) { sb.append(prefix); sb.append(':'); } sb.append(name==null?"!!ERROR!!":name); char quote = ((state&DOC_TYPE)==DOC_TYPE)?'\'':'"'; - if(value!=null) { + if (value!=null) { sb.append('='); sb.append(quote); sb.append(value); 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 f57bb93e..22ce8abf 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 @@ -99,7 +99,7 @@ public class JU_AUTHZServlet { field.setAccessible(true); field.set(target, value); field.setAccessible(false); - } catch(Exception e) { + } 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/principal/test/JU_X509Principal.java b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_X509Principal.java index a8839f2c..ea45c128 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 @@ -93,7 +93,7 @@ public class JU_X509Principal { try { x509 = new X509Principal(cert, cred, null); fail("Should have thrown an Exception"); - } catch(IOException e) { + } catch (IOException e) { assertThat(e.getMessage(), is("X509 does not have Identity as CN")); } @@ -102,7 +102,7 @@ public class JU_X509Principal { try { x509 = new X509Principal(cert, cred, null); fail("Should have thrown an Exception"); - } catch(IOException e) { + } catch (IOException e) { assertThat(e.getMessage(), is("X509 does not have Identity as CN")); } @@ -111,7 +111,7 @@ public class JU_X509Principal { try { x509 = new X509Principal(cert, cred, null); fail("Should have thrown an Exception"); - } catch(IOException e) { + } catch (IOException e) { assertThat(e.getMessage(), is("X509 does not have Identity as CN")); } 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 d67acf3c..47d8f8d1 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 @@ -353,7 +353,7 @@ public class JU_DenialOfServiceTaf { field.setAccessible(true); field.set(null, value); field.setAccessible(false); - } catch(Exception e) { + } 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/test/JU_AES.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_AES.java index affaccc5..a3e0db0d 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 @@ -60,7 +60,7 @@ public class JU_AES { 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) { + for (int i = 0; i < keyBytes.length; ++i) { keyBytes[i] = (byte)codeset[i+offset]; } aes = new AES(keyBytes, 0, keyBytes.length); 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 78a6fa21..60999b69 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 @@ -151,7 +151,7 @@ public class JU_BufferedServletInputStream { @Test public void ByteArrayReadStateIsReadTest() throws Exception { byte output[] = new byte[200]; - for(int i = 0; i < 2; ++i) { + for (int i = 0; i < 2; ++i) { bsis.mark(0); bsis.read(output, 0, 100); Assert.assertEquals(new String(output, 0, expected.length()), expected); @@ -160,7 +160,7 @@ public class JU_BufferedServletInputStream { bsis.read(output, 0, output.length); Assert.assertEquals(new String(output, 0, expected.length()), expected); bsis = new BufferedServletInputStream(new ByteArrayInputStream(output)); - if(i == 0) { + if (i == 0) { output = new byte[200]; } } @@ -286,7 +286,7 @@ public class JU_BufferedServletInputStream { 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) { + for (int i=0;read>=0;i+=read) { read = bsis.read(bb,i,5); switch(i) { case 65: 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 1bdbc571..4c842915 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 @@ -58,13 +58,13 @@ 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) { + 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) { + for (int i = 0; i < 20; ++i) { array[i]=(byte)cap.read(); } assertEquals("abcdefghijklmnopqrst", new String(array)); @@ -73,12 +73,12 @@ public class JU_Capacitor { cap.done(); } - for(int i = 0; i < 500; i++) { + 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) { + for (int i = 0; i < 500; ++i) { array[i]=(byte)cap.read(); } assertEquals((new String(array)).length(), 500); @@ -88,7 +88,7 @@ public class JU_Capacitor { @Test public void availableTest() { assertEquals(cap.available(), 0); - for(int i = 0; i < 100; ++i) { + for (int i = 0; i < 100; ++i) { cap.put((byte)'a'); } // The Capacitor can hold 256 bytes. After reading 100 bytes, @@ -114,12 +114,12 @@ public class JU_Capacitor { 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) { + 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) { + 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)); 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 cba4c46a..967bf221 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 @@ -163,7 +163,7 @@ public class JU_CmdLine { String filePath = "test/output_key"; File testDir = new File("test"); - if(!testDir.exists()) { + if (!testDir.exists()) { testDir.mkdirs(); } CmdLine.main(new String[]{"keygen", filePath}); 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 6f6f49e1..45f221c4 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 @@ -115,7 +115,7 @@ public class JU_PropAccess { }); try { pa.log(new Exception("This exception was thrown intentionally, please ignore it")); - } catch(Exception e) { + } catch (Exception e) { fail("Should have thrown an exception"); } } 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 15464bf1..7c67f8c9 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 @@ -89,7 +89,7 @@ public class JU_ServletContextAccess { try { sca.log(new Exception("This exception was thrown intentionally, please ignore it")); - } catch(Exception e) { + } catch (Exception e) { fail("Should have thrown an exception"); } } 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 5a1014bc..5f880403 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 @@ -130,12 +130,12 @@ public class JU_WSSEParser { // is = new BufferedServletInputStream(fis); // is.mark(0); // try { -// while(is.read()>=0); +// while (is.read()>=0); // } finally { // fis.close(); // } // -// for(int i=0;i rtt = tokenClient.getToken(scope); - if(rtt.isOK()) { + 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) { + 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"); } } @@ -86,10 +86,10 @@ public class SimpleRESTClient { //Format:::[:AS][,::]* public SimpleRESTClient endUser(Principal principal) { - if(principal==null) { + if (principal==null) { chain = null; } else { - if(principal instanceof TaggedPrincipal) { + if (principal instanceof TaggedPrincipal) { TaggedPrincipal tp = (TaggedPrincipal)principal; chain = tp.getName() + ':' + (app==null?"":app) + ':' + tp.tag() + ":AS"; } else { @@ -128,7 +128,7 @@ public class SimpleRESTClient { } public StringBuilder builder() { - if(sb==null) { + if (sb==null) { sb = new StringBuilder(); content = null; } @@ -140,16 +140,16 @@ public class SimpleRESTClient { */ public void clear() { content = null; - if(sb!=null) { + if (sb!=null) { sb.setLength(0); } } @Override public String toString() { - if(content!=null) { + if (content!=null) { return content; - } else if(sb!=null) { + } else if (sb!=null) { return sb.toString(); } else { return ""; @@ -158,8 +158,8 @@ public class SimpleRESTClient { public byte[] getBytes() { byte[] rv; - if(content==null) { - if(sb==null) { + if (content==null) { + if (sb==null) { rv = EMPTY_STREAM_BYTES; } else { rv = sb.toString().getBytes(); @@ -192,7 +192,7 @@ public class SimpleRESTClient { return client.create(path, contentType, new ETransfer(input)); } }); - if(!future.get(callTimeout)) { + if (!future.get(callTimeout)) { throw new RESTException(future); } } @@ -217,7 +217,7 @@ public class SimpleRESTClient { return client.read(path,accepts, headers()); } }); - if(future.get(callTimeout)) { + if (future.get(callTimeout)) { return future.value; } else { throw new RESTException(future); @@ -245,7 +245,7 @@ public class SimpleRESTClient { return client.update(path, contentType, new ETransfer(input)); } }); - if(future.get(callTimeout)) { + if (future.get(callTimeout)) { return future.value; } else { throw new RESTException(future); @@ -268,7 +268,7 @@ public class SimpleRESTClient { return client.delete(path, contentType); } }); - if(!future.get(callTimeout)) { + if (!future.get(callTimeout)) { throw new RESTException(future); } } @@ -292,14 +292,14 @@ public class SimpleRESTClient { } public String[] headers() { - if(chain==null) { + 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 is = tci.introspect(token.getAccessToken()); - if(is.isOK()) { + 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 { @@ -206,7 +206,7 @@ public class OAuthExample { } private static void print(Introspect ti) { - if(ti==null || ti.getClientId()==null) { + if (ti==null || ti.getClientId()==null) { System.out.println("Empty Introspect"); return; } 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 657a9b78..f4fe017f 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 @@ -97,7 +97,7 @@ public class OnapClientExample { // tc.clearToken("org.onap.aaf","org.onap.test"); // Result Object can be queried for success - if(rtt.isOK()) { + if (rtt.isOK()) { TimedToken token = rtt.value; print(token); // Take a look at what's in a Token @@ -122,7 +122,7 @@ public class OnapClientExample { // 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)) { + if (future.get(CALL_TIMEOUT)) { // Client Returned expected value return future.value; } else { @@ -140,7 +140,7 @@ public class OnapClientExample { // 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")) {... + // i.e. if (isUserInRole("ns.perm|instance|action")) {... // // Here, however, is a way to introspect via Java // @@ -148,7 +148,7 @@ public class OnapClientExample { // 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()) { + 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 { @@ -180,7 +180,7 @@ public class OnapClientExample { } private static void print(Introspect ti) { - if(ti==null || ti.getClientId()==null) { + if (ti==null || ti.getClientId()==null) { System.out.println("Empty Introspect"); return; } 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 27f9198a..dc1824fc 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 @@ -42,7 +42,7 @@ public class SimpleRestClientExample { String urlString = cf.getAccess().getProperty("myurl", null); - if(urlString==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" @@ -64,8 +64,8 @@ public class SimpleRestClientExample { PrintWriter pw = input.writer(); pw.print("{\"something\": ["); - for(int i=0;i<4;++i) { - if(i>0) { + for (int i=0;i<4;++i) { + if (i>0) { pw.print(','); } pw.print("{\"myint\":"); @@ -136,14 +136,14 @@ public class SimpleRestClientExample { System.out.println("-------- START Expecting Exception starting here --------"); expectException = true; restClient.get("notAnAPI"); - } catch(RESTException e) { + } 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) { + if (expectException) { System.out.println("-------- END Expecting Exception starting here --------"); } System.out.println("-------- END REST READ/GET --------"); 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 f11d8f89..e3342914 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 @@ -60,15 +60,15 @@ import org.onap.aaf.cadi.principal.TaggedPrincipal; request.getUserPrincipal()); String perm = request.getParameter("PERM"); - if(perm!=null) { - if(request.isUserInRole(perm)) { - if(perm.indexOf('|')<0) { + 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) { + 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); @@ -78,12 +78,12 @@ import org.onap.aaf.cadi.principal.TaggedPrincipal; // You can get the working AAFCon from Trans AAFCon aafcon = AAFCon.obtain(req); - if(aafcon!=null) { + if (aafcon!=null) { try { res.getOutputStream().println("----- Perms JSON from direct call -----"); final Principal up = request.getUserPrincipal(); TaggedPrincipal tp; - if(up instanceof TaggedPrincipal) { + if (up instanceof TaggedPrincipal) { tp = (TaggedPrincipal)up; } else { tp = new TaggedPrincipal() { @@ -101,7 +101,7 @@ import org.onap.aaf.cadi.principal.TaggedPrincipal; // 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 */)) { + if (future.get(4000 /* timeout */)) { res.getOutputStream().print(future.value); } else { System.err.println(future.code() + ", " + future.body()); 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 cec8a539..165acffb 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 @@ -51,7 +51,7 @@ public abstract class JettyServletServer implements Servlet { int maxPoolSize = 10; int keepAliveTime = 3000; String hostname = access.getProperty(Config.HOSTNAME, null); - if(hostname==null) { + if (hostname==null) { hostname = Inet4Address.getLocalHost().getHostName(); } @@ -62,7 +62,7 @@ public abstract class JettyServletServer implements Servlet { Server server = new Server(pool); String protocol; - if(access.getProperty(Config.CADI_KEYSTORE_PASSWORD,null)==null) { + if (access.getProperty(Config.CADI_KEYSTORE_PASSWORD,null)==null) { ServerConnector conn = new ServerConnector(server); conn.setHost(hostname); conn.setPort(port); 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 29462cfb..4d170f3f 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 @@ -55,9 +55,9 @@ public class MiniJASPIWrap extends ServletHolder { 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; + if (rolesAllowed!=null) { + for (String str : rolesAllowed.value()) { + if (first)first=false; else sb.append(','); sb.append(str); } @@ -73,26 +73,26 @@ public class MiniJASPIWrap extends ServletHolder { */ @Override public void handle(Request baseRequest, ServletRequest request, ServletResponse response) throws ServletException, UnavailableException, IOException { - if(rolesAllowed==null) { + 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)) { + for (String role : rolesAllowed.value()) { + if (hreq.isUserInRole(role)) { proceed = true; break; } } - if(proceed) { + if (proceed) { super.handle(baseRequest, request, response); } else { //baseRequest.getServletContext().log(hreq.getUserPrincipal().getName()+" Refused " + roles); ((HttpServletResponse)response).sendError(403); // forbidden } - } catch(ClassCastException e) { + } 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 1597dbd5..e82dddd2 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 @@ -76,10 +76,10 @@ 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) { + if (value==null) { access.log(Level.ERROR, atag, "is null"); } else { - if(value.startsWith("enc:")) { + if (value.startsWith("enc:")) { access.log(Level.INIT,atag,"=enc:************"); value = access.decrypt(value, false); } else { 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 d72222e8..a8f0951e 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 @@ -71,13 +71,13 @@ public class BaseDataFactory { 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"); + 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"); + 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"); + if (xs==null) throw new APIException(clss.getName() + " package-info does not have an XmlSchema annotation"); return new QName(xs.namespace(),xre.name()); } @@ -367,7 +367,7 @@ public class BaseDataFactory { // */ // public Character objectify(Env env, String input) throws APIException { // int length = input.length(); -// if(length<1 || length>1) { +// if (length<1 || length>1) { // throw new APIException("String [" + input + "] does not represent a single Character"); // } // return input.charAt(0); 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 aa74edc9..f2b539a3 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 @@ -68,8 +68,8 @@ public interface LogTarget { 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) { + for (Object str : msgs) { + if (str!=null) { out.print(str.toString()); out.print(' '); } else { @@ -83,7 +83,7 @@ public interface LogTarget { PrintStream out = System.out; out.print(Chrono.dateFmt.format(new Date())); out.print(": "); - for(Object str : msgs) { + for (Object str : msgs) { out.print(str.toString()); out.print(' '); } @@ -108,7 +108,7 @@ public interface LogTarget { PrintStream out = System.err; out.print(Chrono.dateFmt.format(new Date())); out.print(": "); - for(Object str : msgs) { + for (Object str : msgs) { out.print(str.toString()); out.print(' '); } @@ -120,7 +120,7 @@ public interface LogTarget { PrintStream out = System.err; out.print(Chrono.dateFmt.format(new Date())); out.print(": "); - for(Object str : msgs) { + for (Object str : msgs) { out.print(str.toString()); out.print(' '); } 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 b8a8e03a..6848be09 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 @@ -81,15 +81,15 @@ public class StoreImpl implements Store { staticMap = new HashMap<>(); localMap = new HashMap<>(); - if(tag!=null) { + if (tag!=null) { String tequals = tag + '='; - for(String arg : args) { - if(arg.startsWith(tequals) && !arg.equals(tequals)) { // needs to have something after = + 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()))) { + for (String f : Split.split(File.pathSeparatorChar,arg.substring(tequals.length()))) { moreProps(new File(f),props); } - for(Entry es : props.entrySet()) { + for (Entry es : props.entrySet()) { put(staticSlot(es.getKey().toString()),es.getValue()); } } @@ -105,29 +105,29 @@ public class StoreImpl implements Store { staticMap = new HashMap<>(); localMap = new HashMap<>(); - if(tag!=null) { + 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)) { + 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()) { + 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) { + 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])) { + 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 */); } } @@ -138,22 +138,22 @@ public class StoreImpl implements Store { } private boolean moreProps(File f, Properties target) { - if(f.exists()) { + if (f.exists()) { Properties props = new Properties(); try { FileInputStream fis = new FileInputStream(f); try { props.load(fis); - if(target!=null) { + if (target!=null) { target.load(fis); } } finally { fis.close(); } - } catch(IOException e) { + } catch (IOException e) { System.err.println(e); } - for(Entry es : props.entrySet()) { + for (Entry es : props.entrySet()) { put(staticSlot(es.getKey().toString()),es.getValue()); } return true; 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 b86b4fbb..c0e7bde7 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 @@ -124,7 +124,7 @@ public abstract class AbsTrans implements TransStore { Metric metric = new Metric(); int last = (metric.entries = trail.size()) -1; metric.buckets = flags.length==0?EMPTYF:new float[flags.length]; - if(last>=0) { + 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 @@ -133,48 +133,48 @@ public abstract class AbsTrans implements TransStore { metric.total = (end - first.start) / 1000000f; } - if(sb==null) { - for(TimeTaken tt : trail) { + if (sb==null) { + for (TimeTaken tt : trail) { float ms = tt.millis(); - for(int i=0;i stack = new Stack(); - for(TimeTaken tt : trail) { + for (TimeTaken tt : trail) { // Create Indentation based on SUB - while(!stack.isEmpty() && tt.end()>stack.peek()) { + while (!stack.isEmpty() && tt.end()>stack.peek()) { --indent; stack.pop(); } - for(int i=0;i implements TransStore { Object o; try { o = slot.get(state); - } catch(ArrayIndexOutOfBoundsException e) { + } 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); 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 94f7d47b..6fbfacdb 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 @@ -86,9 +86,9 @@ public class BasicEnv extends StoreImpl implements EnvJAXB, TransCreate(); // String value; -// for(int i=0;i=0) { + if (size>=0) { sb.append(" size: "); sb.append(Long.toString(size)); } @@ -185,11 +185,11 @@ public class BasicEnv extends StoreImpl implements EnvJAXB, TransCreate0) { + for (String key : existingStaticSlotNames()) { + if (filter.length>0) { yes = false; - for(String f : filter) { - if(key.startsWith(f)) { + for (String f : filter) { + if (key.startsWith(f)) { yes = true; break; } @@ -197,9 +197,9 @@ public class BasicEnv extends StoreImpl implements EnvJAXB, TransCreate DataFactory newDataFactory(Class... classes) throws APIException { -// if(String.class.isAssignableFrom(classes[0])) +// if (String.class.isAssignableFrom(classes[0])) // return (DataFactory) new StringDF(this); return new JAXBDF(this,classes); } @@ -250,7 +250,7 @@ public class BasicEnv extends StoreImpl implements EnvJAXB, TransCreate DataFactory newDataFactory(Schema schema, Class... classes) throws APIException { -// if(String.class.isAssignableFrom(classes[0])) +// if (String.class.isAssignableFrom(classes[0])) // return (DataFactory) new StringDF(this); return new JAXBDF(this, schema, classes); } @@ -258,7 +258,7 @@ public class BasicEnv extends StoreImpl implements EnvJAXB, TransCreate DataFactory newDataFactory(QName qName, Class ... classes) throws APIException { -// if(String.class.isAssignableFrom(classes[0])) +// if (String.class.isAssignableFrom(classes[0])) // return (DataFactory) new StringDF(this); return new JAXBDF(this, qName, classes); } @@ -274,9 +274,9 @@ public class BasicEnv extends StoreImpl implements EnvJAXB, TransCreate0) { + if (msg!=null && msg.length()>0) { int sbl = sb.length(); - if(sbl>0) { + if (sbl>0) { char last = sb.charAt(sbl-1); - if(" (.".indexOf(last)<0 && "().".indexOf(msg.charAt(0))<0)sb.append(' '); + if (" (.".indexOf(last)<0 && "().".indexOf(msg.charAt(0))<0)sb.append(' '); } sb.append(msg); } @@ -69,10 +69,10 @@ public class JavaUtilLogTarget implements LogTarget { public void log(Throwable e, Object ... msgs) { String str = e.getLocalizedMessage(); - if(str==null) { + if (str==null) { str = e.getMessage(); } - if(str==null) { + if (str==null) { str = e.getClass().getName(); } log.log(level,str,msgs); @@ -83,7 +83,7 @@ public class JavaUtilLogTarget implements LogTarget { */ @Override public void printf(String fmt, Object ... vars) { - if(log.isLoggable(level)) { + 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 81d9c1b2..b144852a 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 @@ -61,7 +61,7 @@ public class Log4JLogTarget implements LogTarget { // @Override public void log(Throwable e, Object... msgs) { - if (log.isEnabledFor(level)) { + if (log.isEnabledFor (level)) { StringBuilder sb = new StringBuilder(); String msg; @@ -69,7 +69,7 @@ public class Log4JLogTarget implements LogTarget { e.printStackTrace(new PrintWriter(new StringBuilderWriter(sb))); } for (int i = 0; i < msgs.length; ++i) { - if(msgs[i]!=null) { + if (msgs[i]!=null) { msg = msgs[i].toString(); if (msg != null && msg.length() > 0) { int sbl = sb.length(); @@ -92,7 +92,7 @@ public class Log4JLogTarget implements LogTarget { */ @Override public void printf(String fmt, Object ... vars) { - if(log.isEnabledFor(level)) { + if (log.isEnabledFor (level)) { log.log(level,String.format(fmt,vars)); } } 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 dc7ee192..d140a6b8 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 @@ -152,7 +152,7 @@ public class JAXBDF extends BaseDataFactory implements OldDataFactory,IOOb try { T t = jumar.unmarshal(env.debug(), input); return new JAXBData(primaryEnv, this, new JAXBStringifier(jmar), new JAXBObjectifier(jumar),t); - } catch(JAXBException e) { + } catch (JAXBException e) { throw new APIException(e); } } 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 38977a35..6d83aca4 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 @@ -114,7 +114,7 @@ public final class JAXBData implements Data{ * @throws APIException */ public String asString(EnvJAXB env) throws APIException { - if(dataAsString!=null) { + if (dataAsString!=null) { return dataAsString; } else { return dataAsString = stringifier.stringify(env, dataAsObject); @@ -131,7 +131,7 @@ public final class JAXBData implements Data{ */ // @Override public String asString() throws APIException { - if(dataAsString!=null) { + if (dataAsString!=null) { return dataAsString; } else { return dataAsString = stringifier.stringify(creatingEnv, dataAsObject,options); @@ -139,7 +139,7 @@ public final class JAXBData implements Data{ } public Data to(OutputStream os) throws APIException, IOException { - if(dataAsString!=null) { + if (dataAsString!=null) { os.write(dataAsString.getBytes()); } else if (stringifier instanceof IOStringifier){ ((IOStringifier)stringifier).stringify(creatingEnv, dataAsObject, os, options); @@ -153,7 +153,7 @@ public final class JAXBData implements Data{ // @Override public JAXBData to(Writer writer) throws APIException, IOException { - if(dataAsString!=null) { + if (dataAsString!=null) { writer.write(dataAsString); } else if (stringifier instanceof IOStringifier){ ((IOStringifier)stringifier).stringify(creatingEnv, dataAsObject, writer, options); @@ -166,7 +166,7 @@ public final class JAXBData implements Data{ public InputStream getInputStream() throws APIException { - if(dataAsString==null) { + if (dataAsString==null) { dataAsString = stringifier.stringify(creatingEnv,dataAsObject,options); } return new ByteArrayInputStream(dataAsString.getBytes()); @@ -184,7 +184,7 @@ public final class JAXBData implements Data{ */ public T asObject(EnvJAXB env) throws APIException { - if(dataAsObject !=null) { + if (dataAsObject !=null) { return dataAsObject; } else { // Some Java compilers need two statements here @@ -204,7 +204,7 @@ public final class JAXBData implements Data{ */ // @Override public T asObject() throws APIException { - if(dataAsObject !=null) { + if (dataAsObject !=null) { return dataAsObject; } else { // Some Java compilers need two statements here @@ -239,7 +239,7 @@ public final class JAXBData implements Data{ */ // @Override public String toString() { - if(dataAsString!=null) { + if (dataAsString!=null) { return dataAsString; } else { try { @@ -292,8 +292,8 @@ public final class JAXBData implements Data{ int count; do { count = input.read(b); - if(count>0)output.write(b, 0, count); - } while(count>=0); + if (count>0)output.write(b, 0, count); + } while (count>=0); } 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 46c40ebb..524fc668 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 @@ -80,10 +80,10 @@ public class JAXBmar { } public Marshaller get(boolean pretty, boolean fragment) throws JAXBException { - if(pretty != p) { + if (pretty != p) { m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, p = pretty); } - if(fragment != f) { + if (fragment != f) { m.setProperty(Marshaller.JAXB_FRAGMENT, f = fragment); } return m; @@ -139,7 +139,7 @@ public class JAXBmar { Pool mp; synchronized(pools) { mp = pools.get(classes); - if(mp==null) { + if (mp==null) { pools.put(classes,mp = new Pool(new Creator(classes))); } } @@ -165,7 +165,7 @@ public class JAXBmar { fragment = options.length>1?options[1]:this.fragment; Pooled m = mpool.get(lt); try { - if(qname==null) { + if (qname==null) { m.content.get(pretty,fragment).marshal(o, writer); } else { m.content.get(pretty,fragment).marshal( @@ -185,7 +185,7 @@ public class JAXBmar { fragment = options.length>1?options[1]:this.fragment; Pooled m = mpool.get(lt); try { - if(qname==null) { + if (qname==null) { m.content.get(pretty,fragment).marshal(o, os); } else { m.content.get(pretty,fragment).marshal( @@ -200,7 +200,7 @@ public class JAXBmar { public O marshal(LogTarget lt, O o, Writer writer, Class clss) throws JAXBException, APIException { Pooled m = mpool.get(lt); try { - if(qname==null) { + if (qname==null) { m.content.get(pretty,fragment).marshal(o, writer); } else { m.content.get(pretty,fragment).marshal( @@ -216,7 +216,7 @@ public class JAXBmar { public O marshal(LogTarget lt, O o, OutputStream os, Class clss) throws JAXBException, APIException { Pooled m = mpool.get(lt); try { - if(qname==null) { + if (qname==null) { m.content.get(pretty,fragment).marshal(o, os); } else { m.content.get(pretty,fragment).marshal( 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 fe3f0145..30345e7c 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 @@ -85,7 +85,7 @@ public class JAXBumar { } public Unmarshaller get(Schema schema) throws JAXBException { - if(s != schema) { + if (s != schema) { u.setSchema(s = schema); } return u; @@ -135,7 +135,7 @@ public class JAXBumar { Pool mp; synchronized(pools) { mp = pools.get(classes); - if(mp==null) { + if (mp==null) { pools.put(classes,mp = new Pool(new Creator(classes))); } } @@ -174,7 +174,7 @@ public class JAXBumar { @SuppressWarnings("unchecked") public O unmarshal(LogTarget env, String xml) throws JAXBException, APIException { - if(xml==null) throw new JAXBException("Null Input for String unmarshal"); + if (xml==null) throw new JAXBException("Null Input for String unmarshal"); Pooled s = mpool.get(env); try { return (O)s.content.get(schema).unmarshal( 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 ae78918c..553d7ade 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 @@ -107,17 +107,17 @@ public class Chrono { } public static String utcStamp(Date date) { - if(date==null)return ""; + if (date==null)return ""; return utcFmt.format(date); } public static String utcStamp(GregorianCalendar gc) { - if(gc==null)return ""; + if (gc==null)return ""; return utcFmt.format(gc.getTime()); } public static String utcStamp(XMLGregorianCalendar xgc) { - if(xgc==null)return ""; + if (xgc==null)return ""; return utcFmt.format(xgc.toGregorianCalendar().getTime()); } @@ -126,17 +126,17 @@ public class Chrono { } public static String dateStamp(GregorianCalendar gc) { - if(gc == null)return ""; + if (gc == null)return ""; return dateFmt.format(gc.getTime()); } public static String dateStamp(Date date) { - if(date == null)return ""; + if (date == null)return ""; return dateFmt.format(date); } public static String dateStamp(XMLGregorianCalendar xgc) { - if(xgc==null)return ""; + if (xgc==null)return ""; return dateFmt.format(xgc.toGregorianCalendar().getTime()); } @@ -172,7 +172,7 @@ public class Chrono { * @return */ public static String dateTime(GregorianCalendar gc) { - if(gc == null)return ""; + if (gc == null)return ""; TimeZone tz = gc.getTimeZone(); int tz1 = (tz.getRawOffset()+tz.getDSTSavings())/0x8CA0; int tz1abs = Math.abs(tz1); @@ -251,7 +251,7 @@ public class Chrono { } public static GregorianCalendar firstMomentOfDay(GregorianCalendar begin) { - if(begin==null)begin = new GregorianCalendar(); + if (begin==null)begin = new GregorianCalendar(); begin.set(GregorianCalendar.HOUR, 0); begin.set(GregorianCalendar.AM_PM, GregorianCalendar.AM); begin.set(GregorianCalendar.MINUTE, 0); @@ -261,7 +261,7 @@ public class Chrono { } public static GregorianCalendar lastMomentOfDay(GregorianCalendar end) { - if(end==null)end = new GregorianCalendar(); + if (end==null)end = new GregorianCalendar(); end.set(GregorianCalendar.HOUR, 11); end.set(GregorianCalendar.MINUTE, 59); end.set(GregorianCalendar.SECOND, 59); 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 97d9de99..b9191c00 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 @@ -43,7 +43,7 @@ public class DoubleOutputStream extends OutputStream { */ @Override public void write(int c) throws IOException { - for(OutputStream os : oss) { + for (OutputStream os : oss) { os.write(c); } } @@ -58,14 +58,14 @@ public class DoubleOutputStream extends OutputStream { */ @Override public void write(byte bbuf[], int off, int len) throws IOException { - for(OutputStream os : oss) { + for (OutputStream os : oss) { os.write(bbuf,off,len); } } @Override public void write(byte[] b) throws IOException { - for(OutputStream os : oss) { + for (OutputStream os : oss) { os.write(b); } } @@ -75,8 +75,8 @@ public class DoubleOutputStream extends OutputStream { */ @Override public void close() throws IOException { - for(int i=0;i> { public T get(Env env) throws APIException { Thread t = Thread.currentThread(); T obj = objs.get(t); - if(obj==null || refreshed>obj.created()) { + if (obj==null || refreshed>obj.created()) { try { obj = cnst.newInstance(new Object[]{env}); } catch (InvocationTargetException e) { @@ -96,7 +96,7 @@ public class RefreshableThreadObject> { throw new APIException(e); } T destroyMe = objs.put(t,obj); - if(destroyMe!=null) { + if (destroyMe!=null) { destroyMe.destroy(env); } } @@ -118,7 +118,7 @@ public class RefreshableThreadObject> { */ public void remove(Env env) { T obj = objs.remove(Thread.currentThread()); - if(obj!=null) + 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 4069c329..b0da8ba2 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 @@ -33,20 +33,20 @@ public class Split { private static final String[] BLANK = new String[0]; public static String[] split(char c, String value) { - if(value==null) { + 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); + for (count=1,idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,++idx),++count); String[] rv = new String[count]; - if(count==1) { + if (count==1) { rv[0]=value; } else { int last=0; count=-1; - for(idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,idx)) { + for (idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,idx)) { rv[++count]=value.substring(last,idx); last = ++idx; } @@ -56,19 +56,19 @@ public class Split { } public static String[] splitTrim(char c, String value) { - if(value==null) { + 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); + for (count=1,idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,++idx),++count); String[] rv = new String[count]; - if(count==1) { + 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)) { + for (idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,idx)) { rv[++count]=value.substring(last,idx).trim(); last = ++idx; } @@ -78,19 +78,19 @@ public class Split { } public static String[] splitTrim(char c, String value, int size) { - if(value==null) { + if (value==null) { return BLANK; } int idx; String[] rv = new String[size]; - if(size==1) { + 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 && count { 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) { + if (state.unsent > 0) { parsed.event = state.unsent; state.unsent = 0; return parsed; @@ -45,13 +45,13 @@ public class InJson implements Parse { 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 + 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. + if (c=='"') { + if (inQuotes) { + if (escaped) { // if escaped Quote, add to data. sb.append(c); escaped = false; } else { @@ -62,9 +62,9 @@ public class InJson implements Parse { inQuotes = true; } } else { // Not a Quote - if(inQuotes) { - if(c=='\\') { - if(escaped) { + if (inQuotes) { + if (c=='\\') { + if (escaped) { sb.append("\\\\"); escaped = false; } else { @@ -80,7 +80,7 @@ public class InJson implements Parse { parsed.isString = false; break; case Parse.START_OBJ: - if(state.braces++ == 0) { + if (state.braces++ == 0) { parsed.event = START_DOC; state.unsent = c; } else { @@ -89,7 +89,7 @@ public class InJson implements Parse { go = false; break; case Parse.END_OBJ: - if(--state.braces == 0) { + if (--state.braces == 0) { parsed.event = c; state.unsent = END_DOC; } else { @@ -99,7 +99,7 @@ public class InJson implements Parse { 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("__")) { + if (parsed.name.startsWith("__")) { parsed.event = Parse.ATTRIB; parsed.name = parsed.name.substring(2); } else { 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 91b7c57d..175a2aa2 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 @@ -51,13 +51,13 @@ public class InXML implements Parse { State state = parsed.state; // OK, before anything else, see if there is leftover processing, if so, do it! - if(state.unevaluated!=null) { + if (state.unevaluated!=null) { DerTag dt = state.unevaluated; state.unevaluated = null; - if(!state.greatExp.eval(parsed, dt))return parsed; + if (!state.greatExp.eval(parsed, dt))return parsed; } - if(state.hasAttributes()) { + if (state.hasAttributes()) { Prop prop = state.pop(); parsed.event = Parse.ATTRIB; parsed.name = prop.tag; @@ -73,14 +73,14 @@ public class InXML implements Parse { boolean go = true; try { - while(go && (ch=r.read())>=0) { + while (go && (ch=r.read())>=0) { c = (char)ch; - if(c == '"') { - if(state.greatExp instanceof LeafExpectations) { // within a set of Tags, make a Quote + if (c == '"') { + if (state.greatExp instanceof LeafExpectations) { // within a set of Tags, make a Quote sb.append(c); } else { - if(inQuotes) { - if(escaped) { + if (inQuotes) { + if (escaped) { sb.append('\\'); sb.append(c); escaped = false; @@ -92,11 +92,11 @@ public class InXML implements Parse { inQuotes = true; } } - } else if(inQuotes) { + } else if (inQuotes) { sb.append(c); - } else if(c=='&') { + } else if (c=='&') { XmlEscape.xmlEscape(sb,r); - } else if(c=='\\') { + } else if (c=='\\') { escaped=true; } else { switch(c) { @@ -106,9 +106,9 @@ public class InXML implements Parse { break; default: // don't add Whitespace to start of SB... saves removing later - if(sb.length()>0) { + if (sb.length()>0) { sb.append(c); - } else if(!Character.isWhitespace(c)) { + } else if (!Character.isWhitespace(c)) { sb.append(c); } } @@ -142,16 +142,16 @@ public class InXML implements Parse { String tag = null; try { - if((ch = r.read())<0) throw new ParseException("Reader content ended before complete"); - if(ch=='?') { + 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) { + if (c=='"') { + if (inQuotes) { + if (escaped) { sb.append(c); escaped = false; } else { @@ -160,7 +160,7 @@ public class InXML implements Parse { } else { inQuotes = true; } - } else if(inQuotes) { + } else if (inQuotes) { sb.append(c); } else { switch(c) { @@ -184,13 +184,13 @@ public class InXML implements Parse { // sb.setLength(0); // break; case '?': - if(!isXmlInfo)sb.append(c); + if (!isXmlInfo)sb.append(c); break; default: sb.append(c); } } - } while(go && (ch=r.read())>=0); + } while (go && (ch=r.read())>=0); } catch (IOException e) { throw new ParseException(e); } @@ -198,14 +198,14 @@ public class InXML implements Parse { } private void endField(String tag, StringBuilder sb) { - if(name==null) { + 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<>(); + if (tag !=null && value != null) { + if (props==null)props = new ArrayList<>(); props.add(new Prop(tag,value)); } } @@ -217,7 +217,7 @@ public class InXML implements Parse { sb.append(" Tag\n"); sb.append(" Name: "); sb.append(name); - if(props!=null) for(Prop p : props) { + if (props!=null) for (Prop p : props) { sb.append("\n "); sb.append(p.tag); sb.append("=\""); @@ -250,7 +250,7 @@ public class InXML implements Parse { } public void push(Prop prop) { - if(attribs==null) { + if (attribs==null) { attribs = new ArrayList<>(); idx = 0; } @@ -259,9 +259,9 @@ public class InXML implements Parse { public Prop pop() { Prop rv = null; - if(attribs!=null) { + if (attribs!=null) { rv = attribs.get(idx++); - if(idx>=attribs.size())attribs = null; + if (idx>=attribs.size())attribs = null; } return rv; } @@ -282,8 +282,8 @@ public class InXML implements Parse { // Recursively look back for any namespaces protected Map getNS() { - if(ns!=null)return ns; - if(prev!=null) { + if (ns!=null)return ns; + if (prev!=null) { return prev.getNS(); } return null; @@ -291,47 +291,47 @@ public class InXML implements Parse { private void addNS(Prop prop) { Map existingNS = getNS(); - if(ns==null)ns = new HashMap<>(); + 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) { + 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; + if (derTag==null)return ji; List props = derTag.props; Prop derived = null; - if(props!=null) { + if (props!=null) { // Load Namespaces (if any) - for(Prop prop : props) { - if(prop.tag.startsWith("xmlns:")) { + for (Prop prop : props) { + if (prop.tag.startsWith("xmlns:")) { addNS(prop); } } - for(Prop prop : props) { - if(prop.tag.endsWith(":type")) { + 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) { + if (ns==null) { noNamespace = true; } else { String nsVal = ns.get(potentialNS); - if(nsVal==null) noNamespace = true; + if (nsVal==null) noNamespace = true; else { derived = new Prop(Parsed.EXTENSION_TAG,prop.value); state.push(derived); } } - if(noNamespace) { + if (noNamespace) { throw new ParseException(prop.tag + " utilizes an invalid Namespace prefix"); } - } else if(!prop.tag.startsWith("xmlns")) { + } else if (!prop.tag.startsWith("xmlns")) { state.push(prop); } } @@ -348,10 +348,10 @@ public class InXML implements Parse { // @Override public boolean eval(Parsed parsed, DerTag derTag) throws ParseException { - if(derTag.isXmlInfo) { + if (derTag.isXmlInfo) { parsed.event = START_DOC; - } else if(ji.name.equals(derTag.name)) { - if(derTag.isEndTag) { + } else if (ji.name.equals(derTag.name)) { + if (derTag.isEndTag) { parsed.event = END_DOC; parsed.state.greatExp = prev; } else { @@ -374,22 +374,22 @@ public class InXML implements Parse { // @Override public boolean eval(Parsed parsed, DerTag derTag) throws ParseException { - if(derTag.isEndTag && ji.name.equals(derTag.name)) { + if (derTag.isEndTag && ji.name.equals(derTag.name)) { parsed.state.greatExp = prev; parsed.event = END_OBJ; - if(printName)parsed.name = ji.name; + if (printName)parsed.name = ji.name; } else { //Standard Members - for(JaxInfo memb : ji.members) { - if(memb.name.equals(derTag.name)) { + for (JaxInfo memb : ji.members) { + if (memb.name.equals(derTag.name)) { parsed.name = memb.name; - if(memb.isArray) { + 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) { + } else if (memb.isObject()) { + if (derTag.isEndTag) { throw new ParseException("Unexpected End Tag '); } else { parsed.event = START_OBJ; @@ -398,7 +398,7 @@ public class InXML implements Parse { return false; } } else { // a leaf - if(derTag.isEndTag) { + if (derTag.isEndTag) { throw new ParseException("Misplaced End Tag '); } else { parsed.state.greatExp = new LeafExpectations(parsed.state,memb, this); @@ -421,7 +421,7 @@ public class InXML implements Parse { // @Override public boolean eval(Parsed parsed, DerTag derTag) throws ParseException { - if(ji.name.equals(derTag.name) && derTag.isEndTag) { + if (ji.name.equals(derTag.name) && derTag.isEndTag) { parsed.event = NEXT; parsed.isString = ji.isString; parsed.state.greatExp = prev; @@ -435,18 +435,18 @@ public class InXML implements Parse { 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(); + 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) { + 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) { + if (ai.firstObj || ai.didNext) { ai.firstObj = false; ai.didNext = false; parsed.event = START_OBJ; @@ -459,7 +459,7 @@ public class InXML implements Parse { } } } else { // a leave - if(derTag.isEndTag) { + if (derTag.isEndTag) { throw new ParseException("Misplaced End Tag '); } else { parsed.state.greatExp = new LeafExpectations(parsed.state, ji, this); 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 edc5f787..d209f02f 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 @@ -65,22 +65,22 @@ public class JaxInfo { public int getType() { - if(isArray)return ARRAY; - else if(members!=null)return OBJECT; + if (isArray)return ARRAY; + else if (members!=null)return OBJECT; return DATA; } public JaxInfo getDerived(String derivedName) { JaxInfo derived; // Lazy Instantiation - if(extensions == null) { + if (extensions == null) { extensions = new HashMap<>(); derived = null; } else { derived = extensions.get(derivedName); } - if(derived == null) { + if (derived == null) { //TODO for the moment, Classes are in same package Package pkg = clss.getPackage(); try { @@ -95,8 +95,8 @@ public class JaxInfo { } public static JaxInfo get(JaxInfo[] fields, String name) { - for(JaxInfo f : fields) { - if(name.equals(f.name)) return f; + for (JaxInfo f : fields) { + if (name.equals(f.name)) return f; } return null; } @@ -128,7 +128,7 @@ public class JaxInfo { */ public static JaxInfo build(Class cls, String ... rootNns) throws SecurityException, NoSuchFieldException, ClassNotFoundException, ParseException { String defaultNS; - if(rootNns.length>0 && rootNns[0]!=null) { + if (rootNns.length>0 && rootNns[0]!=null) { defaultNS = rootNns[0]; } else { Package pkg = cls.getPackage(); @@ -136,15 +136,15 @@ public class JaxInfo { defaultNS = xs==null?"":xs.namespace(); } String name; - if(rootNns.length>1) { + if (rootNns.length>1) { name = rootNns[1]; } else { XmlRootElement xre = cls.getAnnotation(XmlRootElement.class); - if(xre!=null) { + if (xre!=null) { name = xre.name(); } else { XmlType xt = cls.getAnnotation(XmlType.class); - if(xt!=null) { + if (xt!=null) { name=xt.name(); } else { throw new ParseException("Need a JAXB Object with XmlRootElement, or stipulate in parms"); @@ -162,10 +162,10 @@ public class JaxInfo { 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 + 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(); @@ -175,27 +175,27 @@ public class JaxInfo { String namespace = defaultNS; XmlElement xe = rf.getAnnotation(XmlElement.class); - if(xe!=null) { + if (xe!=null) { xmlName=xe.name(); required = xe.required(); nillable = false; - if(DEFAULT.equals(xmlName)) { + if (DEFAULT.equals(xmlName)) { xmlName = field; } namespace = xe.namespace(); - if(DEFAULT.equals(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)) { + 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())) { + if (xe!=null && !DEFAULT.equals(xe.namespace())) { namespace = xe.namespace(); } // add recursed recursed member, marked as array @@ -208,7 +208,7 @@ public class JaxInfo { } cls = cls.getSuperclass(); }; - if(fields!=null) { + if (fields!=null) { JaxInfo[] rv = new JaxInfo[fields.size()]; fields.toArray(rv); return rv; @@ -219,17 +219,17 @@ public class JaxInfo { public StringBuilder dump(StringBuilder sb, int idx) { - for(int i=0;i { members = new TreeMap<>(); XmlType xmltype = cls.getAnnotation(XmlType.class); Class paramType[] = new Class[] {String.class}; - for(String str : xmltype.propOrder()) { + 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) { + if (meth!=null) { members.put(str, new Setter(meth) { public void set(T o, Object t) throws ParseException { try { @@ -78,7 +78,7 @@ public class JaxSet { synchronized(jsets) { @SuppressWarnings("unchecked") JaxSet js = (JaxSet)jsets.get(cls); - if(js == null) { + if (js == null) { jsets.put(cls, js = new JaxSet<>(cls)); } return js; 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 5e03ac91..6ff627b9 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 @@ -55,7 +55,7 @@ public class Ladder { public void top() { rung = struts.length-1; - while(rung>0 && struts[rung]==null)--rung; + while (rung>0 && struts[rung]==null)--rung; } public int howHigh() { @@ -63,7 +63,7 @@ public class Ladder { } public void jumpTo(int rung) { - if(rung>=struts.length) { + if (rung>=struts.length) { Object[] temp = new Object[init_size*((rung/init_size)+1)]; System.arraycopy(struts, 0, temp, 0, struts.length); struts = temp; @@ -83,7 +83,7 @@ public class Ladder { public void ascend() { ++rung; - if(rung>=struts.length) { + if (rung>=struts.length) { Object[] temp = new Object[struts.length+init_size]; System.arraycopy(struts, 0, temp, 0, struts.length); struts = temp; 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 4b8d2bf3..3729d1e3 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 @@ -59,7 +59,7 @@ public abstract class Marshal implements Parse { @Override public Void next() { - if(!hasNext()) { + if (!hasNext()) { throw new NoSuchElementException(); } return null; 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 2716c8be..4fb52d86 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 @@ -35,8 +35,8 @@ public class OutJax extends Out { 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"); + while ((p = parse.parse(in,p.reuse())).valid()) { + if (je==null)throw new ParseException("Incomplete content"); je = je.eval(p); } 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 d0a26784..6c868378 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 @@ -33,7 +33,7 @@ public class OutJson extends Out { 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 + if (options.length>0 && options[0]) { // is Pretty ipw = writer instanceof IndentPrintWriter?(IndentPrintWriter)writer:new IndentPrintWriter(writer); writer = ipw; } else { @@ -47,13 +47,13 @@ public class OutJson extends Out { char afterName=0, beforeName=0, maybe = 0, prev=0; int count = 0; - while((p = prs.parse(in,p.reuse())).valid()) { + 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 + if (count==2) { // it's empty, write open/close on it's own writer.append('{'); writer.append('}'); } @@ -61,7 +61,7 @@ public class OutJson extends Out { return; case '{': afterName = '{'; - if(jsonLevel.peek().printObjectName) { + if (jsonLevel.peek().printObjectName) { print = true; } else { // don't print names on first print=false; @@ -70,7 +70,7 @@ public class OutJson extends Out { jsonLevel.push(new LevelStack(true)); break; case '}': - if(p.hasData()) { // if we have data, we print that, so may need to prepend a comma. + 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 @@ -81,7 +81,7 @@ public class OutJson extends Out { break; case '[': afterName = p.event; - if((prev==',' && !hadData) || prev==']')maybe=','; + if ((prev==',' && !hadData) || prev==']')maybe=','; else maybe = jsonLevel.peek().listItem(); jsonLevel.push(new LevelStack(false)); @@ -89,8 +89,8 @@ public class OutJson extends Out { break; case ']': afterName = p.event; - if(p.hasData()) { - if(prev==',' && !hadData)maybe=','; + if (p.hasData()) { + if (prev==',' && !hadData)maybe=','; else maybe = jsonLevel.peek().listItem(); } else { p.name = ""; // XML tags come through with names, but no data @@ -101,7 +101,7 @@ public class OutJson extends Out { break; case 3: case ',': - if(!p.hasData()) { + if (!p.hasData()) { p.isString=false; print=false; } else { @@ -113,36 +113,36 @@ public class OutJson extends Out { print = true; } - if(maybe!=0) { - if(ipw==null)writer.append(maybe); + if (maybe!=0) { + if (ipw==null)writer.append(maybe); else ipw.println(maybe); maybe = 0; } - if(beforeName!=0) { - if(ipw==null)writer.append(beforeName); + if (beforeName!=0) { + if (ipw==null)writer.append(beforeName); else ipw.println(beforeName); beforeName = 0; } - if(print) { - if(p.hasName()) { + if (print) { + if (p.hasName()) { writer.append('"'); - if(p.event==3)writer.append("__"); + if (p.event==3)writer.append("__"); writer.append(p.name); writer.append("\":"); } - if(p.hasData()) { - if(p.isString) { + if (p.hasData()) { + if (p.isString) { writer.append('"'); escapedWrite(writer, p.sb); writer.append('"'); - } else if(p.sb.length()>0) { + } else if (p.sb.length()>0) { writer.append(p.sb); } } } - if(afterName!=0) { - if(ipw==null)writer.append(afterName); + if (afterName!=0) { + if (ipw==null)writer.append(afterName); else { switch(afterName) { case '{': @@ -155,7 +155,7 @@ public class OutJson extends Out { ipw.print(afterName); break; case ']': - if(prev=='}' || prev==',')ipw.println(); + if (prev=='}' || prev==',')ipw.println(); ipw.dec(); ipw.print(afterName); break; @@ -170,7 +170,7 @@ public class OutJson extends Out { afterName = 0; } - if(ipw!=null) { + if (ipw!=null) { switch(p.event) { case '[': ipw.inc(); @@ -187,11 +187,11 @@ public class OutJson extends Out { 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()) { + while ((p = prs.parse(in,p.reuse())).valid()) { writer.append(p.toString()); writer.append('\n'); } 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 a887cb96..6472c88e 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 @@ -43,9 +43,9 @@ public class OutXML extends Out{ public OutXML(String root, String ... params) { this.root = root; props = new ArrayList<>(); - for(String p : params) { + for (String p : params) { String[] tv=p.split("="); - if(tv.length==2) + if (tv.length==2) props.add(new Prop(tv[0],tv[1])); } } @@ -71,8 +71,8 @@ public class OutXML extends Out{ boolean pretty = (options.length>0&&options[0]); IndentPrintWriter ipw; - if(pretty) { - if(writer instanceof IndentPrintWriter) { + if (pretty) { + if (writer instanceof IndentPrintWriter) { ipw = (IndentPrintWriter)writer; } else { writer = ipw = new IndentPrintWriter(writer); @@ -82,19 +82,19 @@ public class OutXML extends Out{ } boolean closeTag = false; Level level = new Level(null); - while((p = prs.parse(in,p.reuse())).valid()) { - if(!p.hasName() && level.multi!=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) { + if (closeTag && p.event!=Parse.ATTRIB) { writer.append('>'); - if(pretty)writer.append('\n'); + 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); + 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: @@ -102,21 +102,21 @@ public class OutXML extends Out{ case Parse.START_OBJ: stack.push(level); level = new Level(level); - if(p.hasName()) { + if (p.hasName()) { closeTag = tag(writer,level.sbw,pretty,pretty,p.name,null); - } else if(root!=null && stack.size()==1) { // first Object + } 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) { + for (Prop prop : props) { attrib(writer,pretty,prop.tag, prop.value,level); } } - if(pretty)ipw.inc(); + if (pretty)ipw.inc(); break; case Parse.END_OBJ: - if(p.hasData()) + if (p.hasData()) closeTag = tag(writer,writer,pretty,false,p.name, XmlEscape.convert(p.sb)); - if(pretty)ipw.dec(); + if (pretty)ipw.dec(); writer.append(level.sbw.getBuffer()); level = stack.pop(); break; @@ -124,16 +124,16 @@ public class OutXML extends Out{ level.multi = p.name; break; case Parse.END_ARRAY: - if(p.hasData()) + 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()) + if (p.hasData()) attrib(writer,pretty,p.name, XmlEscape.convert(p.sb), level); break; case Parse.NEXT: - if(p.hasData()) + if (p.hasData()) closeTag = tag(writer,writer,pretty, false,p.name, XmlEscape.convert(p.sb)); break; } @@ -156,15 +156,15 @@ public class OutXML extends Out{ public boolean hasPrinted(String ns, String value, boolean create) { boolean rv = false; - if(nses==null) { - if(prev!=null)rv = prev.hasPrinted(ns, value, 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<>(); + if (create && !rv) { + if (nses == null) nses = new HashMap<>(); nses.put(ns, value); } return rv; @@ -177,25 +177,25 @@ public class OutXML extends Out{ 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) { + if (data!=null) { fore.append('>'); // if no data, it may need some attributes... fore.append(data); - if(returns)fore.append('\n'); + if (returns)fore.append('\n'); } aft.append(""); - if(pretty)aft.append('\n'); + 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 + 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)) { + if (!level.hasPrinted(XMLNS_XSI, XML_SCHEMA_INSTANCE,true)) { fore.append(' '); fore.append(XMLNS_XSI); fore.append("=\""); @@ -203,8 +203,8 @@ public class OutXML extends Out{ fore.append("\""); } } else { - if(realTag.startsWith("xmlns:") ) { - if(level.hasPrinted(realTag, value, true)) { + if (realTag.startsWith("xmlns:") ) { + if (level.hasPrinted(realTag, value, true)) { return; } } 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 a4c679db..29a86de8 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 @@ -73,15 +73,15 @@ public class Parsed { public String toString() { StringBuilder sb2 = new StringBuilder(); - if(event<40)sb2.append((int)event); + if (event<40)sb2.append((int)event); else sb2.append(event); sb2.append(" - "); sb2.append(name); - if(sb.length()>0) { + if (sb.length()>0) { sb2.append(" : "); - if(isString)sb2.append('"'); + if (isString)sb2.append('"'); sb2.append(sb); - if(isString)sb2.append('"'); + 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 ae9c8934..d46fc8be 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 @@ -31,7 +31,7 @@ class Prop { public Prop(String t_equals_v) { String[] tv = t_equals_v.split("="); - if(tv.length>1) { + if (tv.length>1) { tag = tv[0]; value = tv[1]; } 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 a596b705..efb4ce4b 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 @@ -50,20 +50,20 @@ public class Saved extends Out implements Parse{ // @Override public void extract(IN in, Writer ignore, Parse parser, boolean ... options) throws IOException, ParseException { Parsed p = parser.newParsed(); - if(!append) { + if (!append) { // reuse array if not too big - if(content==null||content.length>INIT_SIZE*3) { + if (content==null||content.length>INIT_SIZE*3) { content = new Content[INIT_SIZE]; idx = -1; } else do { content[idx]=null; - } while(--idx>=0); + } 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) { + 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; @@ -76,7 +76,7 @@ public class Saved extends Out implements Parse{ // @Override public Parsed parse(Reader ignore, Parsed parsed) throws ParseException { int i; - if((i=parsed.state.count++)<=idx) + if ((i=parsed.state.count++)<=idx) content[i].load(parsed); else parsed.event = Parse.NONE; @@ -85,9 +85,9 @@ public class Saved extends Out implements Parse{ 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) { + 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; @@ -98,8 +98,8 @@ public class Saved extends Out implements Parse{ } public void paste(Content[] appended) { - if(appended!=null) { - if(idx+appended.length>content.length) { + 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; @@ -134,7 +134,7 @@ public class Saved extends Out implements Parse{ p.isString = isString; p.event = event; p.name = name; - if(str!=null) + if (str!=null) p.sb.append(str); } @@ -144,14 +144,14 @@ public class Saved extends Out implements Parse{ sb.append(" - "); sb.append(name); sb.append(": "); - if(isString)sb.append('"'); + if (isString)sb.append('"'); sb.append(str); - if(isString)sb.append('"'); + if (isString)sb.append('"'); sb.append(' '); - if(props!=null) { + if (props!=null) { boolean comma = false; - for(Prop prop : props) { - if(comma)sb.append(','); + for (Prop prop : props) { + if (comma)sb.append(','); else comma = true; sb.append(prop.tag); sb.append('='); 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 1b0eec07..3007ea95 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 @@ -36,13 +36,13 @@ public class XmlEscape { 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!=';') { + 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) { + if (i==null) { // leave in nasty XML format for now. sb.append('&'); sb.append(esc); @@ -69,20 +69,20 @@ public class XmlEscape { 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) { + if (ch>=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(); + if (sb==null)return insb.toString(); - for(int i=idx;i es: charMap.entrySet()) { - if(es.getValue()>=160); // save small space... note that no longer has amp, etc. + 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 69926974..a95da8ea 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 @@ -217,7 +217,7 @@ public class RosettaDF extends BaseDataFactory implements DataFactory { * @return */ public RosettaDF rootMarshal(Marshal marshal) { - if(marshal instanceof DocMarshal) { + if (marshal instanceof DocMarshal) { this.marshal = marshal; } else { this.marshal = DocMarshal.root(marshal); @@ -229,7 +229,7 @@ public class RosettaDF extends BaseDataFactory implements DataFactory { 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 + 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); @@ -247,7 +247,7 @@ public class RosettaDF extends BaseDataFactory implements DataFactory { 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 + 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); 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 97f68dae..fa29dcdc 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 @@ -129,7 +129,7 @@ public class RosettaData implements Data{ Parse in = df.getIn(inType); TimeTaken tt = in.start(trans); try { - if(df.marshal==null) { // Unknown marshaller... do working XML marshal/extraction + 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); @@ -169,15 +169,15 @@ public class RosettaData implements Data{ 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) { + 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) { + if (json==null) { StringWriter sw = new StringWriter(); out.extract(null, sw, saved, options); json = sw.toString(); @@ -197,9 +197,9 @@ public class RosettaData implements Data{ 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) { + if (outType==TYPE.XML && xml!=null) { os.write(xml.getBytes()); - } else if(outType==TYPE.JSON && json!=null) { + } else if (outType==TYPE.JSON && json!=null) { os.write(json.getBytes()); } else { out.extract(null, os, saved, options); @@ -217,9 +217,9 @@ public class RosettaData implements Data{ 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) { + if (outType==TYPE.XML && xml!=null) { writer.append(xml); - } else if(outType==TYPE.JSON && json!=null) { + } else if (outType==TYPE.JSON && json!=null) { writer.append(json); } else { out.extract(null, writer, saved, options); @@ -260,7 +260,7 @@ public class RosettaData implements Data{ 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 (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); @@ -278,8 +278,8 @@ public class RosettaData implements Data{ 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)) { + 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(); 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 849a3214..0617e01d 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 @@ -127,7 +127,7 @@ public abstract class DataWriter { // String in "HexString" or the processing in // "String.format" //sb.append("0x"); - for(int i=0;i>4)]); sb.append(chars[b&0xF]); 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 6cabe068..1fa17010 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 @@ -40,18 +40,18 @@ public class DocMarshal extends Marshal { public Parsed parse(T t, Parsed parsed) throws ParseException { Ladder> ladder = parsed.state.ladder; Iterator iter = ladder.peek(); - if(iter==null) { + 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)){ + if (!DONE_ITERATOR.equals(currFieldIter)){ parsed = root.parse(t, parsed); } ladder.descend(); - if(DONE_ITERATOR.equals(currFieldIter) || parsed.event==NONE) { + if (DONE_ITERATOR.equals(currFieldIter) || parsed.event==NONE) { parsed.event = END_DOC; ladder.push(DONE_ITERATOR); } @@ -68,7 +68,7 @@ public class DocMarshal extends Marshal { @Override public Void next() { - if(!hasNext()) { + if (!hasNext()) { throw new NoSuchElementException(); } return null; 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 48f3608d..abc19b26 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 @@ -44,9 +44,9 @@ public abstract class FieldArray extends Marshal { public Parsed parse(T t, Parsed parsed) throws ParseException { Ladder> ladder = parsed.state.ladder; Iterator iter = ladder.peek(); - if(iter==null) { + if (iter==null) { List list = data(t); - if(list.isEmpty() && parsed.state.smallest) { + if (list.isEmpty() && parsed.state.smallest) { ladder.push(DONE_ITERATOR); } else { ladder.push(new ListIterator(list)); @@ -59,24 +59,24 @@ public abstract class FieldArray extends Marshal { Iterator memIter = ladder.peek(); ListIterator mems = (ListIterator)iter; S mem; - if(memIter==null) { + if (memIter==null) { mem=mems.next(); - } else if(!DONE_ITERATOR.equals(memIter)) { + } else if (!DONE_ITERATOR.equals(memIter)) { mem=mems.peek(); - } else if(iter.hasNext()) { + } else if (iter.hasNext()) { mem=null; ladder.push(null); } else { mem=null; } - if(mem!=null) { + if (mem!=null) { parsed.isString=dataWriter.write(mem, parsed.sb); parsed.event = NEXT; } ladder.descend(); - if(mem==null) { - if(iter.hasNext()) { + if (mem==null) { + if (iter.hasNext()) { parsed.event = NEXT; } else { parsed.event = END_ARRAY; 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 384e0c98..9c64e83d 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 @@ -44,9 +44,9 @@ public abstract class ObjArray extends Marshal { public Parsed parse(T t, Parsed parsed) throws ParseException { Ladder> ladder = parsed.state.ladder; Iterator iter = ladder.peek(); - if(iter==null) { + if (iter==null) { List list = data(t); - if(list.isEmpty() && parsed.state.smallest) { + if (list.isEmpty() && parsed.state.smallest) { ladder.push(DONE_ITERATOR); } else { ladder.push(new ListIterator(list)); @@ -58,22 +58,22 @@ public abstract class ObjArray extends Marshal { Iterator memIter = ladder.peek(); ListIterator mems = (ListIterator)iter; S mem; - if(memIter==null) { + if (memIter==null) { mem=mems.next(); - } else if(!DONE_ITERATOR.equals(memIter)) { + } else if (!DONE_ITERATOR.equals(memIter)) { mem=mems.peek(); - } else if(iter.hasNext()) { + } else if (iter.hasNext()) { mem=null; ladder.push(null); } else { mem=null; } - if(mem!=null) + if (mem!=null) parsed = subMarshaller.parse(mem, parsed); ladder.descend(); - if(mem==null) { - if(iter.hasNext()) { + if (mem==null) { + if (iter.hasNext()) { parsed.event = NEXT; } else { parsed.event = END_ARRAY; 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 31e214b5..d96a44d0 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 @@ -47,9 +47,9 @@ public abstract class ObjMarshal extends Marshal { */ @SuppressWarnings("unchecked") protected void add(Marshal pm) { - if(pml==null) { + if (pml==null) { pml = new Marshal[Ladder.DEFAULT_INIT_SIZE]; - } else if(end>pml.length) { + } 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); @@ -66,8 +66,8 @@ public abstract class ObjMarshal extends Marshal { 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) { + if (iter==null) { + if (pml.length>0) { ladder.push(new FieldsIterator()); parsed.event = START_OBJ; } else { @@ -78,22 +78,22 @@ public abstract class ObjMarshal extends Marshal { ladder.ascend(); // look at field info Iterator currFieldIter = ladder.peek(); Marshal marshal; - if(currFieldIter==null) { + if (currFieldIter==null) { marshal=fields.next(); - } else if(!DONE_ITERATOR.equals(currFieldIter)) { + } else if (!DONE_ITERATOR.equals(currFieldIter)) { marshal=fields.peek(); - if(marshal==null && fields.hasNext())marshal=fields.next(); - } else if(fields.hasNext()) { + if (marshal==null && fields.hasNext())marshal=fields.next(); + } else if (fields.hasNext()) { marshal=fields.next(); ladder.push(null); } else { marshal=null; } - if(marshal!=null) + if (marshal!=null) parsed = marshal.parse(in, parsed); ladder.descend(); - if(marshal==null || parsed.event==NONE) { + if (marshal==null || parsed.event==NONE) { parsed.event = END_OBJ; ladder.push(DONE_ITERATOR); } @@ -111,7 +111,7 @@ public abstract class ObjMarshal extends Marshal { @Override public Marshal next() { - if(!hasNext()) { + if (!hasNext()) { throw new NoSuchElementException(); } return pml[++idx]; 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 3e12f594..67565122 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 @@ -90,7 +90,7 @@ public class JU_FromJSON { tt.done(); } report.glean(trans,Env.JSON); - } while(report.go()); + } while (report.go()); String result = sbw.toString(); System.out.println(result); @@ -120,7 +120,7 @@ public class JU_FromJSON { tt.done(); } report.glean(trans,Env.JSON); - } while(report.go()); + } while (report.go()); report.report(sbw); System.out.println(sbw.toString()); @@ -147,7 +147,7 @@ public class JU_FromJSON { tt.done(); } report.glean(trans,Env.JSON); - } while(report.go()); + } while (report.go()); report.report(sbw); System.out.println(sbw.toString()); @@ -175,7 +175,7 @@ public class JU_FromJSON { tt.done(); } report.glean(trans,Env.JSON); - } while(report.go()); + } while (report.go()); report.report(sbw); System.out.println(sbw.toString()); @@ -218,7 +218,7 @@ public class JU_FromJSON { tt.done(); } report.glean(trans,Env.XML); - } while(report.go()); + } while (report.go()); report.report(sbw); System.out.println(sbw.toString()); @@ -260,7 +260,7 @@ public class JU_FromJSON { tt.done(); } report.glean(trans,Env.XML); - } while(report.go()); + } 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_FromXML.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_FromXML.java index 2a4e3d2d..4fefe622 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 @@ -100,7 +100,7 @@ public class JU_FromXML { tt.done(); } report.glean(trans,Env.XML); - } while(report.go()); + } while (report.go()); report.report(sbw); System.out.println(sbw.toString()); @@ -127,7 +127,7 @@ public class JU_FromXML { tt.done(); } report.glean(trans,Env.XML); - } while(report.go()); + } while (report.go()); report.report(sbw); System.out.println(sbw.toString()); @@ -136,7 +136,7 @@ public class JU_FromXML { @Test public void warmup() throws Exception { - if(ITERATIONS>20) { + if (ITERATIONS>20) { System.out.println("*** Warmup JAXB ***"); JAXBumar jaxbUmar = new JAXBumar(LargerData.class); @@ -170,7 +170,7 @@ public class JU_FromXML { all.done(); } report.glean(trans,Env.XML); - } while(report.go()); + } while (report.go()); report.report(sbw); System.out.println(sbw.toString()); @@ -209,7 +209,7 @@ public class JU_FromXML { all.done(); } report.glean(trans,Env.XML); - } while(report.go()); + } while (report.go()); report.report(sbw); System.out.println(sbw.toString()); } @@ -225,7 +225,7 @@ public class JU_FromXML { Trans trans = EnvFactory.newTrans(); LargerData ld; - for(int i=0;i20) { + if (ITERATIONS>20) { m = trans.auditTrail(0,null); } else { m = trans.auditTrail(0, sbw.getBuffer()); 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 9ab06e7c..af58ea57 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 @@ -123,7 +123,7 @@ public class JU_JSON { System.out.println(sw); String result = sw.toString(); - if(!result.equals(cmp)) { + if (!result.equals(cmp)) { sw.getBuffer().setLength(0); new OutRaw().extract(new StringReader(str), sw, in); System.out.println(sw); 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 229f1bf4..fd6142b1 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 @@ -32,22 +32,22 @@ public class JU_Ladder { public void test() { Ladder ladder = new Ladder(); - for(int i=0;i<30;++i) { - for(int j=0;j 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()); + } while (report.go()); report.report(sbw); System.out.println(sbw); 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 de1b5500..a0847f4c 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 @@ -95,7 +95,7 @@ public class JU_Saved { tt.done(); } report.glean(trans,1,2,3,4); - } while(report.go()); + } 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_Struct.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Struct.java index 7e767e5d..40c41596 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 @@ -57,7 +57,7 @@ public class JU_Struct { // Setter setter = jaxSet.setter("id"); // setter.set(sd, "Your ID"); // -// for(Entry> es : jaxSet.getters()) { +// for (Entry> es : jaxSet.getters()) { // System.out.print(es.getKey()); // System.out.print(' '); // System.out.println(es.getValue().get(sd)); 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 032f9f1c..2aca5f52 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 @@ -120,9 +120,9 @@ public class JU_Types { Multi multi = new Multi(); MultiMarshal pmulti = new MultiMarshal(); - for(int i=0;i<10;++i) { + for (int i=0;i<10;++i) { System.out.println("===== Multi Iteration " + i + " ====="); - if(i>0) { + if (i>0) { multi.getSingle().add(setSData()); } System.out.println(" ===== RAW ====="); @@ -151,9 +151,9 @@ public class JU_Types { Multi multi = new Multi(); DocMarshal doc = DocMarshal.root(new MultiMarshal()); - for(int i=0;i<3;++i) { + for (int i=0;i<3;++i) { System.out.println("===== Multi Iteration " + i + " ====="); - if(i>0) { + if (i>0) { multi.getSingle().add(setSData()); } System.out.println(" ===== RAW ====="); @@ -194,14 +194,14 @@ public class JU_Types { Trans trans = env.newTrans(); RosettaData data = df.newData(trans); // Prime pump - for(int i=0;i<100;++i) { + 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 p = prs.newParsed(); - while((p = prs.parse(in,p.reuse())).valid()) { + while ((p = prs.parse(in,p.reuse())).valid()) { switch(p.event) { case Parse.START_OBJ: ipw.append("Start Object "); @@ -71,9 +71,9 @@ public class OutDump extends Out{ } private void printData(IndentPrintWriter ipw, Parsed parsed) { - if(parsed.hasData()) { + if (parsed.hasData()) { ipw.append("Data:["); - if(parsed.hasName()) { + if (parsed.hasName()) { ipw.append(parsed.name); ipw.append(" : "); } 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 df4fec07..acb33010 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 @@ -46,7 +46,7 @@ public class Report { 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 void replay(State state, Trans trans,Writer w, String theme) throws IOException, APIException { - if(thematic!=null) { + if (thematic!=null) { theme = thematic.themeResolve(theme); } /* Theme @@ -87,7 +87,7 @@ public abstract class CacheGen> { int i=0; @SuppressWarnings("unchecked") Section[] reverse = new Section[sections.size()]; - for(Section section : sections) { + 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); @@ -97,7 +97,7 @@ public abstract class CacheGen> { reverse[i++]=s; } - for(--i;i>=0;--i) { + for (--i;i>=0;--i) { reverse[i].back(w); } w.flush(); @@ -116,7 +116,7 @@ public abstract class CacheGen> { // Clone Dynamic to make Thread Safe Dynamic d = new Dynamic(indent,code); buff.setIndent(indent); - if(code instanceof DynamicCode) { + if (code instanceof DynamicCode) { buff.run(state,trans,Cache.Null.singleton(), (DynamicCode)code); } else { buff.run((Cache)Cache.Null.singleton(), code); 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 7b0a4263..b68ad6e5 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 @@ -61,7 +61,7 @@ public class XGen> { } protected void prettyln(PrintWriter pw) { - if(pretty)pw.println(); + if (pretty)pw.println(); } public RT leaf(Mark mark, String tag, String ... args) { @@ -110,10 +110,10 @@ public class XGen> { back.append(tag); back.append('>'); - if(pretty) { - if(mark!=null && mark.comment!=null) { + 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) { + for (int i = fi+backSB.length();i<=COMMENT_COLUMN;++i) { back.append(' '); } back.append(""); } forward.inc(); - if(!oneLine) { + if (!oneLine) { forward.println(); } back.println(); } - if(mark!=null)mark.spot = backStack.size(); + if (mark!=null)mark.spot = backStack.size(); backStack.push(new Back(backSB.toString(),true, false)); backSB.setLength(0); return (RT)this; @@ -143,7 +143,7 @@ public class XGen> { forward.append(tag); addAttrs(attrs); forward.append(" />"); - if(pretty) { + if (pretty) { forward.println(); } return (RT)this; @@ -157,7 +157,7 @@ public class XGen> { @SuppressWarnings("unchecked") public RT xml(String txt) { - for(int i=0; i> { @SuppressWarnings("unchecked") public RT textCR(int tabs, String txt) { - for(int i=0;i> { int size = backStack.size(); Back c; boolean println = false; - for(int i=mark==null?0:mark.spot;i> { public RT end() { Mark mark = new Mark(); mark.spot=backStack.size()-1; - if(mark.spot<0)mark.spot=0; + if (mark.spot<0)mark.spot=0; return end(mark); } public RT end(int i) { Mark mark = new Mark(); mark.spot=backStack.size()-i; - if(mark.spot<0)mark.spot=0; + if (mark.spot<0)mark.spot=0; return end(mark); } @@ -250,9 +250,9 @@ public class XGen> { } protected void addAttrs(String[] attrs) { - if(attrs!=null) { - for(String attr : attrs) { - if(attr!=null && attr.length()>0) { + if (attrs!=null) { + for (String attr : attrs) { + if (attr!=null && attr.length()>0) { forward.append(' '); String[] split = attr.split("=",2); switch(split.length) { @@ -276,7 +276,7 @@ public class XGen> { @SuppressWarnings("unchecked") public RT comment(String string) { - if(pretty) { + if (pretty) { forward.print(""); 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 16ac60ae..846ab5a1 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 @@ -121,13 +121,13 @@ public class HTML4Gen extends HTMLGen { // @Override // protected void importCSS(Imports imports) { -// if(imports.css.size()==1) { +// if (imports.css.size()==1) { // cssInline(imports.css.get(0)); // } else { // text("