From 759ac5f42c6aff901dbeede4fbf1a1d2e08cad0f Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 4 Dec 2019 19:43:32 +0100 Subject: common EGIZ code-style refactoring --- checks/checkstyleSuppress.xml | 9 + checks/egiz_checks.xml | 219 +++ checks/egiz_pmd_checks.xml | 99 ++ .../eaaf/core/api/gui/IVelocityGuiFormBuilder.java | 103 +- .../idp/process/ExpressionEvaluationContext.java | 56 +- .../core/api/idp/process/ExpressionEvaluator.java | 65 +- .../eaaf/core/api/idp/process/ProcessEngine.java | 210 ++- .../api/idp/process/ProcessInstanceStoreDAO.java | 71 - .../api/idp/process/ProcessInstanceStoreDao.java | 55 + .../at/gv/egiz/eaaf/core/api/idp/process/Task.java | 63 +- .../gv/egiz/eaaf/core/api/utils/IJsonMapper.java | 71 +- .../eaaf/core/impl/data/SLOInformationImpl.java | 355 ++--- .../gui/AbstractGUIFormBuilderConfiguration.java | 179 --- .../gui/AbstractGuiFormBuilderConfiguration.java | 195 +++ .../gui/AbstractVelocityGUIFormBuilderImpl.java | 242 ---- .../gui/AbstractVelocityGuiFormBuilderImpl.java | 250 ++++ .../core/impl/gui/velocity/VelocityLogAdapter.java | 176 +-- .../core/impl/gui/velocity/VelocityProvider.java | 178 +-- .../eaaf/core/impl/idp/AuthenticationData.java | 1052 +++++++------- .../impl/idp/EAAFCoreSpringResourceProvider.java | 54 - .../impl/idp/EaafCoreSpringResourceProvider.java | 47 + .../eaaf/core/impl/idp/EidAuthenticationData.java | 224 +-- .../idp/auth/AbstractAuthenticationManager.java | 704 +++++----- .../eaaf/core/impl/idp/auth/RequestStorage.java | 414 +++--- .../builder/AbstractAuthenticationDataBuilder.java | 1443 ++++++++++---------- .../core/impl/idp/auth/builder/BPKBuilder.java | 302 ---- .../core/impl/idp/auth/builder/BpkBuilder.java | 312 +++++ .../impl/idp/auth/data/AuthProcessDataWrapper.java | 516 +++---- .../eaaf/core/impl/idp/auth/data/IdentityLink.java | 453 +++--- .../data/SimpleIdentityLinkAssertionParser.java | 360 ++--- .../idp/auth/modules/AbstractAuthServletTask.java | 479 ++++--- .../impl/idp/auth/modules/ModuleRegistration.java | 290 ++-- .../services/ProtocolAuthenticationService.java | 992 +++++++------- .../builder/SimpleStringAttributeGenerator.java | 110 +- .../builder/attributes/BPKAttributeBuilder.java | 123 -- .../attributes/BirthdateAttributeBuilder.java | 101 +- .../builder/attributes/BpkAttributeBuilder.java | 94 ++ .../impl/idp/builder/attributes/EIDCcsURL.java | 44 - .../idp/builder/attributes/EIDEIDTokenBuilder.java | 69 - .../EIDEncryptedSourceIdAttributeBuilder.java | 58 - .../EIDEncryptedSourceIdTypeAttributeBuilder.java | 58 - .../builder/attributes/EIDIdentityLinkBuilder.java | 78 -- .../EIDIssuingNationAttributeBuilder.java | 60 - .../attributes/EIDSectorForIDAttributeBuilder.java | 61 - .../builder/attributes/EIDSignerCertificate.java | 80 -- .../impl/idp/builder/attributes/EIDSourcePIN.java | 65 - .../idp/builder/attributes/EIDSourcePINType.java | 59 - .../EIDeIDASQAALevelAttributeBuilder.java | 56 - .../impl/idp/builder/attributes/EidCcsUrl.java | 46 + .../idp/builder/attributes/EidEidTokenBuilder.java | 66 + .../EidEidasQaaLevelAttributeBuilder.java | 52 + .../EidEncryptedSourceIdAttributeBuilder.java | 54 + .../EidEncryptedSourceIdTypeAttributeBuilder.java | 55 + .../builder/attributes/EidIdentityLinkBuilder.java | 71 + .../EidIdentityStatusLevelAttributeBuiler.java | 73 +- .../EidIssuingNationAttributeBuilder.java | 54 + .../attributes/EidSectorForIdAttributeBuilder.java | 57 + .../builder/attributes/EidSignerCertificate.java | 78 ++ .../impl/idp/builder/attributes/EidSourcePin.java | 61 + .../idp/builder/attributes/EidSourcePinType.java | 55 + .../attributes/GivenNameAttributeBuilder.java | 86 +- .../impl/idp/builder/attributes/PVPMETADATA.java | 32 - .../attributes/PVPVersionAttributeBuilder.java | 51 - .../attributes/PrincipalNameAttributeBuilder.java | 92 +- .../impl/idp/builder/attributes/PvpMetadata.java | 27 + .../attributes/PvpVersionAttributeBuilder.java | 47 + .../attributes/SPCountryCodeAttributeBuilder.java | 59 - .../attributes/SPFriendlyNameAttributeBuilder.java | 57 - .../attributes/SPUniqueIdAttributeBuilder.java | 57 - .../idp/builder/attributes/SPUsesMandates.java | 55 - .../attributes/SpCountryCodeAttributeBuilder.java | 55 + .../attributes/SpFriendlyNameAttributeBuilder.java | 51 + .../attributes/SpUniqueIdAttributeBuilder.java | 51 + .../idp/builder/attributes/SpUsesMandates.java | 50 + .../impl/idp/conf/AbstractConfigurationImpl.java | 437 +++--- .../conf/AbstractSpringBootConfigurationImpl.java | 385 +++--- .../core/impl/idp/conf/SPConfigurationImpl.java | 191 --- .../core/impl/idp/conf/SpConfigurationImpl.java | 193 +++ .../impl/idp/controller/AbstractController.java | 394 +++--- .../AbstractProcessEngineSignalController.java | 190 ++- .../controller/ProtocolFinalizationController.java | 259 ++-- .../impl/idp/controller/protocols/RequestImpl.java | 920 ++++++------- .../tasks/AbstractLocaleAuthServletTask.java | 144 +- .../tasks/FinalizeAuthenticationTask.java | 116 +- .../tasks/RestartAuthProzessManagement.java | 197 +-- .../impl/idp/process/ExecutionContextImpl.java | 188 ++- .../process/ExpressionEvaluationContextImpl.java | 89 +- .../impl/idp/process/ProcessDefinitionParser.java | 430 +++--- .../process/ProcessDefinitionParserException.java | 83 +- .../core/impl/idp/process/ProcessEngineImpl.java | 968 ++++++------- .../core/impl/idp/process/ProcessInstance.java | 337 +++-- .../impl/idp/process/ProcessInstanceState.java | 81 +- .../impl/idp/process/dao/ProcessInstanceStore.java | 138 +- .../process/dao/ProcessInstanceStoreDAOImpl.java | 97 -- .../process/dao/ProcessInstanceStoreDaoImpl.java | 94 ++ .../eaaf/core/impl/idp/process/model/EndEvent.java | 94 +- .../impl/idp/process/model/ProcessDefinition.java | 319 +++-- .../core/impl/idp/process/model/ProcessNode.java | 144 +- .../core/impl/idp/process/model/StartEvent.java | 100 +- .../eaaf/core/impl/idp/process/model/TaskInfo.java | 195 ++- .../core/impl/idp/process/model/Transition.java | 258 ++-- .../process/spring/SpringExpressionEvaluator.java | 105 +- .../springweb/AbstractAuthSourceServlet.java | 217 ++- .../impl/idp/process/springweb/AbstractTask.java | 177 ++- .../springweb/SpringWebExpressionEvaluator.java | 232 ++-- .../core/impl/logging/DummyRevisionsLogger.java | 100 +- .../core/impl/logging/DummyStatisticLogger.java | 104 +- .../at/gv/egiz/eaaf/core/impl/utils/DOMUtils.java | 1267 ----------------- .../at/gv/egiz/eaaf/core/impl/utils/DomUtils.java | 1158 ++++++++++++++++ .../core/impl/utils/EAAFDomEntityResolver.java | 128 -- .../core/impl/utils/EaafDomEntityResolver.java | 118 ++ .../gv/egiz/eaaf/core/impl/utils/XPathUtils.java | 593 ++++---- ...iz.components.spring.api.SpringResourceProvider | 2 +- .../at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder | 22 +- eaaf_core/src/main/resources/eaaf_core.beans.xml | 87 +- .../idp/auth/AuthenticationDataBuilderTest.java | 291 ++-- .../eaaf/core/impl/idp/auth/DummyAuthManager.java | 23 +- .../core/impl/idp/auth/DummyHttpClientFactory.java | 20 +- .../idp/auth/TestAuthenticationDataBuilder.java | 90 +- .../attributes/AbstractAttributeBuilderTest.java | 209 ++- .../auth/attributes/BirthdayAttrBuilderTest.java | 40 +- .../auth/attributes/FamilyNameAttrBuilderTest.java | 110 +- .../auth/attributes/GivenNameAttrBuilderTest.java | 110 +- .../impl/idp/module/test/DummyConfiguration.java | 147 +- .../idp/module/test/DummyProtocolAuthService.java | 138 +- .../impl/idp/module/test/DummySPConfiguration.java | 21 - .../impl/idp/module/test/DummySpConfiguration.java | 23 + .../core/impl/idp/module/test/TestRequestImpl.java | 679 ++++----- .../spring/test/DummyTransactionStorage.java | 335 +++-- .../spring/test/ExpressionContextAdapter.java | 100 +- .../impl/idp/process/spring/test/SimplePojo.java | 85 +- .../SpringExpressionAwareProcessEngineTest.java | 283 ++-- .../spring/test/SpringExpressionEvaluatorTest.java | 96 +- .../spring/test/task/CreateSAML1AssertionTask.java | 87 -- .../spring/test/task/CreateSaml1AssertionTask.java | 82 ++ .../spring/test/task/GetIdentityLinkTask.java | 85 +- .../process/spring/test/task/SelectBKUTask.java | 63 - .../process/spring/test/task/SelectBkuTask.java | 55 + .../spring/test/task/SignAuthBlockTask.java | 88 +- .../spring/test/task/ValidateIdentityLinkTask.java | 69 +- .../test/task/ValidateSignedAuthBlockTask.java | 74 +- .../test/BooleanStringExpressionEvaluator.java | 60 +- .../core/impl/idp/process/test/HalloWeltTask.java | 58 +- .../core/impl/idp/process/test/HelloWorldTask.java | 58 +- .../process/test/ProcessDefinitionParserTest.java | 280 ++-- .../impl/idp/process/test/ProcessEngineTest.java | 416 +++--- .../impl/idp/process/test/StopProcessFlagTask.java | 62 +- .../impl/idp/process/test/ThrowExceptionTask.java | 62 +- .../eaaf/core/impl/utils/KeyValueUtilsTest.java | 851 ++++++------ .../resources/SpringTest-context_authManager.xml | 89 +- .../resources/SpringTest-context_eaaf_core.xml | 32 +- eaaf_core/src/test/resources/log4j.xml | 26 +- ...ingExpressionAwareProcessEngineTest-context.xml | 8 +- eaaf_core_api/pom.xml | 128 +- .../eaaf/core/api/IGarbageCollectorProcessing.java | 51 +- .../eaaf/core/api/IPostStartupInitializable.java | 53 +- .../java/at/gv/egiz/eaaf/core/api/IRequest.java | 490 ++++--- .../at/gv/egiz/eaaf/core/api/IRequestStorage.java | 123 +- .../at/gv/egiz/eaaf/core/api/IStatusMessenger.java | 143 +- .../eaaf/core/api/data/EAAFConfigConstants.java | 32 +- .../gv/egiz/eaaf/core/api/data/EAAFConstants.java | 129 +- .../gv/egiz/eaaf/core/api/data/EAAFEventCodes.java | 2 +- .../eaaf/core/api/data/ExceptionContainer.java | 150 +- .../api/data/ExtendedPVPAttributeDefinitions.java | 73 +- .../egiz/eaaf/core/api/data/ILoALevelMapper.java | 78 +- .../core/api/data/PVPAttributeDefinitions.java | 671 ++++----- .../eaaf/core/api/data/XMLNamespaceConstants.java | 346 ++--- .../gv/egiz/eaaf/core/api/gui/GroupDefinition.java | 58 +- .../core/api/gui/IGUIBuilderConfiguration.java | 60 - .../api/gui/IGUIBuilderConfigurationFactory.java | 54 - .../gv/egiz/eaaf/core/api/gui/IGUIFormBuilder.java | 74 - .../core/api/gui/IGuiBuilderConfiguration.java | 55 + .../api/gui/IGuiBuilderConfigurationFactory.java | 53 + .../gv/egiz/eaaf/core/api/gui/IGuiFormBuilder.java | 70 + .../core/api/gui/ISpringMVCGUIFormBuilder.java | 5 - .../core/api/gui/ISpringMvcGuiFormBuilder.java | 5 + .../api/gui/IVelocityGUIBuilderConfiguration.java | 22 - .../api/gui/IVelocityGuiBuilderConfiguration.java | 23 + .../api/gui/ModifyableGuiBuilderConfiguration.java | 79 +- .../core/api/idp/EAAFAuthProcessDataConstants.java | 46 - .../core/api/idp/EaafAuthProcessDataConstants.java | 41 + .../java/at/gv/egiz/eaaf/core/api/idp/IAction.java | 77 +- .../egiz/eaaf/core/api/idp/IAttributeBuilder.java | 67 +- .../eaaf/core/api/idp/IAttributeGenerator.java | 88 +- .../at/gv/egiz/eaaf/core/api/idp/IAuthData.java | 442 +++--- .../core/api/idp/IAuthenticationDataBuilder.java | 47 +- .../gv/egiz/eaaf/core/api/idp/IConfiguration.java | 133 +- .../eaaf/core/api/idp/IConfigurationWithSP.java | 98 +- .../at/gv/egiz/eaaf/core/api/idp/IEidAuthData.java | 76 +- .../eaaf/core/api/idp/IExtendedConfiguration.java | 32 +- .../at/gv/egiz/eaaf/core/api/idp/IModulInfo.java | 140 +- .../eaaf/core/api/idp/IPVPAttributeBuilder.java | 33 - .../eaaf/core/api/idp/IPvpAttributeBuilder.java | 26 + .../egiz/eaaf/core/api/idp/ISPConfiguration.java | 168 --- .../egiz/eaaf/core/api/idp/IspConfiguration.java | 163 +++ .../core/api/idp/auth/IAuthenticationManager.java | 160 ++- .../egiz/eaaf/core/api/idp/auth/ISSOManager.java | 130 -- .../egiz/eaaf/core/api/idp/auth/ISsoManager.java | 127 ++ .../idp/auth/data/IAuthProcessDataContainer.java | 331 +++-- .../eaaf/core/api/idp/auth/data/IIdentityLink.java | 331 ++--- .../eaaf/core/api/idp/auth/modules/AuthModule.java | 97 +- .../services/IProtocolAuthenticationService.java | 144 +- .../core/api/idp/process/ExecutionContext.java | 160 ++- .../core/api/idp/slo/ISLOInformationContainer.java | 93 -- .../core/api/idp/slo/ISloInformationContainer.java | 75 + .../core/api/idp/slo/SLOInformationInterface.java | 104 -- .../core/api/idp/slo/SloInformationInterface.java | 80 ++ .../eaaf/core/api/logging/IRevisionLogger.java | 110 +- .../eaaf/core/api/logging/IStatisticLogger.java | 58 +- .../eaaf/core/api/storage/ITransactionStorage.java | 243 ++-- .../utils/IPendingRequestIdGenerationStrategy.java | 59 +- .../core/exceptions/AttributeBuilderException.java | 49 +- .../core/exceptions/AttributePolicyException.java | 68 +- .../exceptions/AuthnRequestValidatorException.java | 156 ++- .../exceptions/EAAFAuthenticationException.java | 45 - .../eaaf/core/exceptions/EAAFBuilderException.java | 44 - .../exceptions/EAAFConfigurationException.java | 44 - .../egiz/eaaf/core/exceptions/EAAFException.java | 66 - .../eaaf/core/exceptions/EAAFIDPException.java | 46 - .../core/exceptions/EAAFIllegalStateException.java | 44 - .../core/exceptions/EAAFJsonMapperException.java | 16 - .../eaaf/core/exceptions/EAAFParserException.java | 44 - .../core/exceptions/EAAFProtocolException.java | 41 - .../eaaf/core/exceptions/EAAFSSOException.java | 41 - .../eaaf/core/exceptions/EAAFServiceException.java | 30 - .../eaaf/core/exceptions/EAAFStorageException.java | 42 - .../exceptions/EaafAuthenticationException.java | 38 + .../eaaf/core/exceptions/EaafBuilderException.java | 34 + .../exceptions/EaafConfigurationException.java | 35 + .../egiz/eaaf/core/exceptions/EaafException.java | 89 ++ .../eaaf/core/exceptions/EaafIdpException.java | 36 + .../core/exceptions/EaafIllegalStateException.java | 37 + .../core/exceptions/EaafJsonMapperException.java | 16 + .../eaaf/core/exceptions/EaafParserException.java | 34 + .../core/exceptions/EaafProtocolException.java | 34 + .../eaaf/core/exceptions/EaafServiceException.java | 29 + .../eaaf/core/exceptions/EaafSsoException.java | 31 + .../eaaf/core/exceptions/EaafStorageException.java | 35 + .../eaaf/core/exceptions/GUIBuildException.java | 50 - .../eaaf/core/exceptions/GuiBuildException.java | 47 + .../InvalidDateFormatAttributeException.java | 53 +- .../InvalidProtocolRequestException.java | 63 +- .../NoPassivAuthenticationException.java | 52 +- .../PendingReqIdValidationException.java | 110 +- .../core/exceptions/ProcessExecutionException.java | 84 +- .../exceptions/ProtocolNotActiveException.java | 54 +- .../exceptions/ProtocolResponseExceptions.java | 16 +- .../gv/egiz/eaaf/core/exceptions/SLOException.java | 45 - .../gv/egiz/eaaf/core/exceptions/SloException.java | 36 + .../core/exceptions/TaskExecutionException.java | 120 +- .../exceptions/UnavailableAttributeException.java | 63 +- .../egiz/eaaf/core/exceptions/XPathException.java | 81 +- .../java/at/gv/egiz/eaaf/core/impl/data/Pair.java | 90 +- .../at/gv/egiz/eaaf/core/impl/data/Trible.java | 81 +- .../core/impl/logging/DummyStatusMessager.java | 89 +- .../impl/logging/LogMessageProviderFactory.java | 92 +- eaaf_core_utils/pom.xml | 211 +-- .../idp/process/support/SecureRandomHolder.java | 92 +- .../core/impl/logging/SimpleStatusMessager.java | 62 +- .../gv/egiz/eaaf/core/impl/utils/ArrayUtils.java | 62 +- .../egiz/eaaf/core/impl/utils/DataURLBuilder.java | 113 -- .../egiz/eaaf/core/impl/utils/DataUrlBuilder.java | 91 ++ .../at/gv/egiz/eaaf/core/impl/utils/FileUtils.java | 257 ++-- .../at/gv/egiz/eaaf/core/impl/utils/HTTPUtils.java | 178 --- .../eaaf/core/impl/utils/HttpClientFactory.java | 711 +++++----- .../at/gv/egiz/eaaf/core/impl/utils/HttpUtils.java | 119 ++ .../eaaf/core/impl/utils/IHttpClientFactory.java | 29 +- .../egiz/eaaf/core/impl/utils/KeyStoreUtils.java | 248 ++-- .../egiz/eaaf/core/impl/utils/KeyValueUtils.java | 697 +++++----- .../eaaf/core/impl/utils/NodeIteratorAdapter.java | 88 +- .../egiz/eaaf/core/impl/utils/NodeListAdapter.java | 64 +- .../at/gv/egiz/eaaf/core/impl/utils/Random.java | 290 ++-- .../SecurePendingRequestIdGenerationStrategy.java | 390 +++--- .../gv/egiz/eaaf/core/impl/utils/ServletUtils.java | 64 +- .../SimplePendingRequestIdGenerationStrategy.java | 58 +- .../gv/egiz/eaaf/core/impl/utils/StreamUtils.java | 177 ++- .../eaaf/core/impl/utils/TransactionIDUtils.java | 101 -- .../eaaf/core/impl/utils/TransactionIdUtils.java | 94 ++ .../at/gv/egiz/eaaf/core/impl/utils/X509Utils.java | 87 +- .../impl/logging/JUnitTestStatusMessenger.java | 97 +- .../core/impl/utils/test/KeyValueUtilsTest.java | 446 ++++++ eaaf_modules/eaaf_module_auth_sl20/pom.xml | 115 +- .../sl20/AbstractSL20AuthenticationModulImpl.java | 238 ++-- .../gv/egiz/eaaf/modules/auth/sl20/Constants.java | 123 +- .../gv/egiz/eaaf/modules/auth/sl20/EventCodes.java | 14 +- .../modules/auth/sl20/data/VerificationResult.java | 59 +- .../exceptions/SL20EidDataValidationException.java | 16 + .../auth/sl20/exceptions/SL20Exception.java | 20 +- .../sl20/exceptions/SL20SecurityException.java | 24 +- .../exceptions/SL20eIDDataValidationException.java | 16 - .../sl20/exceptions/SLCommandoBuildException.java | 17 - .../sl20/exceptions/SLCommandoParserException.java | 17 - .../sl20/exceptions/SlCommandoBuildException.java | 17 + .../sl20/exceptions/SlCommandoParserException.java | 17 + .../tasks/AbstractCreateQualEidRequestTask.java | 250 ++++ .../tasks/AbstractCreateQualeIDRequestTask.java | 227 --- .../sl20/tasks/AbstractReceiveQualEidTask.java | 344 +++++ .../sl20/tasks/AbstractReceiveQualeIDTask.java | 321 ----- .../eaaf/modules/auth/sl20/utils/IJOSETools.java | 87 -- .../eaaf/modules/auth/sl20/utils/IJoseTools.java | 84 ++ .../eaaf/modules/auth/sl20/utils/JsonMapper.java | 227 +-- .../modules/auth/sl20/utils/JsonSecurityUtils.java | 773 ++++++----- .../modules/auth/sl20/utils/SL20Constants.java | 499 +++---- .../auth/sl20/utils/SL20HttpBindingUtils.java | 90 +- .../auth/sl20/utils/SL20JSONBuilderUtils.java | 640 --------- .../auth/sl20/utils/SL20JSONExtractorUtils.java | 368 ----- .../auth/sl20/utils/SL20JsonBuilderUtils.java | 731 ++++++++++ .../auth/sl20/utils/SL20JsonExtractorUtils.java | 407 ++++++ .../moasig/api/ISignatureVerificationService.java | 142 +- .../IGenericSignatureVerificationResponse.java | 112 +- .../moasig/api/data/ISchemaRessourceProvider.java | 15 +- .../data/IXMLSignatureVerificationResponse.java | 59 +- .../exceptions/MOASigServiceBuilderException.java | 14 - .../MOASigServiceConfigurationException.java | 11 - .../moasig/exceptions/MOASigServiceException.java | 26 - .../exceptions/MOASigServiceParserException.java | 14 - .../exceptions/MoaSigServiceBuilderException.java | 14 + .../MoaSigServiceConfigurationException.java | 11 + .../moasig/exceptions/MoaSigServiceException.java | 26 + .../exceptions/MoaSigServiceParserException.java | 14 + .../moasig/impl/AbstractSignatureService.java | 93 +- .../moasig/impl/MOASigSpringResourceProvider.java | 27 - .../sigverify/moasig/impl/MoaSigInitializer.java | 190 +-- .../moasig/impl/MoaSigSpringResourceProvider.java | 28 + .../moasig/impl/SignatureCreationService.java | 33 +- .../moasig/impl/SignatureVerificationService.java | 573 ++++---- .../data/GenericSignatureVerificationResponse.java | 237 ++-- .../impl/data/VerifyCMSSignatureResponse.java | 5 +- .../impl/data/VerifyXMLSignatureResponse.java | 106 +- .../parser/VerifyXMLSignatureResponseParser.java | 180 --- .../parser/VerifyXmlSignatureResponseParser.java | 192 +++ .../src/main/resources/moa-sig-service.beans.xml | 40 +- .../java/artifacts/MavenArtifactInstaller.java | 109 +- .../PVP2SProfileCoreSpringResourceProvider.java | 54 - .../at/gv/egiz/eaaf/modules/pvp2/PVPConstants.java | 139 -- .../egiz/eaaf/modules/pvp2/PVPEventConstants.java | 36 - .../Pvp2SProfileCoreSpringResourceProvider.java | 48 + .../at/gv/egiz/eaaf/modules/pvp2/PvpConstants.java | 138 ++ .../egiz/eaaf/modules/pvp2/PvpEventConstants.java | 29 + .../modules/pvp2/api/IPVP2BasicConfiguration.java | 50 - .../modules/pvp2/api/IPvo2BasicConfiguration.java | 41 + .../eaaf/modules/pvp2/api/binding/IDecoder.java | 59 +- .../eaaf/modules/pvp2/api/binding/IEncoder.java | 115 +- .../pvp2/api/message/InboundMessageInterface.java | 58 +- .../metadata/IPVPMetadataBuilderConfiguration.java | 243 ---- .../metadata/IPVPMetadataConfigurationFactory.java | 35 - .../pvp2/api/metadata/IPVPMetadataProvider.java | 61 - .../metadata/IPvpMetadataBuilderConfiguration.java | 236 ++++ .../metadata/IPvpMetadataConfigurationFactory.java | 30 + .../pvp2/api/metadata/IPvpMetadataProvider.java | 64 + .../api/metadata/IRefreshableMetadataProvider.java | 55 +- .../pvp2/api/reqattr/EAAFRequestedAttribute.java | 154 --- .../pvp2/api/reqattr/EAAFRequestedAttributes.java | 56 - .../pvp2/api/reqattr/EaafRequestedAttribute.java | 150 ++ .../pvp2/api/reqattr/EaafRequestedAttributes.java | 51 + .../api/validation/IAuthnRequestValidator.java | 48 +- .../pvp2/api/validation/ISAMLValidator.java | 35 - .../pvp2/api/validation/ISamlValidator.java | 28 + .../pvp2/exception/AttributQueryException.java | 65 +- .../exception/BindingNotSupportedException.java | 61 +- .../CredentialsNotAvailableException.java | 68 +- .../pvp2/exception/InvalidDateFormatException.java | 56 +- .../pvp2/exception/InvalidPVPRequestException.java | 40 - .../pvp2/exception/InvalidPvpRequestException.java | 30 + .../NameIDFormatNotSupportedException.java | 46 - .../NameIdFormatNotSupportedException.java | 43 + .../exception/NoMetadataInformationException.java | 57 +- .../eaaf/modules/pvp2/exception/PVP2Exception.java | 66 - .../pvp2/exception/PVP2MetadataException.java | 41 - .../eaaf/modules/pvp2/exception/Pvp2Exception.java | 55 + .../pvp2/exception/Pvp2MetadataException.java | 34 + .../pvp2/exception/QAANotAllowedException.java | 44 - .../pvp2/exception/QAANotSupportedException.java | 44 - .../pvp2/exception/QaaNotAllowedException.java | 33 + .../pvp2/exception/QaaNotSupportedException.java | 37 + .../exception/SAMLMetadataSignatureException.java | 48 - .../exception/SamlMetadataSignatureException.java | 40 + .../pvp2/exception/SchemaValidationException.java | 73 +- .../exception/SignatureValidationException.java | 83 +- .../modules/pvp2/impl/binding/PostBinding.java | 405 +++--- .../modules/pvp2/impl/binding/RedirectBinding.java | 401 +++--- .../modules/pvp2/impl/binding/SoapBinding.java | 263 ++-- .../pvp2/impl/builder/CitizenTokenBuilder.java | 233 ++-- .../pvp2/impl/builder/PVPAttributeBuilder.java | 221 --- .../pvp2/impl/builder/PVPMetadataBuilder.java | 450 ------ .../pvp2/impl/builder/PvpAttributeBuilder.java | 244 ++++ .../pvp2/impl/builder/PvpMetadataBuilder.java | 458 +++++++ .../pvp2/impl/builder/SamlAttributeGenerator.java | 153 ++- .../reqattr/EAAFExtensionImplementation.java | 36 - .../reqattr/EAAFRequestExtensionBuilder.java | 45 - .../reqattr/EAAFRequestedAttributeBuilder.java | 45 - .../reqattr/EAAFRequestedAttributeMarshaller.java | 76 -- .../EAAFRequestedAttributeUnmarshaller.java | 75 - .../reqattr/EAAFRequestedAttributesBuilder.java | 45 - .../reqattr/EAAFRequestedAttributesMarshaller.java | 31 - .../EAAFRequestedAttributesUnmarshaller.java | 45 - .../reqattr/EaafExtensionImplementation.java | 32 + .../reqattr/EaafRequestExtensionBuilder.java | 41 + .../reqattr/EaafRequestedAttributeBuilder.java | 40 + .../reqattr/EaafRequestedAttributeMarshaller.java | 69 + .../EaafRequestedAttributeUnmarshaller.java | 74 + .../reqattr/EaafRequestedAttributesBuilder.java | 41 + .../reqattr/EaafRequestedAttributesMarshaller.java | 26 + .../EaafRequestedAttributesUnmarshaller.java | 41 + .../modules/pvp2/impl/message/InboundMessage.java | 230 ++-- .../pvp2/impl/message/PVPSProfileRequest.java | 69 - .../pvp2/impl/message/PVPSProfileResponse.java | 61 - .../pvp2/impl/message/PvpSProfileRequest.java | 73 + .../pvp2/impl/message/PvpSProfileResponse.java | 59 + .../metadata/AbstractChainingMetadataProvider.java | 929 +++++++------ .../pvp2/impl/metadata/MetadataFilterChain.java | 112 +- .../pvp2/impl/metadata/SimpleMetadataProvider.java | 415 +++--- .../opensaml/HTTPPostEncoderWithOwnTemplate.java | 122 -- .../opensaml/HttpPostEncoderWithOwnTemplate.java | 123 ++ .../opensaml/KeyStoreX509CredentialAdapter.java | 79 +- .../opensaml/StringRedirectDeflateEncoder.java | 106 +- .../initialize/EAAFDefaultSAML2Bootstrap.java | 94 -- .../EAAFDefaultSecurityConfigurationBootstrap.java | 156 --- .../initialize/EaafDefaultSaml2Bootstrap.java | 87 ++ .../EaafDefaultSecurityConfigurationBootstrap.java | 141 ++ .../impl/reqattr/EAAFRequestedAttributeImpl.java | 133 -- .../impl/reqattr/EAAFRequestedAttributesImpl.java | 61 - .../impl/reqattr/EaafRequestedAttributeImpl.java | 149 ++ .../impl/reqattr/EaafRequestedAttributesImpl.java | 56 + .../impl/utils/AbstractCredentialProvider.java | 430 +++--- .../modules/pvp2/impl/utils/QAALevelVerifier.java | 104 -- .../modules/pvp2/impl/utils/QaaLevelVerifier.java | 106 ++ .../eaaf/modules/pvp2/impl/utils/SAML2Utils.java | 201 --- .../eaaf/modules/pvp2/impl/utils/Saml2Utils.java | 247 ++++ .../pvp2/impl/validation/EAAFURICompare.java | 60 - .../pvp2/impl/validation/EaafUriCompare.java | 53 + .../pvp2/impl/validation/TrustEngineFactory.java | 73 +- .../metadata/AbstractMetadataSignatureFilter.java | 266 ++-- .../metadata/PVPEntityCategoryFilter.java | 236 ---- .../metadata/PvpEntityCategoryFilter.java | 251 ++++ .../metadata/SchemaValidationFilter.java | 163 ++- .../AbstractRequestSignedSecurityPolicyRule.java | 317 ++--- .../verification/PVPAuthRequestSignedRole.java | 66 - .../verification/PVPSignedRequestPolicyRule.java | 84 -- .../verification/PvpAuthRequestSignedRole.java | 56 + .../verification/PvpSignedRequestPolicyRule.java | 82 ++ .../impl/verification/SAMLVerificationEngine.java | 207 --- .../impl/verification/SamlVerificationEngine.java | 218 +++ ...iz.components.spring.api.SpringResourceProvider | 2 +- .../src/main/resources/eaaf_pvp.beans.xml | 47 +- .../idp/PVP2SProfileIDPSpringResourceProvider.java | 54 - .../idp/Pvp2SProfileIdpSpringResourceProvider.java | 47 + .../idp/api/builder/ISubjectNameIdGenerator.java | 62 +- .../InvalidAssertionConsumerServiceException.java | 75 +- .../InvalidAssertionEncryptionException.java | 54 +- .../pvp2/idp/exception/RequestDeniedException.java | 57 +- .../idp/exception/ResponderErrorException.java | 67 +- .../exception/SAMLRequestNotSignedException.java | 50 - .../idp/exception/SAMLRequestNotSupported.java | 46 - .../exception/SamlRequestNotSignedException.java | 42 + .../idp/exception/SamlRequestNotSupported.java | 39 + .../exception/UnprovideableAttributeException.java | 56 +- .../pvp2/idp/impl/AbstractPVP2XProtocol.java | 541 -------- .../pvp2/idp/impl/AbstractPvp2XProtocol.java | 561 ++++++++ .../pvp2/idp/impl/AuthenticationAction.java | 312 +++-- .../eaaf/modules/pvp2/idp/impl/MetadataAction.java | 206 ++- .../pvp2/idp/impl/PVPSProfilePendingRequest.java | 69 - .../pvp2/idp/impl/PvpSProfilePendingRequest.java | 61 + .../pvp2/idp/impl/builder/AuthResponseBuilder.java | 234 ++-- .../idp/impl/builder/PVP2AssertionBuilder.java | 459 ------- .../idp/impl/builder/Pvp2AssertionBuilder.java | 465 +++++++ ...iz.components.spring.api.SpringResourceProvider | 2 +- .../src/main/resources/eaaf_pvp_idp.beans.xml | 35 +- eaaf_modules/eaaf_module_pvp2_sp/pom.xml | 2 +- .../api/IPVPAuthnRequestBuilderConfiguruation.java | 195 --- .../api/IPvpAuthnRequestBuilderConfiguruation.java | 187 +++ .../AssertionAttributeExtractorExeption.java | 80 +- .../sp/exception/AssertionValidationExeption.java | 75 +- .../sp/exception/AuthnRequestBuildException.java | 76 +- .../AuthnResponseValidationException.java | 77 +- .../pvp2/sp/impl/PVPAuthnRequestBuilder.java | 259 ---- .../pvp2/sp/impl/PvpAuthnRequestBuilder.java | 263 ++++ .../sp/impl/utils/AssertionAttributeExtractor.java | 641 ++++----- pom.xml | 1088 ++++++++------- 479 files changed, 36133 insertions(+), 35491 deletions(-) create mode 100644 checks/checkstyleSuppress.xml create mode 100644 checks/egiz_checks.xml create mode 100644 checks/egiz_pmd_checks.xml delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/ProcessInstanceStoreDAO.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/ProcessInstanceStoreDao.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractGUIFormBuilderConfiguration.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractGuiFormBuilderConfiguration.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractVelocityGUIFormBuilderImpl.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractVelocityGuiFormBuilderImpl.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/EAAFCoreSpringResourceProvider.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/EaafCoreSpringResourceProvider.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/builder/BPKBuilder.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/builder/BpkBuilder.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/BPKAttributeBuilder.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/BpkAttributeBuilder.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDCcsURL.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDEIDTokenBuilder.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDEncryptedSourceIdAttributeBuilder.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDEncryptedSourceIdTypeAttributeBuilder.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDIdentityLinkBuilder.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDIssuingNationAttributeBuilder.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDSectorForIDAttributeBuilder.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDSignerCertificate.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDSourcePIN.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDSourcePINType.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDeIDASQAALevelAttributeBuilder.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidCcsUrl.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidEidTokenBuilder.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidEidasQaaLevelAttributeBuilder.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidEncryptedSourceIdAttributeBuilder.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidEncryptedSourceIdTypeAttributeBuilder.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidIdentityLinkBuilder.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidIssuingNationAttributeBuilder.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidSectorForIdAttributeBuilder.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidSignerCertificate.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidSourcePin.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidSourcePinType.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/PVPMETADATA.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/PVPVersionAttributeBuilder.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/PvpMetadata.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/PvpVersionAttributeBuilder.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SPCountryCodeAttributeBuilder.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SPFriendlyNameAttributeBuilder.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SPUniqueIdAttributeBuilder.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SPUsesMandates.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SpCountryCodeAttributeBuilder.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SpFriendlyNameAttributeBuilder.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SpUniqueIdAttributeBuilder.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SpUsesMandates.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/conf/SPConfigurationImpl.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/conf/SpConfigurationImpl.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/dao/ProcessInstanceStoreDAOImpl.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/dao/ProcessInstanceStoreDaoImpl.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/utils/DOMUtils.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/utils/DomUtils.java delete mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/utils/EAAFDomEntityResolver.java create mode 100644 eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/utils/EaafDomEntityResolver.java delete mode 100644 eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/module/test/DummySPConfiguration.java create mode 100644 eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/module/test/DummySpConfiguration.java delete mode 100644 eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/CreateSAML1AssertionTask.java create mode 100644 eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/CreateSaml1AssertionTask.java delete mode 100644 eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/SelectBKUTask.java create mode 100644 eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/SelectBkuTask.java delete mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IGUIBuilderConfiguration.java delete mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IGUIBuilderConfigurationFactory.java delete mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IGUIFormBuilder.java create mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IGuiBuilderConfiguration.java create mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IGuiBuilderConfigurationFactory.java create mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IGuiFormBuilder.java delete mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/ISpringMVCGUIFormBuilder.java create mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/ISpringMvcGuiFormBuilder.java delete mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IVelocityGUIBuilderConfiguration.java create mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IVelocityGuiBuilderConfiguration.java delete mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/EAAFAuthProcessDataConstants.java create mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/EaafAuthProcessDataConstants.java delete mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IPVPAttributeBuilder.java create mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IPvpAttributeBuilder.java delete mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/ISPConfiguration.java create mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IspConfiguration.java delete mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/ISSOManager.java create mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/ISsoManager.java delete mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/slo/ISLOInformationContainer.java create mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/slo/ISloInformationContainer.java delete mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/slo/SLOInformationInterface.java create mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/slo/SloInformationInterface.java delete mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFAuthenticationException.java delete mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFBuilderException.java delete mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFConfigurationException.java delete mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFException.java delete mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFIDPException.java delete mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFIllegalStateException.java delete mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFJsonMapperException.java delete mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFParserException.java delete mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFProtocolException.java delete mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFSSOException.java delete mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFServiceException.java delete mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFStorageException.java create mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafAuthenticationException.java create mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafBuilderException.java create mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafConfigurationException.java create mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafException.java create mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafIdpException.java create mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafIllegalStateException.java create mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafJsonMapperException.java create mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafParserException.java create mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafProtocolException.java create mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafServiceException.java create mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafSsoException.java create mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafStorageException.java delete mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/GUIBuildException.java create mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/GuiBuildException.java delete mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/SLOException.java create mode 100644 eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/SloException.java delete mode 100644 eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/DataURLBuilder.java create mode 100644 eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/DataUrlBuilder.java delete mode 100644 eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/HTTPUtils.java create mode 100644 eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/HttpUtils.java delete mode 100644 eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/TransactionIDUtils.java create mode 100644 eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/TransactionIdUtils.java create mode 100644 eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/impl/utils/test/KeyValueUtilsTest.java create mode 100644 eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SL20EidDataValidationException.java delete mode 100644 eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SL20eIDDataValidationException.java delete mode 100644 eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SLCommandoBuildException.java delete mode 100644 eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SLCommandoParserException.java create mode 100644 eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SlCommandoBuildException.java create mode 100644 eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SlCommandoParserException.java create mode 100644 eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/tasks/AbstractCreateQualEidRequestTask.java delete mode 100644 eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/tasks/AbstractCreateQualeIDRequestTask.java create mode 100644 eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/tasks/AbstractReceiveQualEidTask.java delete mode 100644 eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/tasks/AbstractReceiveQualeIDTask.java delete mode 100644 eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/IJOSETools.java create mode 100644 eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/IJoseTools.java delete mode 100644 eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20JSONBuilderUtils.java delete mode 100644 eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20JSONExtractorUtils.java create mode 100644 eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20JsonBuilderUtils.java create mode 100644 eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20JsonExtractorUtils.java delete mode 100644 eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MOASigServiceBuilderException.java delete mode 100644 eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MOASigServiceConfigurationException.java delete mode 100644 eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MOASigServiceException.java delete mode 100644 eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MOASigServiceParserException.java create mode 100644 eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MoaSigServiceBuilderException.java create mode 100644 eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MoaSigServiceConfigurationException.java create mode 100644 eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MoaSigServiceException.java create mode 100644 eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MoaSigServiceParserException.java delete mode 100644 eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/MOASigSpringResourceProvider.java create mode 100644 eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/MoaSigSpringResourceProvider.java delete mode 100644 eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/parser/VerifyXMLSignatureResponseParser.java create mode 100644 eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/parser/VerifyXmlSignatureResponseParser.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/PVP2SProfileCoreSpringResourceProvider.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/PVPConstants.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/PVPEventConstants.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/Pvp2SProfileCoreSpringResourceProvider.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/PvpConstants.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/PvpEventConstants.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/IPVP2BasicConfiguration.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/IPvo2BasicConfiguration.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IPVPMetadataBuilderConfiguration.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IPVPMetadataConfigurationFactory.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IPVPMetadataProvider.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IPvpMetadataBuilderConfiguration.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IPvpMetadataConfigurationFactory.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IPvpMetadataProvider.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/reqattr/EAAFRequestedAttribute.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/reqattr/EAAFRequestedAttributes.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/reqattr/EaafRequestedAttribute.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/reqattr/EaafRequestedAttributes.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/validation/ISAMLValidator.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/validation/ISamlValidator.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/InvalidPVPRequestException.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/InvalidPvpRequestException.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/NameIDFormatNotSupportedException.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/NameIdFormatNotSupportedException.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/PVP2Exception.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/PVP2MetadataException.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/Pvp2Exception.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/Pvp2MetadataException.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/QAANotAllowedException.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/QAANotSupportedException.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/QaaNotAllowedException.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/QaaNotSupportedException.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/SAMLMetadataSignatureException.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/SamlMetadataSignatureException.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/PVPAttributeBuilder.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/PVPMetadataBuilder.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/PvpAttributeBuilder.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/PvpMetadataBuilder.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFExtensionImplementation.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestExtensionBuilder.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestedAttributeBuilder.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestedAttributeMarshaller.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestedAttributeUnmarshaller.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestedAttributesBuilder.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestedAttributesMarshaller.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestedAttributesUnmarshaller.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafExtensionImplementation.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestExtensionBuilder.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestedAttributeBuilder.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestedAttributeMarshaller.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestedAttributeUnmarshaller.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestedAttributesBuilder.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestedAttributesMarshaller.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestedAttributesUnmarshaller.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/message/PVPSProfileRequest.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/message/PVPSProfileResponse.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/message/PvpSProfileRequest.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/message/PvpSProfileResponse.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/HTTPPostEncoderWithOwnTemplate.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/HttpPostEncoderWithOwnTemplate.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/initialize/EAAFDefaultSAML2Bootstrap.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/initialize/EAAFDefaultSecurityConfigurationBootstrap.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/initialize/EaafDefaultSaml2Bootstrap.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/initialize/EaafDefaultSecurityConfigurationBootstrap.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/reqattr/EAAFRequestedAttributeImpl.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/reqattr/EAAFRequestedAttributesImpl.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/reqattr/EaafRequestedAttributeImpl.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/reqattr/EaafRequestedAttributesImpl.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/utils/QAALevelVerifier.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/utils/QaaLevelVerifier.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/utils/SAML2Utils.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/utils/Saml2Utils.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/EAAFURICompare.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/EaafUriCompare.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/metadata/PVPEntityCategoryFilter.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/metadata/PvpEntityCategoryFilter.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/PVPAuthRequestSignedRole.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/PVPSignedRequestPolicyRule.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/PvpAuthRequestSignedRole.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/PvpSignedRequestPolicyRule.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/SAMLVerificationEngine.java create mode 100644 eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/SamlVerificationEngine.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/PVP2SProfileIDPSpringResourceProvider.java create mode 100644 eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/Pvp2SProfileIdpSpringResourceProvider.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/SAMLRequestNotSignedException.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/SAMLRequestNotSupported.java create mode 100644 eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/SamlRequestNotSignedException.java create mode 100644 eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/SamlRequestNotSupported.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/AbstractPVP2XProtocol.java create mode 100644 eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/AbstractPvp2XProtocol.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/PVPSProfilePendingRequest.java create mode 100644 eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/PvpSProfilePendingRequest.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/builder/PVP2AssertionBuilder.java create mode 100644 eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/builder/Pvp2AssertionBuilder.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/api/IPVPAuthnRequestBuilderConfiguruation.java create mode 100644 eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/api/IPvpAuthnRequestBuilderConfiguruation.java delete mode 100644 eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/impl/PVPAuthnRequestBuilder.java create mode 100644 eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/impl/PvpAuthnRequestBuilder.java diff --git a/checks/checkstyleSuppress.xml b/checks/checkstyleSuppress.xml new file mode 100644 index 00000000..68a23260 --- /dev/null +++ b/checks/checkstyleSuppress.xml @@ -0,0 +1,9 @@ + + + + + + + \ No newline at end of file diff --git a/checks/egiz_checks.xml b/checks/egiz_checks.xml new file mode 100644 index 00000000..af852811 --- /dev/null +++ b/checks/egiz_checks.xml @@ -0,0 +1,219 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/checks/egiz_pmd_checks.xml b/checks/egiz_pmd_checks.xml new file mode 100644 index 00000000..51b3956b --- /dev/null +++ b/checks/egiz_pmd_checks.xml @@ -0,0 +1,99 @@ + + + + + + EGIZ modifications of the default ruleset used by the Maven PMD Plugin, when no other ruleset is specified. + It contains the rules of the old (pre PMD 6.0.0) rulesets java-basic, java-empty, java-imports, + java-unnecessary, java-unusedcode. + + This ruleset might be used as a starting point for an own customized ruleset [0]. + + [0] https://pmd.github.io/latest/pmd_userdocs_making_rulesets.html + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/gui/IVelocityGuiFormBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/gui/IVelocityGuiFormBuilder.java index 103b38d9..e06140bf 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/gui/IVelocityGuiFormBuilder.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/gui/IVelocityGuiFormBuilder.java @@ -1,66 +1,67 @@ package at.gv.egiz.eaaf.core.api.gui; import java.io.InputStream; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - +import at.gv.egiz.eaaf.core.exceptions.GuiBuildException; import org.apache.velocity.VelocityContext; -import at.gv.egiz.eaaf.core.exceptions.GUIBuildException; +public interface IVelocityGuiFormBuilder extends IGuiFormBuilder { + -public interface IVelocityGuiFormBuilder extends IGUIFormBuilder { + /** + * Generate a new {@link VelocityContext} and populate it with MOA-ID GUI parameters. + * + * @param config GUI builder configuration + * @return + */ + public VelocityContext generateVelocityContextFromConfiguration( + IVelocityGuiBuilderConfiguration config); - - /** - * Generate a new {@link VelocityContext} and populate it with MOA-ID GUI parameters - * - * @param config - * @return - */ - public VelocityContext generateVelocityContextFromConfiguration(IVelocityGUIBuilderConfiguration config); - - /** - * Load the template from different resources - * - * @param config - * @return An {@link InputStream} but never null. The {@link InputStream} had to be closed be the invoking method - * @throws GUIBuildException - */ - public InputStream getTemplateInputStream(IVelocityGUIBuilderConfiguration config) throws GUIBuildException; + /** + * Load the template from different resources. + * + * @param config GUI builder configuration + * @return An {@link InputStream} but never null. The {@link InputStream} had to be closed be the + * invoking method + * @throws GuiBuildException In case of an error + */ + public InputStream getTemplateInputStream(IVelocityGuiBuilderConfiguration config) + throws GuiBuildException; - /** - * Parse a GUI template, with parameters into a http servlet-response - * and use the default http-response content-type. - *

- * The parser use the VelocityEngine as internal template evaluator. - * - * @param httpReq http-request object - * @param httpResp http-response object - * @param config Configuration object - * @param loggerName String, which should be used from logger - * - * @throws GUIBuildException - */ - void build(HttpServletRequest httpReq, HttpServletResponse httpResp, IVelocityGUIBuilderConfiguration config, String loggerName) - throws GUIBuildException; + /** + * Parse a GUI template, with parameters into a http servlet-response and use the default + * http-response content-type.
+ *
+ * The parser use the VelocityEngine as internal template evaluator. + * + * @param httpReq http-request object + * @param httpResp http-response object + * @param config Configuration object + * @param loggerName String, which should be used from logger + * + * @throws GuiBuildException in case of an error + */ + void build(HttpServletRequest httpReq, HttpServletResponse httpResp, + IVelocityGuiBuilderConfiguration config, String loggerName) throws GuiBuildException; - /** - * Parse a GUI template, with parameters into a http servlet-response. - *

- * The parser use the VelocityEngine as internal template evaluator. - * - * @param httpReq http-request object - * @param httpResp http-response object - * @param config Configuration object - * @param contentType http-response content-type, which should be set - * @param loggerName String, which should be used from logger - * - * @throws GUIBuildException - */ - void build(HttpServletRequest httpReq, HttpServletResponse httpResp, IVelocityGUIBuilderConfiguration config, String contentType, - String loggerName) throws GUIBuildException; + /** + * Parse a GUI template, with parameters into a http servlet-response.
+ *
+ * The parser use the VelocityEngine as internal template evaluator. + * + * @param httpReq http-request object + * @param httpResp http-response object + * @param config Configuration object + * @param contentType http-response content-type, which should be set + * @param loggerName String, which should be used from logger + * + * @throws GuiBuildException In case of an error + */ + void build(HttpServletRequest httpReq, HttpServletResponse httpResp, + IVelocityGuiBuilderConfiguration config, String contentType, String loggerName) + throws GuiBuildException; } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/ExpressionEvaluationContext.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/ExpressionEvaluationContext.java index 31b8a219..7315dbf1 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/ExpressionEvaluationContext.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/ExpressionEvaluationContext.java @@ -1,48 +1,42 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.api.idp.process; import java.io.Serializable; import java.util.Map; +import at.gv.egiz.eaaf.core.impl.idp.process.model.Transition; /** * Context used for evaluation of condition expressions set for {@linkplain Transition Transitions}. - * + * * @author tknall - * + * */ public interface ExpressionEvaluationContext extends Serializable { - /** - * Returns the context data map used for expression evaluation. - * - * @return An unmodifiable map (never {@code null}). - */ - Map getCtx(); + /** + * Returns the context data map used for expression evaluation. + * + * @return An unmodifiable map (never {@code null}). + */ + Map getCtx(); } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/ExpressionEvaluator.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/ExpressionEvaluator.java index ef147bff..7fa67ae4 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/ExpressionEvaluator.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/ExpressionEvaluator.java @@ -1,51 +1,40 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.api.idp.process; /** * Evaluates a given {@code expression} returning a boolean value. - * + * * @author tknall */ public interface ExpressionEvaluator { - /** - * Evaluates a given {@code expression} returning a boolean value. - * - * @param expressionContext - * The context which can be used for evaluation of the expression. - * @param expression - * The expression resulting in a boolean (must not be {@code null}). - * @return A boolean value. - * @throws IllegalArgumentException - * In case of an invalid {@code expression}. - * @throws NullPointerException - * In case of a {@code null} expression. - */ - boolean evaluate(ExpressionEvaluationContext expressionContext, String expression); + /** + * Evaluates a given {@code expression} returning a boolean value. + * + * @param expressionContext The context which can be used for evaluation of the expression. + * @param expression The expression resulting in a boolean (must not be {@code null}). + * @return A boolean value. + * @throws IllegalArgumentException In case of an invalid {@code expression}. + * @throws NullPointerException In case of a {@code null} expression. + */ + boolean evaluate(ExpressionEvaluationContext expressionContext, String expression); } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/ProcessEngine.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/ProcessEngine.java index 6f6d6938..d4c221e0 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/ProcessEngine.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/ProcessEngine.java @@ -1,34 +1,26 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.api.idp.process; import java.io.InputStream; - import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.exceptions.ProcessExecutionException; import at.gv.egiz.eaaf.core.impl.idp.process.ProcessDefinitionParserException; @@ -37,102 +29,98 @@ import at.gv.egiz.eaaf.core.impl.idp.process.model.ProcessDefinition; /** * Process engine providing means for starting and resuming processes. - * + * * @author tknall */ public interface ProcessEngine { - /** - * Registers a new process definition. Note that existing definitions with the same identifier will be replaced. - * - * @param processDefinition - * The process definition to be registered. - */ - void registerProcessDefinition(ProcessDefinition processDefinition); + /** + * Registers a new process definition. Note that existing definitions with the same identifier + * will be replaced. + * + * @param processDefinition The process definition to be registered. + */ + void registerProcessDefinition(ProcessDefinition processDefinition); + + /** + * Registers a new process definition given as {@link InputStream}. Note that existing definitions + * with the same identifier will be replaced. + * + * @param processDefinitionInputStream The input stream to the definition to be registered. + * @return The process definition's identifier. + * @throws ProcessDefinitionParserException Thrown in case of an error parsing the process + * definition. + */ + String registerProcessDefinition(InputStream processDefinitionInputStream) + throws ProcessDefinitionParserException; + + /** + * Creates a process instance according to the referenced process definition, persists it into the + * database and returns it identifier. + *

+ * Note that the method returns the identifier of a process instance which will be needed in order + * to start a process or to continue process execution after asynchronous task execution (refer to + * {@link #start(String)} and {@link #signal(String)} for further information). + * + * @param processDefinitionId The identifier of the respective process definition. + * @param executionContext The execution context (may be {@code null}). + * @return The id of the newly created process instance (never {@code null}). + * @throws ProcessExecutionException Thrown in case of error, e.g. when a + * {@code processDefinitionId} is referenced that does not exist. + */ + String createProcessInstance(String processDefinitionId, ExecutionContext executionContext) + throws ProcessExecutionException; - /** - * Registers a new process definition given as {@link InputStream}. Note that existing definitions with the same identifier will be replaced. - * - * @param processDefinitionInputStream The input stream to the definition to be registered. - * @throws ProcessDefinitionParserException Thrown in case of an error parsing the process definition. - * @return The process definition's identifier. - */ - String registerProcessDefinition(InputStream processDefinitionInputStream) throws ProcessDefinitionParserException; + /** + * Creates a process instance according to the referenced process definition, persists it into the + * database and returns it identifier. + *

+ * Note that the method returns the identifier of a process instance which will be needed in order + * to start a process or to continue process execution after asynchronous task execution (refer to + * {@link #start(String)} and {@link #signal(String)} for further information). + * + * @param processDefinitionId The identifier of the respective process definition. + * @return The id of the newly created process instance (never {@code null}). + * @throws ProcessExecutionException Thrown in case of error, e.g. when a + * {@code processDefinitionId} is referenced that does not exist. + */ + String createProcessInstance(String processDefinitionId) throws ProcessExecutionException; - /** - * Creates a process instance according to the referenced process definition, persists it into the database and returns it identifier. - *

- * Note that the method returns the identifier of a process instance which will be needed in order to start a process or to continue - * process execution after asynchronous task execution (refer to {@link #start(String)} and - * {@link #signal(String)} for further information). - * - * @param processDefinitionId - * The identifier of the respective process definition. - * @param executionContext The execution context (may be {@code null}). - * @return The id of the newly created process instance (never {@code null}). - * @throws ProcessExecutionException - * Thrown in case of error, e.g. when a {@code processDefinitionId} is referenced that does not exist. - */ - String createProcessInstance(String processDefinitionId, ExecutionContext executionContext) throws ProcessExecutionException; - /** - * Creates a process instance according to the referenced process definition, persists it into the database and returns it identifier. - *

- * Note that the method returns the identifier of a process instance which will be needed in order to start a process or to continue - * process execution after asynchronous task execution (refer to {@link #start(String)} and - * {@link #signal(String)} for further information). - * - * @param processDefinitionId - * The identifier of the respective process definition. - * @return The id of the newly created process instance (never {@code null}). - * @throws ProcessExecutionException - * Thrown in case of error, e.g. when a {@code processDefinitionId} is referenced that does not exist. - */ - String createProcessInstance(String processDefinitionId) throws ProcessExecutionException; + /** + * Delete a process instance. + * + * @param processInstanceId The identifier of the respective process. + * @throws ProcessExecutionException Thrown in case of error, e.g. when a + * {@code processInstanceId} is referenced that does not exist. + */ + void deleteProcessInstance(String processInstanceId) throws ProcessExecutionException; - - /** - * Delete a process instance - * - * @param processInstanceId - * The identifier of the respective process. - * @throws ProcessExecutionException - * Thrown in case of error, e.g. when a {@code processInstanceId} is referenced that does not exist. - */ - void deleteProcessInstance(String processInstanceId) throws ProcessExecutionException; - - /** - * Returns the process instance with a given {@code processInstanceId}. - * - * @param processInstanceId - * The process instance id. - * @return The process instance (never {@code null}). - * @throws IllegalArgumentException - * In case the process instance does not/no longer exist. - * @throws RuntimeException - * In case the process instance could not be retrieved from persistence. - */ - ProcessInstance getProcessInstance(String processInstanceId); + /** + * Returns the process instance with a given {@code processInstanceId}. + * + * @param processInstanceId The process instance id. + * @return The process instance (never {@code null}). + * @throws IllegalArgumentException In case the process instance does not/no longer exist. + * @throws RuntimeException In case the process instance could not be retrieved from persistence. + */ + ProcessInstance getProcessInstance(String processInstanceId); - /** - * Starts the process using the given {@code pendingReq}. - * - * @param pendingReq - * The protocol request for which a process should be started. - * @throws ProcessExecutionException - * Thrown in case of error. - */ - void start(IRequest pendingReq) throws ProcessExecutionException; + /** + * Starts the process using the given {@code pendingReq}. + * + * @param pendingReq The protocol request for which a process should be started. + * @throws ProcessExecutionException Thrown in case of error. + */ + void start(IRequest pendingReq) throws ProcessExecutionException; - /** - * Resumes process execution after an asynchronous task has been executed. - * - * @param pendingReq - * The process instance id. - * @throws ProcessExecutionException - * Thrown in case of error. - */ - void signal(IRequest pendingReq) throws ProcessExecutionException; + /** + * Resumes process execution after an asynchronous task has been executed. + * + * @param pendingReq The process instance id. + * @throws ProcessExecutionException Thrown in case of error. + */ + void signal(IRequest pendingReq) throws ProcessExecutionException; -} \ No newline at end of file +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/ProcessInstanceStoreDAO.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/ProcessInstanceStoreDAO.java deleted file mode 100644 index 305af911..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/ProcessInstanceStoreDAO.java +++ /dev/null @@ -1,71 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.api.idp.process; - -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.core.exceptions.EAAFStorageException; -import at.gv.egiz.eaaf.core.impl.idp.process.ProcessInstance; -import at.gv.egiz.eaaf.core.impl.idp.process.dao.ProcessInstanceStore; - -public interface ProcessInstanceStoreDAO { - - /** - * Stores a {@link ProcessInstance} defined by {@code pIStore} in the - * database. - * - * @param pIStore - * the {@link ProcessInstanceStore} to persist. - * @throws EAAFStorageException - * is thrown if a problem occurs while accessing the database. - */ - void saveOrUpdate(ProcessInstanceStore pIStore) throws EAAFException; - - /** - * Returns a {@link ProcessInstanceStore}, defined by - * {@code processInstanceID} from the database, or {@code null} if the - * object could not be found. - * - * @param processInstanceId - * the id of the {@code ProcessInstanceStore} to retrieve. - * @return a ProcessInstanceStore, or {@code null}. - * @throws EAAFStorageException - * is thrown if a problem occurs while accessing the database. - */ - ProcessInstanceStore load(String processInstanceId) throws EAAFException; - - /** - * Deletes the {@link ProcessInstance} corresponding with the - * {@code processInstanceId}. - * - * @param processInstanceId - * the id of the {@code ProcessInstance} to be deleted. - * @throws EAAFStorageException - * is thrown if a problem occurs while accessing the database. - */ - void remove(String processInstanceId) throws EAAFException; - -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/ProcessInstanceStoreDao.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/ProcessInstanceStoreDao.java new file mode 100644 index 00000000..641eeab8 --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/ProcessInstanceStoreDao.java @@ -0,0 +1,55 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.api.idp.process; + +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; +import at.gv.egiz.eaaf.core.impl.idp.process.ProcessInstance; +import at.gv.egiz.eaaf.core.impl.idp.process.dao.ProcessInstanceStore; + +public interface ProcessInstanceStoreDao { + + /** + * Stores a {@link ProcessInstance} defined by {@code pIStore} in the database. + * + * @param piStore the {@link ProcessInstanceStore} to persist. + * @throws EaafStorageException is thrown if a problem occurs while accessing the database. + */ + void saveOrUpdate(ProcessInstanceStore piStore) throws EaafException; + + /** + * Returns a {@link ProcessInstanceStore}, defined by {@code processInstanceID} from the database, + * or {@code null} if the object could not be found. + * + * @param processInstanceId the id of the {@code ProcessInstanceStore} to retrieve. + * @return a ProcessInstanceStore, or {@code null}. + * @throws EaafStorageException is thrown if a problem occurs while accessing the database. + */ + ProcessInstanceStore load(String processInstanceId) throws EaafException; + + /** + * Deletes the {@link ProcessInstance} corresponding with the {@code processInstanceId}. + * + * @param processInstanceId the id of the {@code ProcessInstance} to be deleted. + * @throws EaafStorageException is thrown if a problem occurs while accessing the database. + */ + void remove(String processInstanceId) throws EaafException; + +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/Task.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/Task.java index 435dff12..06573403 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/Task.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/Task.java @@ -1,29 +1,22 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.api.idp.process; import at.gv.egiz.eaaf.core.api.IRequest; @@ -32,21 +25,21 @@ import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; /** * Represents a single task to be performed upon process execution. - * + * * @author tknall - * + * */ public interface Task { - /** - * Executes this task. - * @param pendingReq - * Provides the current processed protocol request - * @param executionContext - * Provides execution related information. - * @return The pending-request object, because Process-management works recursive - * @throws Exception An exception upon task execution. - */ - IRequest execute(IRequest pendingReq, ExecutionContext executionContext) throws TaskExecutionException; + /** + * Executes this task. + * + * @param pendingReq Provides the current processed protocol request + * @param executionContext Provides execution related information. + * @return The pending-request object, because Process-management works recursive + * @throws Exception An exception upon task execution. + */ + IRequest execute(IRequest pendingReq, ExecutionContext executionContext) + throws TaskExecutionException; } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/utils/IJsonMapper.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/utils/IJsonMapper.java index 6db5a6ae..dd7e69fd 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/utils/IJsonMapper.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/api/utils/IJsonMapper.java @@ -3,40 +3,45 @@ package at.gv.egiz.eaaf.core.api.utils; import java.io.IOException; import java.io.InputStream; -import at.gv.egiz.eaaf.core.exceptions.EAAFJsonMapperException; +import at.gv.egiz.eaaf.core.exceptions.EaafJsonMapperException; public interface IJsonMapper { - - /** - * Serialize an object to a JSON string. - * @param value the object to serialize - * @return a JSON string - * @throws JsonProcessingException thrown when an error occurs during serialization - */ - String serialize(Object value) throws EAAFJsonMapperException; - /** - * Deserialize a JSON string. - * - * @param value the JSON string to deserialize - * @param clazz optional parameter that determines the type of the returned object. If not set, an {@link Object} is returned. - * @return the deserialized JSON string as an object of type {@code clazz} or {@link Object} - * @throws JsonParseException if the JSON string contains invalid content. - * @throws JsonMappingException if the input JSON structure does not match structure expected for result type - * @throws IOException if an I/O problem occurs (e.g. unexpected end-of-input) - */ - Object deserialize(String value, Class clazz) throws EAAFJsonMapperException; + /** + * Serialize an object to a JSON string. + * + * @param value the object to serialize + * @return a JSON string + * @throws JsonProcessingException thrown when an error occurs during serialization + */ + String serialize(Object value) throws EaafJsonMapperException; - /** - * Deserialize a JSON string. - * - * @param is the JSON to deserialize as {@link InputStream} - * @param clazz optional parameter that determines the type of the returned object. If not set, an {@link Object} is returned. - * @return the deserialized JSON string as an object of type {@code clazz} or {@link Object} - * @throws JsonParseException if the JSON string contains invalid content. - * @throws JsonMappingException if the input JSON structure does not match structure expected for result type - * @throws IOException if an I/O problem occurs (e.g. unexpected end-of-input) - */ - Object deserialize(InputStream is, Class clazz) throws EAAFJsonMapperException; - -} \ No newline at end of file + /** + * Deserialize a JSON string. + * + * @param value the JSON string to deserialize + * @param clazz optional parameter that determines the type of the returned object. If not set, an + * {@link Object} is returned. + * @return the deserialized JSON string as an object of type {@code clazz} or {@link Object} + * @throws JsonParseException if the JSON string contains invalid content. + * @throws JsonMappingException if the input JSON structure does not match structure expected for + * result type + * @throws IOException if an I/O problem occurs (e.g. unexpected end-of-input) + */ + Object deserialize(String value, Class clazz) throws EaafJsonMapperException; + + /** + * Deserialize a JSON string. + * + * @param is the JSON to deserialize as {@link InputStream} + * @param clazz optional parameter that determines the type of the returned object. If not set, an + * {@link Object} is returned. + * @return the deserialized JSON string as an object of type {@code clazz} or {@link Object} + * @throws JsonParseException if the JSON string contains invalid content. + * @throws JsonMappingException if the input JSON structure does not match structure expected for + * result type + * @throws IOException if an I/O problem occurs (e.g. unexpected end-of-input) + */ + Object deserialize(InputStream is, Class clazz) throws EaafJsonMapperException; + +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/data/SLOInformationImpl.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/data/SLOInformationImpl.java index 9f025979..c0980b0b 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/data/SLOInformationImpl.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/data/SLOInformationImpl.java @@ -1,24 +1,20 @@ /******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ /******************************************************************************* *******************************************************************************/ @@ -27,165 +23,182 @@ package at.gv.egiz.eaaf.core.impl.data; import java.io.Serializable; - -import at.gv.egiz.eaaf.core.api.idp.slo.SLOInformationInterface; +import at.gv.egiz.eaaf.core.api.idp.slo.SloInformationInterface; /** * @author tlenz * */ -public class SLOInformationImpl implements SLOInformationInterface, Serializable { - - private static final long serialVersionUID = 295577931870512387L; - private String sessionIndex = null; - private String nameID = null; - private String protocolType = null; - private String nameIDFormat = null; - private String binding = null; - private String serviceURL = null; - private String authURL = null; - private String spEntityID = null; - - public SLOInformationImpl(String authURL, String spEntityID, String sessionID, String nameID, String nameIDFormat, String protocolType) { - new SLOInformationImpl(authURL, spEntityID, sessionID, nameID, nameIDFormat, protocolType, null, null); - } - - public SLOInformationImpl(String authURL, String spEntityID, String sessionID, String nameID, String nameIDFormat, String protocolType, String sloBinding, String sloLocationURL) { - this.sessionIndex = sessionID; - this.nameID = nameID; - this.nameIDFormat = nameIDFormat; - this.protocolType = protocolType; - this.spEntityID = spEntityID; - - if (authURL.endsWith("/")) - this.authURL = authURL.substring(0, authURL.length()-1); - else - this.authURL = authURL; - - - this.binding = sloBinding; - this.serviceURL = sloLocationURL; - - } - - - /** - * - */ - public SLOInformationImpl() { - - } - - - - /** - * @return the spEntityID - */ - public String getSpEntityID() { - return spEntityID; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.data.SLOInformationInterface#getSessionIndex() - */ - @Override - public String getSessionIndex() { - return sessionIndex; - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.data.SLOInformationInterface#getUserNameIdentifier() - */ - @Override - public String getUserNameIdentifier() { - return nameID; - - } - - - /** - * @param sessionIndex the sessionIndex to set - */ - public void setSessionIndex(String sessionIndex) { - this.sessionIndex = sessionIndex; - } - - - /** - * @param nameID the nameID to set - */ - public void setUserNameIdentifier(String nameID) { - this.nameID = nameID; - } - - - - /** - * @param protocolType the protocolType to set - */ - public void setProtocolType(String protocolType) { - this.protocolType = protocolType; - } - - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.data.SLOInformationInterface#getProtocolType() - */ - @Override - public String getProtocolType() { - return protocolType; - } - - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.data.SLOInformationInterface#getUserNameIDFormat() - */ - @Override - public String getUserNameIDFormat() { - return this.nameIDFormat; - } - - - /** - * @param nameIDFormat the nameIDFormat to set - */ - public void setNameIDFormat(String nameIDFormat) { - this.nameIDFormat = nameIDFormat; - } - - /** - * @return the binding - */ - public String getBinding() { - return binding; - } - - /** - * @return the serviceURL - */ - public String getServiceURL() { - return serviceURL; - } - - /** - * @return the authURL from requested IDP without ending / - */ - public String getAuthURL() { - return authURL; - } - - /** - * @param spEntityID the spEntityID to set - */ - public void setSpEntityID(String spEntityID) { - this.spEntityID = spEntityID; - } - - - - - +public class SLOInformationImpl implements SloInformationInterface, Serializable { + + private static final long serialVersionUID = 295577931870512387L; + private String sessionIndex = null; + private String nameID = null; + private String protocolType = null; + private String nameIDFormat = null; + private String binding = null; + private String serviceURL = null; + private String authURL = null; + private String spEntityID = null; + + public SLOInformationImpl(final String authURL, final String spEntityID, final String sessionID, + final String nameID, final String nameIDFormat, final String protocolType) { + this(authURL, spEntityID, sessionID, nameID, nameIDFormat, protocolType, null, + null); + + } + + public SLOInformationImpl(final String authURL, final String spEntityID, final String sessionID, + final String nameID, final String nameIDFormat, final String protocolType, + final String sloBinding, final String sloLocationURL) { + this.sessionIndex = sessionID; + this.nameID = nameID; + this.nameIDFormat = nameIDFormat; + this.protocolType = protocolType; + this.spEntityID = spEntityID; + + if (authURL.endsWith("/")) { + this.authURL = authURL.substring(0, authURL.length() - 1); + } else { + this.authURL = authURL; + } + + + this.binding = sloBinding; + this.serviceURL = sloLocationURL; + + } + + + /** + * + */ + public SLOInformationImpl() { + + } + + + + /** + * @return the spEntityID + */ + @Override + public String getSpEntityID() { + return spEntityID; + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.data.SLOInformationInterface#getSessionIndex() + */ + @Override + public String getSessionIndex() { + return sessionIndex; + + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.data.SLOInformationInterface#getUserNameIdentifier() + */ + @Override + public String getUserNameIdentifier() { + return nameID; + + } + + + /** + * @param sessionIndex the sessionIndex to set + */ + @Override + public void setSessionIndex(final String sessionIndex) { + this.sessionIndex = sessionIndex; + } + + + /** + * @param nameID the nameID to set + */ + @Override + public void setUserNameIdentifier(final String nameID) { + this.nameID = nameID; + } + + + + /** + * @param protocolType the protocolType to set + */ + public void setProtocolType(final String protocolType) { + this.protocolType = protocolType; + } + + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.data.SLOInformationInterface#getProtocolType() + */ + @Override + public String getProtocolType() { + return protocolType; + } + + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.data.SLOInformationInterface#getUserNameIDFormat() + */ + @Override + public String getUserNameIdFormat() { + return this.nameIDFormat; + } + + + /** + * @param nameIDFormat the nameIDFormat to set + */ + @Override + public void setNameIdFormat(final String nameIDFormat) { + this.nameIDFormat = nameIDFormat; + } + + /** + * @return the binding + */ + @Override + public String getBinding() { + return binding; + } + + /** + * @return the serviceURL + */ + @Override + public String getServiceUrl() { + return serviceURL; + } + + /** + * @return the authURL from requested IDP without ending / + */ + @Override + public String getAuthUrl() { + return authURL; + } + + /** + * @param spEntityID the spEntityID to set + */ + public void setSpEntityID(final String spEntityID) { + this.spEntityID = spEntityID; + } + + } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractGUIFormBuilderConfiguration.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractGUIFormBuilderConfiguration.java deleted file mode 100644 index dde5ab70..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractGUIFormBuilderConfiguration.java +++ /dev/null @@ -1,179 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.gui; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import at.gv.egiz.eaaf.core.api.gui.GroupDefinition; -import at.gv.egiz.eaaf.core.api.gui.GroupDefinition.TYPE; -import at.gv.egiz.eaaf.core.api.gui.IGUIBuilderConfiguration; - -/** - * @author tlenz - * - */ -public abstract class AbstractGUIFormBuilderConfiguration implements IGUIBuilderConfiguration { - private static final Logger log = LoggerFactory.getLogger(AbstractGUIFormBuilderConfiguration.class); - - public static final GroupDefinition PARAM_GROUP_FORM = GroupDefinition.getInstance("form", TYPE.MAP); - public static final GroupDefinition PARAM_GROUP_ACTIONS = GroupDefinition.getInstance("actions", TYPE.LIST); - public static final GroupDefinition PARAM_GROUP_PARAMS = GroupDefinition.getInstance("params", TYPE.MAP); - public static final GroupDefinition PARAM_GROUP_UIOPTIONS = GroupDefinition.getInstance("uiOptions", TYPE.MAP); - public static final GroupDefinition PARAM_GROUP_MSG = GroupDefinition.getInstance("msg", TYPE.MAP); - - - public static final String PARAM_VIEWNAME = "viewName"; - public static final String PARAM_AUTHCONTEXT = "contextPath"; - public static final String PARAM_FORMSUBMITENDPOINT = "submitEndpoint"; - @Deprecated public static final String PARAM_PENDINGREQUESTID_DEPRECATED = "pendingReqID"; - public static final String PARAM_PENDINGREQUESTID = "pendingid"; - - private String authURL = null; - private String viewName = null; - private String formSubmitEndpoint = null; - - private final Map params = new HashMap(); - - /** - * @param authURL IDP PublicURL-Prefix which should be used, but never null - * @param viewName Name of the template (with suffix) but never null - * @param formSubmitEndpoint EndPoint on which the form should be submitted, - * or null if the form must not submitted - * - */ - public AbstractGUIFormBuilderConfiguration(String authURL, String viewName, String formSubmitEndpoint) { - if (viewName.startsWith("/")) - this.viewName = viewName.substring(1); - else - this.viewName = viewName; - - if (authURL.endsWith("/")) - this.authURL = authURL.substring(0, authURL.length() - 1); - else - this.authURL = authURL; - - if (StringUtils.isNotEmpty(formSubmitEndpoint)) { - if (formSubmitEndpoint.startsWith("/")) - this.formSubmitEndpoint = formSubmitEndpoint; - else - this.formSubmitEndpoint = "/" + formSubmitEndpoint; - } - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.frontend.builder.IGUIBuilderConfiguration#getViewName() - */ - @Override - public final String getViewName() { - return this.viewName; - - } - - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.frontend.builder.IGUIBuilderConfiguration#getViewParameters() - */ - @Override - public final Map getViewParameters() { - //set generic parameters - setViewParameter(getFromGroup(), PARAM_AUTHCONTEXT, this.authURL); - setViewParameter(getFromGroup(), PARAM_FORMSUBMITENDPOINT, this.formSubmitEndpoint); - setViewParameter(getFromGroup(), PARAM_VIEWNAME, this.viewName); - - //get parameters from detail implementation - putSpecificViewParameters(); - - try { - log.trace("Full view parameters: {}", StringUtils.join(params, ",")); - } catch (final Exception e) { - log.info("Can NOT trace view parameters. Reason: {}", e.getMessage() ); - } - - return params; - - } - - /** - * Define the parameters, which should be evaluated in the template
- * IMPORTANT: external HTML escapetion is required, because it is NOT done internally during the building process - * - */ - abstract protected void putSpecificViewParameters(); - - /** - * Get the Group for generic form elements - * - * @return {@link GroupDefinition} or null if no groups are used - */ - abstract protected GroupDefinition getFromGroup(); - - @SuppressWarnings("unchecked") - protected void setViewParameter(GroupDefinition groupDefinition, String key, Object value) { - - if (groupDefinition != null) { - log.trace("Adding group object ... "); - Object groupMap = params.get(groupDefinition.getName()); - if (groupMap == null) { - if (groupDefinition.getType().equals(TYPE.MAP)) { - groupMap = new HashMap();; - log.trace("Build new MAP based group element"); - - } else if (groupDefinition.getType().equals(TYPE.LIST)) { - groupMap = new ArrayList(); - log.trace("Build new List based group element"); - - } else - log.warn("GroupDefinition contains an unknown type: {}", groupDefinition.getType().name()); - - } - - params.put(groupDefinition.getName(), groupMap); - if (groupMap instanceof Map) - ((Map) groupMap).put(key, value); - - else if (groupMap instanceof List) - ((List)groupMap).add(value); - - else - log.warn("Can NOT add element: {} to group: {}, because group is of type: {}", - key, groupDefinition.getName(), groupMap.getClass().getName()); - - } else { - log.trace("Add root object ... "); - params.put(key, value); - - } - - } -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractGuiFormBuilderConfiguration.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractGuiFormBuilderConfiguration.java new file mode 100644 index 00000000..efb8c713 --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractGuiFormBuilderConfiguration.java @@ -0,0 +1,195 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.impl.gui; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import at.gv.egiz.eaaf.core.api.gui.GroupDefinition; +import at.gv.egiz.eaaf.core.api.gui.GroupDefinition.Type; +import at.gv.egiz.eaaf.core.api.gui.IGuiBuilderConfiguration; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Abstract Configuration implementation for GUI Builders. + * + * @author tlenz + * + */ +public abstract class AbstractGuiFormBuilderConfiguration implements IGuiBuilderConfiguration { + private static final Logger log = + LoggerFactory.getLogger(AbstractGuiFormBuilderConfiguration.class); + + public static final GroupDefinition PARAM_GROUP_FORM = + GroupDefinition.getInstance("form", Type.MAP); + public static final GroupDefinition PARAM_GROUP_ACTIONS = + GroupDefinition.getInstance("actions", Type.LIST); + public static final GroupDefinition PARAM_GROUP_PARAMS = + GroupDefinition.getInstance("params", Type.MAP); + public static final GroupDefinition PARAM_GROUP_UIOPTIONS = + GroupDefinition.getInstance("uiOptions", Type.MAP); + public static final GroupDefinition PARAM_GROUP_MSG = + GroupDefinition.getInstance("msg", Type.MAP); + + + public static final String PARAM_VIEWNAME = "viewName"; + public static final String PARAM_AUTHCONTEXT = "contextPath"; + public static final String PARAM_FORMSUBMITENDPOINT = "submitEndpoint"; + @Deprecated + public static final String PARAM_PENDINGREQUESTID_DEPRECATED = "pendingReqID"; + public static final String PARAM_PENDINGREQUESTID = "pendingid"; + + private String authUrl = null; + private String viewName = null; + private String formSubmitEndpoint = null; + + private final Map params = new HashMap<>(); + + /** + * Abstract GUI Builder config. + * + * @param authUrl IDP PublicURL-Prefix which should be used, but never null + * @param viewName Name of the template (with suffix) but never null + * @param formSubmitEndpoint EndPoint on which the form should be submitted, or null if the form + * must not submitted + * + */ + public AbstractGuiFormBuilderConfiguration(final String authUrl, final String viewName, + final String formSubmitEndpoint) { + if (viewName.startsWith("/")) { + this.viewName = viewName.substring(1); + } else { + this.viewName = viewName; + } + + if (authUrl.endsWith("/")) { + this.authUrl = authUrl.substring(0, authUrl.length() - 1); + } else { + this.authUrl = authUrl; + } + + if (StringUtils.isNotEmpty(formSubmitEndpoint)) { + if (formSubmitEndpoint.startsWith("/")) { + this.formSubmitEndpoint = formSubmitEndpoint; + } else { + this.formSubmitEndpoint = "/" + formSubmitEndpoint; + } + } + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.frontend.builder.IGUIBuilderConfiguration#getViewName() + */ + @Override + public final String getViewName() { + return this.viewName; + + } + + + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.auth.frontend.builder.IGUIBuilderConfiguration#getViewParameters() + */ + @Override + public final Map getViewParameters() { + // set generic parameters + setViewParameter(getFromGroup(), PARAM_AUTHCONTEXT, this.authUrl); + setViewParameter(getFromGroup(), PARAM_FORMSUBMITENDPOINT, this.formSubmitEndpoint); + setViewParameter(getFromGroup(), PARAM_VIEWNAME, this.viewName); + + // get parameters from detail implementation + putSpecificViewParameters(); + + try { + log.trace("Full view parameters: {}", StringUtils.join(params, ",")); + } catch (final Exception e) { + log.info("Can NOT trace view parameters. Reason: {}", e.getMessage()); + } + + return params; + + } + + /** + * Define the parameters, which should be evaluated in the template.
+ * IMPORTANT: external HTML escapetion is required, because it is NOT done internally + * during the building process + * + */ + protected abstract void putSpecificViewParameters(); + + /** + * Get the Group for generic form elements. + * + * @return {@link GroupDefinition} or null if no groups are used + */ + protected abstract GroupDefinition getFromGroup(); + + @SuppressWarnings("unchecked") + protected void setViewParameter(final GroupDefinition groupDefinition, final String key, + final Object value) { + + if (groupDefinition != null) { + log.trace("Adding group object ... "); + Object groupMap = params.get(groupDefinition.getName()); + if (groupMap == null) { + if (groupDefinition.getType().equals(Type.MAP)) { + groupMap = new HashMap(); + log.trace("Build new MAP based group element"); + + } else if (groupDefinition.getType().equals(Type.LIST)) { + groupMap = new ArrayList<>(); + log.trace("Build new List based group element"); + + } else { + log.warn("GroupDefinition contains an unknown type: {}", + groupDefinition.getType().name()); + groupMap = StringUtils.EMPTY; + + } + + } + + params.put(groupDefinition.getName(), groupMap); + if (groupMap instanceof Map) { + ((Map) groupMap).put(key, value); + } else if (groupMap instanceof List) { + ((List) groupMap).add(value); + } else { + log.warn("Can NOT add element: {} to group: {}, because group is of type: {}", key, + groupDefinition.getName(), groupMap.getClass().getName()); + } + + } else { + log.trace("Add root object ... "); + params.put(key, value); + + } + + } +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractVelocityGUIFormBuilderImpl.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractVelocityGUIFormBuilderImpl.java deleted file mode 100644 index b9c16538..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractVelocityGUIFormBuilderImpl.java +++ /dev/null @@ -1,242 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.gui; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.StringWriter; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang3.StringUtils; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.VelocityEngine; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import at.gv.egiz.eaaf.core.api.data.EAAFConstants; -import at.gv.egiz.eaaf.core.api.gui.IGUIBuilderConfiguration; -import at.gv.egiz.eaaf.core.api.gui.IVelocityGUIBuilderConfiguration; -import at.gv.egiz.eaaf.core.api.gui.IVelocityGuiFormBuilder; -import at.gv.egiz.eaaf.core.exceptions.GUIBuildException; -import at.gv.egiz.eaaf.core.impl.gui.velocity.VelocityProvider; - -/** - * @author tlenz - * - */ -public abstract class AbstractVelocityGUIFormBuilderImpl implements IVelocityGuiFormBuilder { - private static final Logger log = LoggerFactory.getLogger(AbstractVelocityGUIFormBuilderImpl.class); - private static final String DEFAULT_CONTENT_TYPE = EAAFConstants.CONTENTTYPE_HTML_UTF8; - - private VelocityEngine engine; - - public AbstractVelocityGUIFormBuilderImpl() throws GUIBuildException { - try { - engine = VelocityProvider.getClassPathVelocityEngine(); - - } catch (final Exception e) { - log.error("Initialization of Velocity-Engine to render GUI components FAILED.", e); - throw new GUIBuildException("Initialization of Velocity-Engine to render GUI components FAILED.", e); - - } - - } - - @Override - public final void build(HttpServletRequest httpReq, HttpServletResponse httpResp, IGUIBuilderConfiguration config, - String loggerName) throws GUIBuildException { - if (config instanceof IVelocityGUIBuilderConfiguration) - build(httpReq, httpResp, (IVelocityGUIBuilderConfiguration)config, loggerName); - else - throw new IllegalStateException(this.getClass().getName() + " needs a " + IVelocityGUIBuilderConfiguration.class.getName()); - - - } - - @Override - public final void build(HttpServletRequest httpReq, HttpServletResponse httpResp, IGUIBuilderConfiguration config, - String contentType, String loggerName) throws GUIBuildException { - if (config instanceof IVelocityGUIBuilderConfiguration) - build(httpReq, httpResp, (IVelocityGUIBuilderConfiguration)config, contentType, loggerName); - else - throw new IllegalStateException(this.getClass().getName() + " needs a " + IVelocityGUIBuilderConfiguration.class.getName()); - - } - - @Override - public void build(HttpServletRequest httpReq, HttpServletResponse httpResp, IVelocityGUIBuilderConfiguration config, String loggerName) throws GUIBuildException { - build(httpReq, httpResp, config, getInternalContentType(config), loggerName); - - } - - @Override - public void build(HttpServletRequest httpReq, HttpServletResponse httpResp, IVelocityGUIBuilderConfiguration config, - String contentType, String loggerName) throws GUIBuildException { - - InputStream is = null; - try { - final String viewName = config.getViewName(); - is = getTemplateInputStream(config); - - //build Velocity Context from input paramters - final VelocityContext context = buildContextFromViewParams(config.getViewParameters()); - - //evaluate template - final StringWriter writer = new StringWriter(); - engine.evaluate(context, writer, loggerName, new BufferedReader(new InputStreamReader(is))); - - //write template to response - final byte[] content = writer.toString().getBytes("UTF-8"); - httpResp.setStatus(HttpServletResponse.SC_OK); - httpResp.setContentLength(content.length); - httpResp.setContentType(contentType); - httpResp.getOutputStream().write(content); - - if (log.isTraceEnabled()) { - log.trace("Write Content for viewName:" + viewName - + ". Contentsize:" + String.valueOf(content.length) - + " BufferSize:" + httpResp.getBufferSize() - + " ContentType:" + contentType); - for (final String el : httpResp.getHeaderNames()) - log.trace(" * Headername:" + el + " Value:" + httpResp.getHeader(el)); - - } - - } catch (final IOException e) { - log.error("GUI form-builder has an internal error.", e); - throw new GUIBuildException("GUI form-builder has an internal error.", e); - - } finally { - if (is != null) - try { - is.close(); - - } catch (final IOException e) { - log.error("Can NOT close GUI-Template InputStream.", e); - - } - } - - } - - /** - * Generate a new {@link VelocityContext} and populate it with MOA-ID GUI parameters - * - * @param config - * @return - */ - @Override - public VelocityContext generateVelocityContextFromConfiguration(IVelocityGUIBuilderConfiguration config) { - return buildContextFromViewParams(config.getViewParameters()); - - } - - /** - * Load the template from different resources - * - * @param config - * @return An {@link InputStream} but never null. The {@link InputStream} had to be closed be the invoking method - * @throws GUIBuildException - */ - @Override - public InputStream getTemplateInputStream(IVelocityGUIBuilderConfiguration config) throws GUIBuildException { - InputStream is = config.getTemplate(config.getViewName()); - if (is == null) { - log.trace("Loading GUI template:" + config.getViewName() + " from default resources ... "); - is = getInternalTemplate(config); - - if (is == null) { - log.warn("No GUI with viewName:" + config.getViewName() + " FOUND."); - throw new GUIBuildException("No GUI with viewName:" + config.getViewName() + " FOUND."); - - } - } - return is; - - } - - /** - * Load an internal template from default resources - * - * @param config - * @return - * @throws GUIBuildException - */ - abstract protected InputStream getInternalTemplate(IVelocityGUIBuilderConfiguration config) throws GUIBuildException; - - - /** - * @return - */ - protected String getInternalClasspathTemplateDir(IVelocityGUIBuilderConfiguration config, String defaultClassPathDir) { - String dir = config.getClasspathTemplateDir(); - if (dir != null) { - if (!dir.endsWith("/")) - dir += "/"; - - return dir; - - } else - return defaultClassPathDir; - } - - /** - * @param viewParams - * @return - */ - private VelocityContext buildContextFromViewParams(Map viewParams) { - final VelocityContext context = new VelocityContext(); - - if (viewParams != null) { - final Iterator> interator = viewParams.entrySet().iterator(); - while (interator.hasNext()) { - final Entry el = interator.next(); - context.put(el.getKey(), el.getValue()); - } - - } - - return context; - } - - private String getInternalContentType(IGUIBuilderConfiguration config) { - if (StringUtils.isEmpty(config.getDefaultContentType())) - return DEFAULT_CONTENT_TYPE; - - else - return config.getDefaultContentType(); - - } - -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractVelocityGuiFormBuilderImpl.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractVelocityGuiFormBuilderImpl.java new file mode 100644 index 00000000..0ab5fa49 --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/AbstractVelocityGuiFormBuilderImpl.java @@ -0,0 +1,250 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.impl.gui; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.StringWriter; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; +import at.gv.egiz.eaaf.core.api.gui.IGuiBuilderConfiguration; +import at.gv.egiz.eaaf.core.api.gui.IVelocityGuiBuilderConfiguration; +import at.gv.egiz.eaaf.core.api.gui.IVelocityGuiFormBuilder; +import at.gv.egiz.eaaf.core.exceptions.GuiBuildException; +import at.gv.egiz.eaaf.core.impl.gui.velocity.VelocityProvider; +import org.apache.commons.lang3.StringUtils; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Abstract VeloCity based GUI builder implementation. + * + * @author tlenz + * + */ +public abstract class AbstractVelocityGuiFormBuilderImpl implements IVelocityGuiFormBuilder { + private static final Logger log = + LoggerFactory.getLogger(AbstractVelocityGuiFormBuilderImpl.class); + private static final String DEFAULT_CONTENT_TYPE = EAAFConstants.CONTENTTYPE_HTML_UTF8; + + private VelocityEngine engine; + + /** + * Velocity based GUI builder. + * + * @throws GuiBuildException In case of a error + */ + public AbstractVelocityGuiFormBuilderImpl() throws GuiBuildException { + try { + engine = VelocityProvider.getClassPathVelocityEngine(); + + } catch (final Exception e) { + log.error("Initialization of Velocity-Engine to render GUI components FAILED.", e); + throw new GuiBuildException( + "Initialization of Velocity-Engine to render GUI components FAILED.", e); + + } + + } + + @Override + public final void build(final HttpServletRequest httpReq, final HttpServletResponse httpResp, + final IGuiBuilderConfiguration config, final String loggerName) throws GuiBuildException { + if (config instanceof IVelocityGuiBuilderConfiguration) { + build(httpReq, httpResp, (IVelocityGuiBuilderConfiguration) config, loggerName); + } else { + throw new IllegalStateException(this.getClass().getName() + " needs a " + + IVelocityGuiBuilderConfiguration.class.getName()); + } + + + } + + @Override + public final void build(final HttpServletRequest httpReq, final HttpServletResponse httpResp, + final IGuiBuilderConfiguration config, final String contentType, final String loggerName) + throws GuiBuildException { + if (config instanceof IVelocityGuiBuilderConfiguration) { + build(httpReq, httpResp, (IVelocityGuiBuilderConfiguration) config, contentType, loggerName); + } else { + throw new IllegalStateException(this.getClass().getName() + " needs a " + + IVelocityGuiBuilderConfiguration.class.getName()); + } + + } + + @Override + public void build(final HttpServletRequest httpReq, final HttpServletResponse httpResp, + final IVelocityGuiBuilderConfiguration config, final String loggerName) + throws GuiBuildException { + build(httpReq, httpResp, config, getInternalContentType(config), loggerName); + + } + + @Override + public void build(final HttpServletRequest httpReq, final HttpServletResponse httpResp, + final IVelocityGuiBuilderConfiguration config, final String contentType, + final String loggerName) throws GuiBuildException { + + InputStream is = null; + try { + final String viewName = config.getViewName(); + is = getTemplateInputStream(config); + + // build Velocity Context from input paramters + final VelocityContext context = buildContextFromViewParams(config.getViewParameters()); + + // evaluate template + final StringWriter writer = new StringWriter(); + engine.evaluate(context, writer, loggerName, new BufferedReader(new InputStreamReader(is, "UTF-8"))); + + // write template to response + final byte[] content = writer.toString().getBytes("UTF-8"); + httpResp.setStatus(HttpServletResponse.SC_OK); + httpResp.setContentLength(content.length); + httpResp.setContentType(contentType); + httpResp.getOutputStream().write(content); + + if (log.isTraceEnabled()) { + log.trace("Write Content for viewName:" + viewName + ". Contentsize:" + + String.valueOf(content.length) + " BufferSize:" + httpResp.getBufferSize() + + " ContentType:" + contentType); + for (final String el : httpResp.getHeaderNames()) { + log.trace(" * Headername:" + el + " Value:" + httpResp.getHeader(el)); + } + + } + + } catch (final IOException e) { + log.error("GUI form-builder has an internal error.", e); + throw new GuiBuildException("GUI form-builder has an internal error.", e); + + } finally { + if (is != null) { + try { + is.close(); + + } catch (final IOException e) { + log.error("Can NOT close GUI-Template InputStream.", e); + + } + } + } + + } + + /** + * Generate a new {@link VelocityContext} and populate it with MOA-ID GUI parameters. + * + * @param config GUI builder config + * @return Context of Velocity engine + */ + @Override + public VelocityContext generateVelocityContextFromConfiguration( + final IVelocityGuiBuilderConfiguration config) { + return buildContextFromViewParams(config.getViewParameters()); + + } + + /** + * Load the template from different resources. + * + * @param config GUI builder config + * @return An {@link InputStream} but never null. The {@link InputStream} had to be closed be the + * invoking method + * @throws GuiBuildException In case of an error + */ + @Override + public InputStream getTemplateInputStream(final IVelocityGuiBuilderConfiguration config) + throws GuiBuildException { + InputStream is = config.getTemplate(config.getViewName()); + if (is == null) { + log.trace("Loading GUI template:" + config.getViewName() + " from default resources ... "); + is = getInternalTemplate(config); + + if (is == null) { + log.warn("No GUI with viewName:" + config.getViewName() + " FOUND."); + throw new GuiBuildException("No GUI with viewName:" + config.getViewName() + " FOUND."); + + } + } + return is; + + } + + /** + * Load an internal template from default resources. + * + * @param config GUI builder config + * @return Template that should be used + * @throws GuiBuildException in case of an error + */ + protected abstract InputStream getInternalTemplate(IVelocityGuiBuilderConfiguration config) + throws GuiBuildException; + + + protected String getInternalClasspathTemplateDir(final IVelocityGuiBuilderConfiguration config, + final String defaultClassPathDir) { + String dir = config.getClasspathTemplateDir(); + if (dir != null) { + if (!dir.endsWith("/")) { + dir += "/"; + } + + return dir; + + } else { + return defaultClassPathDir; + } + } + + private VelocityContext buildContextFromViewParams(final Map viewParams) { + final VelocityContext context = new VelocityContext(); + + if (viewParams != null) { + final Iterator> interator = viewParams.entrySet().iterator(); + while (interator.hasNext()) { + final Entry el = interator.next(); + context.put(el.getKey(), el.getValue()); + } + + } + + return context; + } + + private String getInternalContentType(final IGuiBuilderConfiguration config) { + if (StringUtils.isEmpty(config.getDefaultContentType())) { + return DEFAULT_CONTENT_TYPE; + } else { + return config.getDefaultContentType(); + } + + } + +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/velocity/VelocityLogAdapter.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/velocity/VelocityLogAdapter.java index a118d7e1..05cbaf58 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/velocity/VelocityLogAdapter.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/velocity/VelocityLogAdapter.java @@ -1,32 +1,26 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.gui.velocity; import org.apache.velocity.app.Velocity; +import org.apache.velocity.runtime.RuntimeConstants; import org.apache.velocity.runtime.RuntimeServices; import org.apache.velocity.runtime.log.LogChute; import org.slf4j.Logger; @@ -34,72 +28,78 @@ import org.slf4j.LoggerFactory; public class VelocityLogAdapter implements LogChute { - private static final Logger log = LoggerFactory.getLogger(VelocityLogAdapter.class); - - public VelocityLogAdapter() { - try - { - /* - * register this class as a logger with the Velocity singleton - * (NOTE: this would not work for the non-singleton method.) - */ - Velocity.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, this ); - Velocity.init(); - } - catch (Exception e) - { - log.error("Failed to register Velocity logger"); - } - } - - public void init(RuntimeServices arg0) throws Exception { - } + private static final Logger log = LoggerFactory.getLogger(VelocityLogAdapter.class); + + /** + * VeloCity Logging adapter. + * + */ + public VelocityLogAdapter() { + try { + /* + * register this class as a logger with the Velocity singleton (NOTE: this would not work for + * the non-singleton method.) + */ + Velocity.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, this); + Velocity.init(); + } catch (final Exception e) { + log.error("Failed to register Velocity logger"); + } + } + + @Override + public void init(final RuntimeServices arg0) throws Exception { + + } + + @Override + public boolean isLevelEnabled(final int arg0) { + switch (arg0) { + case LogChute.DEBUG_ID: + return log.isDebugEnabled(); + case LogChute.TRACE_ID: + return log.isTraceEnabled(); + default: + return true; + } + } - public boolean isLevelEnabled(int arg0) { - switch(arg0) { - case LogChute.DEBUG_ID: - return log.isDebugEnabled(); - case LogChute.TRACE_ID: - return log.isTraceEnabled(); - default: - return true; - } - } + @Override + public void log(final int arg0, final String arg1) { + switch (arg0) { + case LogChute.DEBUG_ID: + log.debug(arg1); + break; + case LogChute.TRACE_ID: + log.trace(arg1); + break; + case LogChute.INFO_ID: + log.info(arg1); + break; + case LogChute.WARN_ID: + log.warn(arg1); + break; + case LogChute.ERROR_ID: + default: + log.error(arg1); + break; + } + } - public void log(int arg0, String arg1) { - switch(arg0) { - case LogChute.DEBUG_ID: - log.debug(arg1); - break; - case LogChute.TRACE_ID: - log.trace(arg1); - break; - case LogChute.INFO_ID: - log.info(arg1); - break; - case LogChute.WARN_ID: - log.warn(arg1); - break; - case LogChute.ERROR_ID: - default: - log.error(arg1); - break; - } - } + @Override + public void log(final int arg0, final String arg1, final Throwable arg2) { + switch (arg0) { + case LogChute.DEBUG_ID: + case LogChute.TRACE_ID: + case LogChute.INFO_ID: + case LogChute.WARN_ID: + log.warn(arg1, arg2); + break; + case LogChute.ERROR_ID: + default: + log.error(arg1, arg2); + break; + } + } - public void log(int arg0, String arg1, Throwable arg2) { - switch(arg0) { - case LogChute.DEBUG_ID: - case LogChute.TRACE_ID: - case LogChute.INFO_ID: - case LogChute.WARN_ID: - log.warn(arg1, arg2); - break; - case LogChute.ERROR_ID: - default: - log.error(arg1, arg2); - break; - } - } - } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/velocity/VelocityProvider.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/velocity/VelocityProvider.java index 5775e203..18594985 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/velocity/VelocityProvider.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/gui/velocity/VelocityProvider.java @@ -1,121 +1,91 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ /* - * Copyright 2011 by Graz University of Technology, Austria - * The Austrian STORK Modules have been developed by the E-Government - * Innovation Center EGIZ, a joint initiative of the Federal Chancellery - * Austria and Graz University of Technology. + * Copyright 2014 Federal Chancellery Austria MOA-ID has been developed in a cooperation between + * BRZ, the Federal Chancellery Austria - ICT staff unit, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: http://www.osor.eu/eupl/ * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ - + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ -/** - * - */ package at.gv.egiz.eaaf.core.impl.gui.velocity; -import org.apache.velocity.app.Velocity; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.runtime.RuntimeConstants; /** - * Gets a Velocity Engine - * + * Gets a Velocity Engine. + * * @author bzwattendorfer * */ public class VelocityProvider { - private static VelocityEngine velocityEngine = null; - - /** - * Gets velocityEngine from Classpath - * @return VelocityEngine - * @throws Exception - */ - public static VelocityEngine getClassPathVelocityEngine() throws Exception { - if (velocityEngine == null) { - velocityEngine = getBaseVelocityEngine(); - velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); - velocityEngine.setProperty("classpath.resource.loader.class", - "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); - velocityEngine.init(); - - } - - return velocityEngine; - } - - /** - * Gets VelocityEngine from File - * @param rootPath File Path to template file - * @return VelocityEngine - * @throws Exception - */ - public static VelocityEngine getFileVelocityEngine(String rootPath) throws Exception { - if (velocityEngine == null) { - velocityEngine = getBaseVelocityEngine(); - velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "file"); - velocityEngine.setProperty("file.resource.loader.class", - "org.apache.velocity.runtime.resource.loader.FileResourceLoader"); - velocityEngine.setProperty("file.resource.loader.path", rootPath); - - velocityEngine.init(); - - } - - return velocityEngine; - } - - /** - * Gets a basic VelocityEngine - * @return VelocityEngine - */ - private static VelocityEngine getBaseVelocityEngine() { - VelocityEngine velocityEngine = new VelocityEngine(); - velocityEngine.setProperty(RuntimeConstants.INPUT_ENCODING, "UTF-8"); - velocityEngine.setProperty(RuntimeConstants.OUTPUT_ENCODING, "UTF-8"); -// velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, -// "org.apache.velocity.runtime.log.SimpleLog4JLogSystem"); - velocityEngine.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, new VelocityLogAdapter() ); - - return velocityEngine; - } - + private static VelocityEngine velocityEngine = null; + + /** + * Gets velocityEngine from Classpath. + * + * @return VelocityEngine + * @throws Exception In case of an error + */ + public static VelocityEngine getClassPathVelocityEngine() throws Exception { + if (velocityEngine == null) { + velocityEngine = getBaseVelocityEngine(); + velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); + velocityEngine.setProperty("classpath.resource.loader.class", + "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); + velocityEngine.init(); + + } + + return velocityEngine; + } + + /** + * Gets VelocityEngine from File. + * + * @param rootPath File Path to template file + * @return VelocityEngine + * @throws Exception in case of an error + */ + public static VelocityEngine getFileVelocityEngine(final String rootPath) throws Exception { + if (velocityEngine == null) { + velocityEngine = getBaseVelocityEngine(); + velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "file"); + velocityEngine.setProperty("file.resource.loader.class", + "org.apache.velocity.runtime.resource.loader.FileResourceLoader"); + velocityEngine.setProperty("file.resource.loader.path", rootPath); + + velocityEngine.init(); + + } + + return velocityEngine; + } + + /** + * Gets a basic VelocityEngine. + * + * @return VelocityEngine + */ + private static VelocityEngine getBaseVelocityEngine() { + final VelocityEngine velocityEngine = new VelocityEngine(); + velocityEngine.setProperty(RuntimeConstants.INPUT_ENCODING, "UTF-8"); + velocityEngine.setProperty(RuntimeConstants.OUTPUT_ENCODING, "UTF-8"); + // velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, + // "org.apache.velocity.runtime.log.SimpleLog4JLogSystem"); + velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, new VelocityLogAdapter()); + + return velocityEngine; + } + } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/AuthenticationData.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/AuthenticationData.java index a6bf247a..a02498b7 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/AuthenticationData.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/AuthenticationData.java @@ -1,29 +1,22 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp; import java.io.Serializable; @@ -35,492 +28,547 @@ import java.util.Date; import java.util.List; import java.util.Map; import java.util.TimeZone; - +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.auth.data.IIdentityLink; +import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; +import at.gv.egiz.eaaf.core.impl.data.Pair; import org.apache.commons.collections4.map.HashedMap; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.auth.data.IIdentityLink; -import at.gv.egiz.eaaf.core.exceptions.EAAFStorageException; -import at.gv.egiz.eaaf.core.impl.data.Pair; - /** + * Service-Provider specific authentication data. + * * @author tlenz * */ -public class AuthenticationData implements IAuthData, Serializable { - - private static final Logger log = LoggerFactory.getLogger(AuthenticationData.class); - - private static final long serialVersionUID = -1042697056735596866L; - public static final String IDENTITY_LINK_DATE_FORMAT = "yyyy-MM-dd"; - - private boolean isBaseIDTransferRestrication = true; - private final Map genericDataStorate = new HashedMap(); - - private String issuer; - private Date issueInstant; - - @Deprecated private String identificationValue; - @Deprecated private String identificationType; - @Deprecated private IIdentityLink identityLink = null; - - private String familyName; - private String givenName; - private Date dateOfBirth; - - private String encSourceId; - private String encSourceIdType; - - - - @Deprecated private String bPK; - @Deprecated private String bPKType; - @Deprecated private List> additionalBpks; - - private String ccc = null; - - - private boolean foreigner =false; - private String eIDASLoA = null; - - private boolean ssoSession = false; - private Date ssoSessionValidTo = null; - - private String sessionIndex = null; - private String nameID = null; - private String nameIDFormat = null; - - public AuthenticationData() { - this.issueInstant = new Date(); - - } - - @Override - public String getAuthenticationIssuer() { - return this.issuer; - } - - /** - * Set an unique identifier for the IDP that authenticates the user - * - * @param authIssuer - */ - public void setAuthenticationIssuer(final String authIssuer) { - this.issuer = authIssuer; - - } - - - @Override - public Date getAuthenticationIssueInstant() { - return this.issueInstant; - } - - - @Override - public String getAuthenticationIssueInstantString() { - final SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); - f.setTimeZone(TimeZone.getTimeZone("UTC")); - return f.format(this.issueInstant); - - } - - /** - * Set the timestamp for this user authentication process - * - * @param date - */ - public void setAuthenticationIssueInstant(final Date date) { - this.issueInstant = date; - } - - @Override - public String getCiticenCountryCode() { - return this.ccc; - } - - - @Override - @Deprecated - public String getBPK() { - return bPK; - } - - /** - * Sets the bPK. - * @param bPK The bPK to set - */ - @Deprecated - public void setBPK(final String bPK) { - this.bPK = bPK; - } - - - @Override - public Date getDateOfBirth() { - return this.dateOfBirth; - } - - @Override - public String getFormatedDateOfBirth() { - final DateFormat pvpDateFormat = new SimpleDateFormat(IDENTITY_LINK_DATE_FORMAT); - if (getDateOfBirth() != null) - return pvpDateFormat.format(getDateOfBirth()); - else - return "2999-12-31"; - - } - - - @Override - public String getFamilyName() { - return this.familyName; - } - - - @Override - public String getGivenName() { - return this.givenName; - } - - @Override - public String getEncryptedSourceId() { - return this.encSourceId; - } - - @Override - public String getEncryptedSourceIdType() { - return this.encSourceIdType; - } - - @Override - @Deprecated - public String getIdentificationValue() { - return identificationValue; - } - - - @Override - @Deprecated - public String getIdentificationType() { - return identificationType; - } - - @Override - @Deprecated - public IIdentityLink getIdentityLink() { - return identityLink; - } - - /** - * @param identityLink the identityLink to set - */ - @Deprecated - public void setIdentityLink(final IIdentityLink identityLink) { - this.identityLink = identityLink; - } - - /** - * Sets the dateOfBirth. - * @param dateOfBirth The dateOfBirth to set - */ - public void setDateOfBirth(final Date dateOfBirth) { - this.dateOfBirth = dateOfBirth; - } - - public void setDateOfBirth(final String dateOfBirth) { - try { - if (StringUtils.isNotEmpty(dateOfBirth)) { - final DateFormat identityLinkFormat = new SimpleDateFormat(IDENTITY_LINK_DATE_FORMAT); - this.dateOfBirth = identityLinkFormat.parse(dateOfBirth); - - } - - } catch (final ParseException e) { - log.warn("Parse dateOfBirht from IdentityLink FAILED", e); - - } - } - - /** - * Sets the familyName. - * @param familyName The familyName to set - */ - public void setFamilyName(final String familyName) { - this.familyName = familyName; - } - - /** - * Sets the givenName. - * @param givenName The givenName to set - */ - public void setGivenName(final String givenName) { - this.givenName = givenName; - } - - /** - * Sets the identificationValue. - * @param identificationValue The identificationValue to set - */ - @Deprecated - public void setIdentificationValue(final String identificationValue) { - this.identificationValue = identificationValue; - } - - /** - * Sets the identificationType. - * @param identificationType The identificationType to set - */ - @Deprecated - public void setIdentificationType(final String identificationType) { - this.identificationType = identificationType; - } - - - @Override - @Deprecated - public String getBPKType() { - return bPKType; - } - - /** - * Set sector identifier of user's bPK - * - * @param bPKType - */ - @Deprecated - public void setBPKType(final String bPKType) { - this.bPKType = bPKType; - } - - @Override - public String getEIDASQAALevel() { - return this.eIDASLoA; - - } - - - @Override - public boolean isForeigner() { - return this.foreigner; - } - - - /** - * Indicate the the user is a foreigner - * - * @param true if the user is a foreigner, otherwise false - */ - public void setForeigner(final boolean foreigner) { - this.foreigner = foreigner; - } - - @Override - public boolean isSsoSession() { - return ssoSession; - } - - - /** - * Indicate that the authentication was done by using an active SSO session - * - * @param true if a SSO was used, otherwise false - */ - public void setSsoSession(final boolean ssoSession) { - this.ssoSession = ssoSession; - } - - - /** - * Country Code for the authenticated user - * - * @param ccc Two letter country code - */ - public void setCiticenCountryCode(final String ccc) { - this.ccc = ccc; - } - - @Override - public String getSessionIndex() { - return sessionIndex; - } - - /** - * @param sessionIndex the sessionIndex to set - */ - public void setSessionIndex(final String sessionIndex) { - this.sessionIndex = sessionIndex; - } - - - @Override - public String getNameID() { - return this.nameID; - } - - /** - * @param nameID the nameID to set - */ - public void setNameID(final String nameID) { - this.nameID = nameID; - } - - /** - * @return the nameIDFormat - */ - @Override - public String getNameIDFormat() { - return nameIDFormat; - } - - /** - * @param nameIDFormat the nameIDFormat to set - */ - public void setNameIDFormat(final String nameIDFormat) { - this.nameIDFormat = nameIDFormat; - } - - /** - * @return the ssoSessionValidTo - */ - @Override - public Date getSsoSessionValidTo() { - return ssoSessionValidTo; - } - - /** - * @param ssoSessionValidTo the ssoSessionValidTo to set - */ - public void setSsoSessionValidTo(final Date ssoSessionValidTo) { - this.ssoSessionValidTo = ssoSessionValidTo; - } - - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.data.IAuthData#isBusinessService() - */ - @Override - public boolean isBaseIDTransferRestrication() { - return isBaseIDTransferRestrication; - } - - /** - * @param isBaseIDTransmittionAllowed the isBaseIDTransmittionAllowed to set - */ - public void setBaseIDTransferRestrication(final boolean isBaseIDTransferRestrication) { - this.isBaseIDTransferRestrication = isBaseIDTransferRestrication; - } - - /** - * Returns a generic data-object with is stored with a specific identifier - * - * @param key The specific identifier of the data object - * @param clazz The class type which is stored with this key - * @return The data object or null if no data is found with this key - */ - @Override - public T getGenericData(final String key, final Class clazz) { - if (StringUtils.isNotEmpty(key)) { - final Object data = genericDataStorate.get(key); - - if (data == null) - return null; - - try { - @SuppressWarnings("unchecked") - final - T test = (T) data; - return test; - - } catch (final Exception e) { - log.warn("Generic authentication-data object can not be casted to requsted type", e); - return null; - - } - - } - - log.info("Can not load generic session-data with key='null'"); - return null; - - } - - /** - * Store a generic data-object to session with a specific identifier - * - * @param key Identifier for this data-object - * @param object Generic data-object which should be stored. This data-object had to be implement the 'java.io.Serializable' interface - * @throws SessionDataStorageException Error message if the data-object can not stored to generic session-data storage - */ - public void setGenericData(final String key, final Object object) throws EAAFStorageException { - if (StringUtils.isEmpty(key)) { - log.info("Generic session-data can not be stored with a 'null' key"); - throw new EAAFStorageException("Generic data can not be stored with a 'null' key", null); - - } - - if (object != null) { - if (!Serializable.class.isInstance(object)) { - log.warn("Generic data can only store objects which implements the 'Seralizable' interface"); - throw new EAAFStorageException("Generic data can only store objects which implements the 'Seralizable' interface", null); - - } - } - - if (genericDataStorate.containsKey(key)) - log.debug("Overwrite generic data with key:" + key); - else - log.trace("Add generic data with key:" + key + " to session."); - - genericDataStorate.put(key, object); - } - - public void seteIDASLoA(final String eIDASLoA) { - this.eIDASLoA = eIDASLoA; - } - - @Override - @Deprecated - public List> getAdditionalbPKs() { - return this.additionalBpks; - } - - - /** - * Set the encrypted SourceId for current authenticated user - * - * @param encSourceId - */ - public void setEncSourceId(final String encSourceId) { - this.encSourceId = encSourceId; - } - - /** - * Set the type identifier of the encrypted SourceId - * - * @param encSourceIdType - */ - public void setEncSourceIdType(final String encSourceIdType) { - this.encSourceIdType = encSourceIdType; - } - - - - /** - * Add an additional bPK Pair into authdata - * - * @param bPK Pair - */ - @Deprecated - public void addAdditionalbPKPair(final Pair bPK) { - if (this.additionalBpks == null) { - this.additionalBpks = new ArrayList>(); - - } - - this.additionalBpks.add(bPK); - } +public class AuthenticationData implements IAuthData, Serializable { + + private static final Logger log = LoggerFactory.getLogger(AuthenticationData.class); + + private static final long serialVersionUID = -1042697056735596866L; + public static final String IDENTITY_LINK_DATE_FORMAT = "yyyy-MM-dd"; + + private boolean isBaseIdTransferRestrication = true; + private final Map genericDataStorate = new HashedMap<>(); + + private String issuer; + private Date issueInstant; + + @Deprecated + private String identificationValue; + @Deprecated + private String identificationType; + @Deprecated + private IIdentityLink identityLink = null; + + private String familyName; + private String givenName; + private Date dateOfBirth; + + private String encSourceId; + private String encSourceIdType; + + + + @Deprecated + private String bpk; + @Deprecated + private String bpkType; + @Deprecated + private List> additionalBpks; + + private String ccc = null; + + + private boolean foreigner = false; + private String eidasLoa = null; + + private boolean ssoSession = false; + private Date ssoSessionValidTo = null; + + private String sessionIndex = null; + private String nameID = null; + private String nameIdFormat = null; + + public AuthenticationData() { + this.issueInstant = new Date(); + + } + + @Override + public String getAuthenticationIssuer() { + return this.issuer; + } + + /** + * Set an unique identifier for the IDP that authenticates the user. + * + * @param authIssuer Issuer of this authentication information + */ + public void setAuthenticationIssuer(final String authIssuer) { + this.issuer = authIssuer; + + } + + + @Override + public Date getAuthenticationIssueInstant() { + return getDateCopyOrNull(this.issueInstant); + + } + + + @Override + public String getAuthenticationIssueInstantString() { + final SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); + f.setTimeZone(TimeZone.getTimeZone("UTC")); + return f.format(this.issueInstant); + + } + + /** + * Set the timestamp for this user authentication process. + * + * @param date Authentication data + */ + public void setAuthenticationIssueInstant(final Date date) { + this.issueInstant = getDateCopyOrNull(date); + } + + @Override + public String getCiticenCountryCode() { + return this.ccc; + } + + + @Override + @Deprecated + public String getBpk() { + return bpk; + } + + /** + * Sets the bPK. + * + * @param bpk The bPK to set + */ + @Deprecated + public void setBpk(final String bpk) { + this.bpk = bpk; + } + + + @Override + public Date getDateOfBirth() { + return getDateCopyOrNull(this.dateOfBirth); + + } + + + + @Override + public String getFormatedDateOfBirth() { + final DateFormat pvpDateFormat = new SimpleDateFormat(IDENTITY_LINK_DATE_FORMAT); + if (getDateOfBirth() != null) { + return pvpDateFormat.format(getDateOfBirth()); + } else { + return "2999-12-31"; + } + + } + + + @Override + public String getFamilyName() { + return this.familyName; + } + + + @Override + public String getGivenName() { + return this.givenName; + } + + @Override + public String getEncryptedSourceId() { + return this.encSourceId; + } + + @Override + public String getEncryptedSourceIdType() { + return this.encSourceIdType; + } + + @Override + @Deprecated + public String getIdentificationValue() { + return identificationValue; + } + + + @Override + @Deprecated + public String getIdentificationType() { + return identificationType; + } + + @Override + @Deprecated + public IIdentityLink getIdentityLink() { + return identityLink; + } + + /** + * Set the IdentityLink. + * + * @param identityLink the identityLink to set + */ + @Deprecated + public void setIdentityLink(final IIdentityLink identityLink) { + this.identityLink = identityLink; + } + + /** + * Sets the dateOfBirth. + * + * @param dateOfBirth The dateOfBirth to set + */ + public void setDateOfBirth(final Date dateOfBirth) { + this.dateOfBirth = getDateCopyOrNull(dateOfBirth); + } + + /** + * Set the date of birth. + * + * @param dateOfBirth date of birth String as "yyyy-MM-dd" + */ + public void setDateOfBirth(final String dateOfBirth) { + try { + if (StringUtils.isNotEmpty(dateOfBirth)) { + final DateFormat identityLinkFormat = new SimpleDateFormat(IDENTITY_LINK_DATE_FORMAT); + this.dateOfBirth = identityLinkFormat.parse(dateOfBirth); + + } + + } catch (final ParseException e) { + log.warn("Parse dateOfBirht from IdentityLink FAILED", e); + + } + } + + /** + * Sets the familyName. + * + * @param familyName The familyName to set + */ + public void setFamilyName(final String familyName) { + this.familyName = familyName; + } + + /** + * Sets the givenName. + * + * @param givenName The givenName to set + */ + public void setGivenName(final String givenName) { + this.givenName = givenName; + } + + /** + * Sets the identificationValue. + * + * @param identificationValue The identificationValue to set + */ + @Deprecated + public void setIdentificationValue(final String identificationValue) { + this.identificationValue = identificationValue; + } + + /** + * Sets the identificationType. + * + * @param identificationType The identificationType to set + */ + @Deprecated + public void setIdentificationType(final String identificationType) { + this.identificationType = identificationType; + } + + + @Override + @Deprecated + public String getBpkType() { + return bpkType; + } + + /** + * Set sector identifier of user's bPK. + * + * @param bpkType bPK type + */ + @Deprecated + public void setBpkType(final String bpkType) { + this.bpkType = bpkType; + } + + @Override + public String getEidasQaaLevel() { + return this.eidasLoa; + + } + + + @Override + public boolean isForeigner() { + return this.foreigner; + } + + + /** + * Indicate the the user is a foreigner. + * + * @param foreigner true if the user is a foreigner, otherwise false + */ + public void setForeigner(final boolean foreigner) { + this.foreigner = foreigner; + } + + @Override + public boolean isSsoSession() { + return ssoSession; + } + + + /** + * Indicate that the authentication was done by using an active SSO session. + * + * @param ssoSession true if a SSO was used, otherwise false + */ + public void setSsoSession(final boolean ssoSession) { + this.ssoSession = ssoSession; + } + + + /** + * Country Code for the authenticated user. + * + * @param ccc Two letter country code + */ + public void setCiticenCountryCode(final String ccc) { + this.ccc = ccc; + } + + @Override + public String getSessionIndex() { + return sessionIndex; + } + + /** + * Set an index for this session. + * + * @param sessionIndex the sessionIndex to set. + */ + public void setSessionIndex(final String sessionIndex) { + this.sessionIndex = sessionIndex; + } + + + @Override + public String getNameID() { + return this.nameID; + } + + /** + * Set User's nameId. + * + * @param nameID the nameID to set. + */ + public void setNameID(final String nameID) { + this.nameID = nameID; + } + + /** + * Get format of User's NameId. + * + * @return the nameIDFormat. + */ + @Override + public String getNameIdFormat() { + return nameIdFormat; + } + + /** + * Set format of User's NameId. + * + * @param nameIdFormat the nameIDFormat to set. + */ + public void setNameIdFormat(final String nameIdFormat) { + this.nameIdFormat = nameIdFormat; + } + + /** + * Get SSO session valid period. + * + * @return the ssoSessionValidTo + */ + @Override + public Date getSsoSessionValidTo() { + return getDateCopyOrNull(ssoSessionValidTo); + } + + /** + * Set SSO session valid period. + * + * @param ssoSessionValidTo the ssoSessionValidTo to set + */ + public void setSsoSessionValidTo(final Date ssoSessionValidTo) { + this.ssoSessionValidTo = getDateCopyOrNull(ssoSessionValidTo); + } + + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.data.IAuthData#isBusinessService() + */ + @Override + public boolean isBaseIdTransferRestrication() { + return isBaseIdTransferRestrication; + } + + /** + * Set baseId transfer restriction. + * + * @param isBaseIdTransferRestrication the isBaseIDTransmittionAllowed to set + */ + public void setBaseIdTransferRestrication(final boolean isBaseIdTransferRestrication) { + this.isBaseIdTransferRestrication = isBaseIdTransferRestrication; + } + + /** + * Returns a generic data-object with is stored with a specific identifier. + * + * @param key The specific identifier of the data object + * @param clazz The class type which is stored with this key + * @return The data object or null if no data is found with this key + */ + @Override + public T getGenericData(final String key, final Class clazz) { + if (StringUtils.isNotEmpty(key)) { + final Object data = genericDataStorate.get(key); + + if (data == null) { + return null; + } + + try { + @SuppressWarnings("unchecked") + final T test = (T) data; + return test; + + } catch (final Exception e) { + log.warn("Generic authentication-data object can not be casted to requsted type", e); + return null; + + } + + } + + log.info("Can not load generic session-data with key='null'"); + return null; + + } + + /** + * Store a generic data-object to session with a specific identifier. + * + * @param key Identifier for this data-object + * @param object Generic data-object which should be stored. This data-object had to be implement + * the 'java.io.Serializable' interface + * @throws SessionDataStorageException Error message if the data-object can not stored to generic + * session-data storage + */ + public void setGenericData(final String key, final Object object) throws EaafStorageException { + if (StringUtils.isEmpty(key)) { + log.info("Generic session-data can not be stored with a 'null' key"); + throw new EaafStorageException("Generic data can not be stored with a 'null' key", null); + + } + + if (object != null) { + if (!Serializable.class.isInstance(object)) { + log.warn( + "Generic data can only store objects which implements the 'Seralizable' interface"); + throw new EaafStorageException( + "Generic data can only store objects which implements the 'Seralizable' interface", + null); + + } + } + + if (genericDataStorate.containsKey(key)) { + log.debug("Overwrite generic data with key:" + key); + } else { + log.trace("Add generic data with key:" + key + " to session."); + } + + genericDataStorate.put(key, object); + } + + public void setEidasLoa(final String eidasLoa) { + this.eidasLoa = eidasLoa; + } + + @Override + @Deprecated + public List> getAdditionalbPKs() { + return this.additionalBpks; + } + + + /** + * Set the encrypted SourceId for current authenticated user. + * + * @param encSourceId encryped baseId + */ + public void setEncSourceId(final String encSourceId) { + this.encSourceId = encSourceId; + } + + /** + * Set the type identifier of the encrypted SourceId. + * + * @param encSourceIdType type identifier of encryped baseId + */ + public void setEncSourceIdType(final String encSourceIdType) { + this.encSourceIdType = encSourceIdType; + } + + + + /** + * Add an additional bPK Pair bPK/bPKType into authdata. + * + * @param bpk Pair bPK/bPKType + */ + @Deprecated + public void addAdditionalBpkPair(final Pair bpk) { + if (this.additionalBpks == null) { + this.additionalBpks = new ArrayList<>(); + + } + + this.additionalBpks.add(bpk); + } + + private Date getDateCopyOrNull(Date in) { + if (in != null) { + return new Date(in.getTime()); + } else { + return null; + } + } + } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/EAAFCoreSpringResourceProvider.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/EAAFCoreSpringResourceProvider.java deleted file mode 100644 index c7c8010b..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/EAAFCoreSpringResourceProvider.java +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp; - -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; - -import at.gv.egiz.components.spring.api.SpringResourceProvider; - -public class EAAFCoreSpringResourceProvider implements SpringResourceProvider { - - @Override - public String getName() { - return "EAAF Core SpringResourceProvider"; - } - - @Override - public String[] getPackagesToScan() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Resource[] getResourcesToLoad() { - ClassPathResource sl20AuthConfig = new ClassPathResource("/eaaf_core.beans.xml", EAAFCoreSpringResourceProvider.class); - - return new Resource[] {sl20AuthConfig}; - } - -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/EaafCoreSpringResourceProvider.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/EaafCoreSpringResourceProvider.java new file mode 100644 index 00000000..74b6a0fb --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/EaafCoreSpringResourceProvider.java @@ -0,0 +1,47 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.impl.idp; + +import at.gv.egiz.components.spring.api.SpringResourceProvider; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; + +public class EaafCoreSpringResourceProvider implements SpringResourceProvider { + + @Override + public String getName() { + return "EAAF Core SpringResourceProvider"; + } + + @Override + public String[] getPackagesToScan() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Resource[] getResourcesToLoad() { + final ClassPathResource sl20AuthConfig = + new ClassPathResource("/eaaf_core.beans.xml", EaafCoreSpringResourceProvider.class); + + return new Resource[] {sl20AuthConfig}; + } + +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/EidAuthenticationData.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/EidAuthenticationData.java index 86728c05..ea197478 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/EidAuthenticationData.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/EidAuthenticationData.java @@ -2,120 +2,124 @@ package at.gv.egiz.eaaf.core.impl.idp; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; - +import at.gv.egiz.eaaf.core.api.data.PVPAttributeDefinitions.EID_IDENTITY_STATUS_LEVEL_VALUES; +import at.gv.egiz.eaaf.core.api.idp.IEidAuthData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.lang.NonNull; import org.springframework.util.Assert; -import at.gv.egiz.eaaf.core.api.data.PVPAttributeDefinitions.EID_IDENTITY_STATUS_LEVEL_VALUES; -import at.gv.egiz.eaaf.core.api.idp.IEidAuthData; - public class EidAuthenticationData extends AuthenticationData implements IEidAuthData { - private static final Logger log = LoggerFactory.getLogger(EidAuthenticationData.class); - - - private static final long serialVersionUID = -7106142572904327044L; - - private byte[] eIDToken; - private byte[] signerCertificate; - private EID_IDENTITY_STATUS_LEVEL_VALUES eidStatus; - private String vdaEndpointUrl; - private boolean useMandate = false; - - @Override - public byte[] getSignerCertificate() { - return this.signerCertificate; - } - - @Override - public byte[] getEIDToken() { - return this.eIDToken; - } - - @Override - public EID_IDENTITY_STATUS_LEVEL_VALUES getEIDStatus() { - return this.eidStatus; - - } - - @Override - public boolean isUseMandate() { - return useMandate; - } - - @Override - public String getVdaEndPointUrl() { - return vdaEndpointUrl; - - } - - /** - * Set the status of the E-ID identity - * - * @param eidStatus - */ - public void setEidStatus(EID_IDENTITY_STATUS_LEVEL_VALUES eidStatus) { - this.eidStatus = eidStatus; - } - - /** - * Set Online IdentityLink to AuthenticationData - * - * @param eIDToken - */ - public void seteIDToken(final byte[] eIDToken) { - this.eIDToken = eIDToken; - - } - - /** - * Set the signing certificate that was used to sign the user consent - * - * @param signerCertificate - */ - public void setSignerCertificate(@NonNull final X509Certificate signerCertificate) { - Assert.notNull(signerCertificate, "Signer certificate is null"); - try { - this.signerCertificate = signerCertificate.getEncoded(); - - } catch (final CertificateEncodingException e) { - log.warn("Can NOT serialized signer-certificate", e); - log.warn("Signer certificate will be ignored"); - - } - } - - /** - * Set the signing certificate that was used to sign the user consent - * - * @param signerCertificate - */ - public void setSignerCertificate(final byte[] signerCertificate) { - this.signerCertificate = signerCertificate; - - } - - /** - * Set flag that mandates are used in this process - * - * @param useMandate true if mandates was used, otherwise false - */ - public void setUseMandate(boolean useMandate) { - this.useMandate = useMandate; - } - - - /** - * Set URL of the EndPoint that was used on VDA for authentication - * - * @param vdaEndpointUrl - */ - public void setVdaEndpointUrl(String vdaEndpointUrl) { - this.vdaEndpointUrl = vdaEndpointUrl; - } - - - - + private static final Logger log = LoggerFactory.getLogger(EidAuthenticationData.class); + + + private static final long serialVersionUID = -7106142572904327044L; + + private byte[] eidToken; + private byte[] signerCertificate; + private EID_IDENTITY_STATUS_LEVEL_VALUES eidStatus; + private String vdaEndpointUrl; + private boolean useMandate = false; + + @Override + public byte[] getSignerCertificate() { + return getByteCopyOrNull(this.signerCertificate); + } + + @Override + public byte[] getEidToken() { + return getByteCopyOrNull(this.eidToken); + } + + @Override + public EID_IDENTITY_STATUS_LEVEL_VALUES getEidStatus() { + return this.eidStatus; + + } + + @Override + public boolean isUseMandate() { + return useMandate; + } + + @Override + public String getVdaEndPointUrl() { + return vdaEndpointUrl; + + } + + /** + * Set the status of the E-ID identity. + * + * @param eidStatus Status of the E-ID + */ + public void setEidStatus(final EID_IDENTITY_STATUS_LEVEL_VALUES eidStatus) { + this.eidStatus = eidStatus; + } + + /** + * Set Online IdentityLink to AuthenticationData. + * + * @param eidToken Online-IdentityLink + */ + public void setEidToken(final byte[] eidToken) { + this.eidToken = getByteCopyOrNull(eidToken); + + } + + /** + * Set the signing certificate that was used to sign the user consent. + * + * @param signerCertificate User's signer certificate + */ + public void setSignerCertificate(@NonNull final X509Certificate signerCertificate) { + Assert.notNull(signerCertificate, "Signer certificate is null"); + try { + this.signerCertificate = signerCertificate.getEncoded(); + + } catch (final CertificateEncodingException e) { + log.warn("Can NOT serialized signer-certificate", e); + log.warn("Signer certificate will be ignored"); + + } + } + + /** + * Set the signing certificate that was used to sign the user consent. + * + * @param signerCertificate User's signer certificate + */ + public void setSignerCertificate(final byte[] signerCertificate) { + this.signerCertificate = getByteCopyOrNull(signerCertificate); + + } + + /** + * Set flag that mandates are used in this process. + * + * @param useMandate true if mandates was used, otherwise false + */ + public void setUseMandate(final boolean useMandate) { + this.useMandate = useMandate; + } + + + /** + * Set URL of the EndPoint that was used on VDA for authentication. + * + * @param vdaEndpointUrl Used VDA end-point + */ + public void setVdaEndpointUrl(final String vdaEndpointUrl) { + this.vdaEndpointUrl = vdaEndpointUrl; + } + + private byte[] getByteCopyOrNull(byte[] in) { + if (in != null) { + return in.clone(); + } else { + return null; + } + } + + } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/AbstractAuthenticationManager.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/AbstractAuthenticationManager.java index 4cefcd8d..7a967d3f 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/AbstractAuthenticationManager.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/AbstractAuthenticationManager.java @@ -1,29 +1,22 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.auth; import java.io.IOException; @@ -31,340 +24,371 @@ import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; - import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.text.StringEscapeUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.IRequestStorage; import at.gv.egiz.eaaf.core.api.data.EAAFConstants; import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; import at.gv.egiz.eaaf.core.api.idp.auth.IAuthenticationManager; -import at.gv.egiz.eaaf.core.api.idp.auth.ISSOManager; +import at.gv.egiz.eaaf.core.api.idp.auth.ISsoManager; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; import at.gv.egiz.eaaf.core.api.idp.process.ProcessEngine; import at.gv.egiz.eaaf.core.api.logging.IRevisionLogger; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.core.exceptions.EAAFSSOException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.exceptions.EaafSsoException; import at.gv.egiz.eaaf.core.exceptions.NoPassivAuthenticationException; import at.gv.egiz.eaaf.core.exceptions.ProcessExecutionException; import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; import at.gv.egiz.eaaf.core.impl.idp.auth.modules.ModuleRegistration; import at.gv.egiz.eaaf.core.impl.idp.controller.protocols.RequestImpl; import at.gv.egiz.eaaf.core.impl.idp.process.ExecutionContextImpl; -import at.gv.egiz.eaaf.core.impl.utils.TransactionIDUtils; +import at.gv.egiz.eaaf.core.impl.utils.TransactionIdUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.text.StringEscapeUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; public abstract class AbstractAuthenticationManager implements IAuthenticationManager { - private static final Logger log = LoggerFactory.getLogger(AbstractAuthenticationManager.class); - - private static List reqParameterWhiteListeForModules = new ArrayList(); - private static List reqHeaderWhiteListeForModules = new ArrayList(); - - public static final String MOA_SESSION = "MoaAuthenticationSession"; - public static final String MOA_AUTHENTICATED = "MoaAuthenticated"; - - public static final int SLOTIMEOUT = 30 * 1000; //30 sec - - @Autowired(required=true) protected IConfiguration authConfig; - @Autowired(required=true) private ProcessEngine processEngine; - @Autowired(required=true) private IRequestStorage requestStoreage; - @Autowired(required=true) protected IRevisionLogger revisionsLogger; - @Autowired(required=false) protected ISSOManager ssoManager; - - /* (non-Javadoc) - * @see at.gv.egiz.eaaf.core.impl.idp.auth.IAuthenticationManager#addParameterNameToWhiteList(java.lang.String) - */ - @Override - public final void addParameterNameToWhiteList(String httpReqParam) { - if (StringUtils.isNotEmpty(httpReqParam)) - reqParameterWhiteListeForModules.add(httpReqParam); - - } - - /* (non-Javadoc) - * @see at.gv.egiz.eaaf.core.impl.idp.auth.IAuthenticationManager#addHeaderNameToWhiteList(java.lang.String) - */ - @Override - public final void addHeaderNameToWhiteList(String httpReqParam) { - if (StringUtils.isNotEmpty(httpReqParam)) - reqHeaderWhiteListeForModules.add(httpReqParam.toLowerCase()); - - } - - /* (non-Javadoc) - * @see at.gv.egiz.eaaf.core.impl.idp.auth.IAuthenticationManager#addHeaderNameToWhiteList(java.lang.String) - */ - @Override - public final boolean doAuthentication(HttpServletRequest httpReq, HttpServletResponse httpResp, - IRequest pendingReq) throws EAAFException { - - if (!(pendingReq instanceof RequestImpl)) { - log.error("Requests that need authentication MUST be of type 'RequestImpl'"); - throw new RuntimeException("Requests that need authentication HAS TO BE of type 'RequestImpl'"); - - } - - //load OA configuration from pending request - final ISPConfiguration oaParam = pendingReq.getServiceProviderConfiguration(); - - //set logging context and log unique OA identifier to revision log - TransactionIDUtils.setServiceProviderId(oaParam.getUniqueIdentifier()); - revisionsLogger.logEvent(pendingReq, EVENT_AUTHENTICATION_PROCESS_FOR_SP, pendingReq.getSPEntityId()); - - //generic authentication request validation - if (pendingReq.isPassiv() && pendingReq.forceAuth()) { - // conflict! - throw new NoPassivAuthenticationException(); - } - - - //check Single Sign-On functionality if SSOManager is available - boolean isValidSSOSession = false; - if (ssoManager != null) { - log.trace("SSOManager is loaded. Starting SSO session validation ... "); - //check if SSO is allowed for this service provider - ssoManager.isSSOAllowedForSP(pendingReq, httpReq); - - //check if SSO session is active and valid - isValidSSOSession = ssoManager.checkAndValidateSSOSession(pendingReq, httpReq, httpResp) && - pendingReq.needSingleSignOnFunctionality(); - - - } - - //check if session is already authenticated - //boolean isSessionAuthenticated = tryPerformAuthentication((RequestImpl) pendingReq, isValidSSOSession); - //boolean isSessionAuthenticated = isValidSSOSession && StringUtils.isNotEmpty(pendingReq.getSSOSessionIdentifier()); - - - //force new authentication authentication process - if (pendingReq.forceAuth()) { - startAuthenticationProcess(httpReq, httpResp, (RequestImpl) pendingReq); - return false; - - //perform SSO-Consents evaluation if it it required - } else if (isValidSSOSession && pendingReq.isNeedUserConsent()) { - sendSingleSignOnConsentsEvaluation(httpReq, httpResp, (RequestImpl) pendingReq); - return false; - - - } else if (pendingReq.isPassiv()) { - if (isValidSSOSession && - StringUtils.isNotEmpty(pendingReq.getInternalSSOSessionIdentifier()) ) { - // Passive authentication ok! --> Populate pending request from SSO session - ssoManager.populatePendingRequestWithSSOInformation(pendingReq); - revisionsLogger.logEvent(pendingReq, EVENT_AUTHENTICATION_PROCESS_FINISHED); - return true; - - } else { - throw new NoPassivAuthenticationException(); - - } - - } else { - if (isValidSSOSession && - StringUtils.isNotEmpty(pendingReq.getInternalSSOSessionIdentifier())) { - // Is authenticated .. proceed - ssoManager.populatePendingRequestWithSSOInformation(pendingReq); - revisionsLogger.logEvent(pendingReq, EVENT_AUTHENTICATION_PROCESS_FINISHED); - return true; - - } else { - // Start authentication! - startAuthenticationProcess(httpReq, httpResp, (RequestImpl) pendingReq); - return false; - - } - } - } - - @Override - public final void performOnlyIDPLogOut(HttpServletRequest request, HttpServletResponse response, IRequest pendingReq) { - - log.debug("Close session. Remove pending request ... "); - requestStoreage.removePendingRequest(pendingReq.getPendingRequestId()); - - - if (ssoManager != null) { - try { - log.trace("'SSOManager' active. Search for active SSO sessions ... "); - if (ssoManager.destroySSOSessionOnIDPOnly(request, response, pendingReq)) - log.info("SSO session successfully closed"); - else - log.info("Closing SSO session NOT successfully"); - - } catch (final EAAFSSOException e) { - log.warn("Destroying of SSO session FAILED. Reason: " + e.getMessage(), e); - - } - - } - - } - - /** - * Populate process execution context and start process engine - * - * @param httpReq - * @param httpResp - * @param pendingReq - * @throws ServletException - * @throws IOException - * @throws EAAFException - */ - private void startAuthenticationProcess(HttpServletRequest httpReq, - HttpServletResponse httpResp, RequestImpl pendingReq) - throws EAAFException { - - log.info("Starting authentication ..."); - revisionsLogger.logEvent(pendingReq, EVENT_AUTHENTICATION_PROCESS_STARTED); - - //create authentication process execution context - final ExecutionContext executionContext = new ExecutionContextImpl(); - - //set oaIdentifeir - executionContext.put(EAAFConstants.PROCESS_ENGINE_SERVICE_PROVIDER_ENTITYID, - pendingReq.getServiceProviderConfiguration().getUniqueIdentifier()); - - //add X509 SSL client certificate if exist - if (httpReq.getAttribute("javax.servlet.request.X509Certificate") != null) { - log.debug("Find SSL-client-certificate on request --> Add it to context"); - executionContext.put(EAAFConstants.PROCESS_ENGINE_SSL_CLIENT_CERTIFICATE, - ((X509Certificate[])httpReq.getAttribute("javax.servlet.request.X509Certificate"))); - pendingReq.setRawDataToTransaction(EAAFConstants.PROCESS_ENGINE_SSL_CLIENT_CERTIFICATE, - (httpReq.getAttribute("javax.servlet.request.X509Certificate"))); - - } - - //add additional http request parameter to context - if (!reqParameterWhiteListeForModules.isEmpty()) { - final Enumeration reqParamNames = httpReq.getParameterNames(); - while(reqParamNames.hasMoreElements()) { - final String paramName = reqParamNames.nextElement(); - if (StringUtils.isNotEmpty(paramName) && reqParameterWhiteListeForModules.contains(paramName) ) - executionContext.put(paramName, StringEscapeUtils.escapeHtml4(httpReq.getParameter(paramName))); - } - } - - //add additional http request parameter to context - if (!reqHeaderWhiteListeForModules.isEmpty()) { - final Enumeration reqHeaderNames = httpReq.getHeaderNames(); - while(reqHeaderNames.hasMoreElements()) { - final String paramName = reqHeaderNames.nextElement(); - if (StringUtils.isNotEmpty(paramName) - && at.gv.egiz.eaaf.core.impl.utils.ArrayUtils.containsCaseInsensitive(paramName, reqHeaderWhiteListeForModules) - //reqHeaderWhiteListeForModules.contains(paramName.toLowerCase()) - ) - executionContext.put(paramName.toLowerCase(), StringEscapeUtils.escapeHtml4(httpReq.getHeader(paramName))); - - } - } - - - - //populate more IDP specific information to execution context - populateExecutionContext(executionContext, pendingReq, httpReq); - - //start process engine - startProcessEngine(pendingReq, executionContext); - - } - - /** - * - * - * @throws EAAFException - */ - abstract protected void populateExecutionContext(ExecutionContext executionContext, - RequestImpl pendingReq, HttpServletRequest httpReq) throws EAAFException; - - /** - * Starting a user consent evaluation - * - * @param request - * @param response - * @param pendingReq - * @throws ServletException - * @throws IOException - * @throws EAAFException - */ - private void sendSingleSignOnConsentsEvaluation(HttpServletRequest request, - HttpServletResponse response, RequestImpl pendingReq) - throws EAAFException { - - log.debug("Starting SSO user-consents evaluation ..."); - - //set authenticated flag to false, because user consents is required - pendingReq.setAuthenticated(false); - - //create execution context - final ExecutionContext executionContext = new ExecutionContextImpl(); - executionContext.put(ISSOManager.PROCESS_ENGINE_SSO_CONSENTS_EVALUATION, true); - - //start process engine - startProcessEngine(pendingReq, executionContext); - - } - - - /** - * Select a specific process and starting process engine - * - * @param pendingReq - * @param executionContext - * @throws EAAFException - */ - private void startProcessEngine(RequestImpl pendingReq, ExecutionContext executionContext) throws EAAFException { - try { - //put pending-request ID on execurtionContext - executionContext.put(EAAFConstants.PROCESS_ENGINE_PENDINGREQUESTID, pendingReq.getPendingRequestId()); - - // create process instance - final String processDefinitionId = ModuleRegistration.getInstance().selectProcess(executionContext, pendingReq); - - if (processDefinitionId == null) { - log.warn("No suitable process found for PendingReqId " + pendingReq.getPendingRequestId() ); - throw new EAAFException( - "process.02", - new Object[] {pendingReq.getPendingRequestId()}); - - } - - final String processInstanceId = processEngine.createProcessInstance(processDefinitionId, executionContext); - - // keep process instance id in protocol pending-request - pendingReq.setProcessInstanceId(processInstanceId); - - //store pending-request - requestStoreage.storePendingRequest(pendingReq); - - // start process - processEngine.start(pendingReq); - - } catch (final ProcessExecutionException e) { - final Throwable cause = e.getCause(); - if (cause != null && cause instanceof TaskExecutionException) { - final Throwable taskCause = cause.getCause(); - if (taskCause != null && taskCause instanceof EAAFException) { - final EAAFException moaTaskCause = (EAAFException) taskCause; - log.warn(taskCause.getMessage(), taskCause); - throw moaTaskCause; - - } - } - - throw new EAAFException( - "process.01", - new Object[] { pendingReq.getProcessInstanceId(), pendingReq.getPendingRequestId() }, e); - } - - } + private static final Logger log = LoggerFactory.getLogger(AbstractAuthenticationManager.class); + + private static List reqParameterWhiteListeForModules = new ArrayList<>(); + private static List reqHeaderWhiteListeForModules = new ArrayList<>(); + + public static final String MOA_SESSION = "MoaAuthenticationSession"; + public static final String MOA_AUTHENTICATED = "MoaAuthenticated"; + + public static final int SLOTIMEOUT = 30 * 1000; // 30 sec + + @Autowired(required = true) + protected IConfiguration authConfig; + @Autowired(required = true) + private ProcessEngine processEngine; + @Autowired(required = true) + private IRequestStorage requestStoreage; + @Autowired(required = true) + protected IRevisionLogger revisionsLogger; + @Autowired(required = false) + protected ISsoManager ssoManager; + @Autowired ModuleRegistration moduleRegistration; + + /* + * (non-Javadoc) + * + * @see + * at.gv.egiz.eaaf.core.impl.idp.auth.IAuthenticationManager#addParameterNameToWhiteList(java.lang + * .String) + */ + @Override + public final void addParameterNameToWhiteList(final String httpReqParam) { + if (StringUtils.isNotEmpty(httpReqParam)) { + reqParameterWhiteListeForModules.add(httpReqParam); + } + + } + + /* + * (non-Javadoc) + * + * @see + * at.gv.egiz.eaaf.core.impl.idp.auth.IAuthenticationManager#addHeaderNameToWhiteList(java.lang. + * String) + */ + @Override + public final void addHeaderNameToWhiteList(final String httpReqParam) { + if (StringUtils.isNotEmpty(httpReqParam)) { + reqHeaderWhiteListeForModules.add(httpReqParam.toLowerCase()); + } + + } + + /* + * (non-Javadoc) + * + * @see + * at.gv.egiz.eaaf.core.impl.idp.auth.IAuthenticationManager#addHeaderNameToWhiteList(java.lang. + * String) + */ + @Override + public final boolean doAuthentication(final HttpServletRequest httpReq, + final HttpServletResponse httpResp, final IRequest pendingReq) throws EaafException { + + if (!(pendingReq instanceof RequestImpl)) { + log.error("Requests that need authentication MUST be of type 'RequestImpl'"); + throw new RuntimeException( + "Requests that need authentication HAS TO BE of type 'RequestImpl'"); + + } + + // load OA configuration from pending request + final IspConfiguration oaParam = pendingReq.getServiceProviderConfiguration(); + + // set logging context and log unique OA identifier to revision log + TransactionIdUtils.setServiceProviderId(oaParam.getUniqueIdentifier()); + revisionsLogger.logEvent(pendingReq, EVENT_AUTHENTICATION_PROCESS_FOR_SP, + pendingReq.getSpEntityId()); + + // generic authentication request validation + if (pendingReq.isPassiv() && pendingReq.forceAuth()) { + // conflict! + throw new NoPassivAuthenticationException(); + } + + + // check Single Sign-On functionality if SSOManager is available + boolean isValidSsoSession = false; + if (ssoManager != null) { + log.trace("SSOManager is loaded. Starting SSO session validation ... "); + // check if SSO is allowed for this service provider + ssoManager.isSsoAllowedForSp(pendingReq, httpReq); + + // check if SSO session is active and valid + isValidSsoSession = ssoManager.checkAndValidateSsoSession(pendingReq, httpReq, httpResp) + && pendingReq.needSingleSignOnFunctionality(); + + + } + + // check if session is already authenticated + // boolean isSessionAuthenticated = tryPerformAuthentication((RequestImpl) pendingReq, + // isValidSSOSession); + // boolean isSessionAuthenticated = isValidSSOSession && + // StringUtils.isNotEmpty(pendingReq.getSSOSessionIdentifier()); + + + // force new authentication authentication process + if (pendingReq.forceAuth()) { + startAuthenticationProcess(httpReq, httpResp, (RequestImpl) pendingReq); + return false; + + // perform SSO-Consents evaluation if it it required + } else if (isValidSsoSession && pendingReq.isNeedUserConsent()) { + sendSingleSignOnConsentsEvaluation(httpReq, httpResp, (RequestImpl) pendingReq); + return false; + + + } else if (pendingReq.isPassiv()) { + if (isValidSsoSession + && StringUtils.isNotEmpty(pendingReq.getInternalSsoSessionIdentifier())) { + // Passive authentication ok! --> Populate pending request from SSO session + ssoManager.populatePendingRequestWithSsoInformation(pendingReq); + revisionsLogger.logEvent(pendingReq, EVENT_AUTHENTICATION_PROCESS_FINISHED); + return true; + + } else { + throw new NoPassivAuthenticationException(); + + } + + } else { + if (isValidSsoSession + && StringUtils.isNotEmpty(pendingReq.getInternalSsoSessionIdentifier())) { + // Is authenticated .. proceed + ssoManager.populatePendingRequestWithSsoInformation(pendingReq); + revisionsLogger.logEvent(pendingReq, EVENT_AUTHENTICATION_PROCESS_FINISHED); + return true; + + } else { + // Start authentication! + startAuthenticationProcess(httpReq, httpResp, (RequestImpl) pendingReq); + return false; + + } + } + } + + @Override + public final void performOnlyIdpLogOut(final HttpServletRequest request, + final HttpServletResponse response, final IRequest pendingReq) { + + log.debug("Close session. Remove pending request ... "); + requestStoreage.removePendingRequest(pendingReq.getPendingRequestId()); + + + if (ssoManager != null) { + try { + log.trace("'SSOManager' active. Search for active SSO sessions ... "); + if (ssoManager.destroySsoSessionOnIdpOnly(request, response, pendingReq)) { + log.info("SSO session successfully closed"); + } else { + log.info("Closing SSO session NOT successfully"); + } + + } catch (final EaafSsoException e) { + log.warn("Destroying of SSO session FAILED. Reason: " + e.getMessage(), e); + + } + + } + + } + + /** + * Populate process execution context and start process engine. + * + * @param httpReq http request + * @param httpResp http response + * @param pendingReq current pending request + * @throws ServletException In case of a servlet error + * @throws IOException In case of an IO error + * @throws EaafException In case of EAAF processing error + */ + private void startAuthenticationProcess(final HttpServletRequest httpReq, + final HttpServletResponse httpResp, final RequestImpl pendingReq) throws EaafException { + + log.info("Starting authentication ..."); + revisionsLogger.logEvent(pendingReq, EVENT_AUTHENTICATION_PROCESS_STARTED); + + // create authentication process execution context + final ExecutionContext executionContext = new ExecutionContextImpl(); + + // set oaIdentifeir + executionContext.put(EAAFConstants.PROCESS_ENGINE_SERVICE_PROVIDER_ENTITYID, + pendingReq.getServiceProviderConfiguration().getUniqueIdentifier()); + + // add X509 SSL client certificate if exist + if (httpReq.getAttribute("javax.servlet.request.X509Certificate") != null) { + log.debug("Find SSL-client-certificate on request --> Add it to context"); + executionContext.put(EAAFConstants.PROCESS_ENGINE_SSL_CLIENT_CERTIFICATE, + ((X509Certificate[]) httpReq.getAttribute("javax.servlet.request.X509Certificate"))); + pendingReq.setRawDataToTransaction(EAAFConstants.PROCESS_ENGINE_SSL_CLIENT_CERTIFICATE, + (httpReq.getAttribute("javax.servlet.request.X509Certificate"))); + + } + + // add additional http request parameter to context + if (!reqParameterWhiteListeForModules.isEmpty()) { + final Enumeration reqParamNames = httpReq.getParameterNames(); + while (reqParamNames.hasMoreElements()) { + final String paramName = reqParamNames.nextElement(); + if (StringUtils.isNotEmpty(paramName) + && reqParameterWhiteListeForModules.contains(paramName)) { + executionContext.put(paramName, + StringEscapeUtils.escapeHtml4(httpReq.getParameter(paramName))); + } + } + } + + // add additional http request parameter to context + if (!reqHeaderWhiteListeForModules.isEmpty()) { + final Enumeration reqHeaderNames = httpReq.getHeaderNames(); + while (reqHeaderNames.hasMoreElements()) { + final String paramName = reqHeaderNames.nextElement(); + if (StringUtils.isNotEmpty(paramName) && at.gv.egiz.eaaf.core.impl.utils.ArrayUtils + .containsCaseInsensitive(paramName, reqHeaderWhiteListeForModules) + // reqHeaderWhiteListeForModules.contains(paramName.toLowerCase()) + ) { + executionContext.put(paramName.toLowerCase(), + StringEscapeUtils.escapeHtml4(httpReq.getHeader(paramName))); + } + + } + } + + + + // populate more IDP specific information to execution context + populateExecutionContext(executionContext, pendingReq, httpReq); + + // start process engine + startProcessEngine(pendingReq, executionContext); + + } + + /** + * Add additional parameters into context of process-engine. + * + * @param executionContext Process-engine context + * @param pendingReq Current pending request + * @param httpReq http request + * + * @throws EaafException In case of an error + */ + protected abstract void populateExecutionContext(ExecutionContext executionContext, + RequestImpl pendingReq, HttpServletRequest httpReq) throws EaafException; + + /** + * Starting a user consent evaluation. + * + * @param request http request + * @param response http response + * @param pendingReq current pending request + * @throws ServletException In case of a servlet error + * @throws IOException In case of an IO error + * @throws EaafException In case of a EAAF processing error + */ + private void sendSingleSignOnConsentsEvaluation(final HttpServletRequest request, + final HttpServletResponse response, final RequestImpl pendingReq) throws EaafException { + + log.debug("Starting SSO user-consents evaluation ..."); + + // set authenticated flag to false, because user consents is required + pendingReq.setAuthenticated(false); + + // create execution context + final ExecutionContext executionContext = new ExecutionContextImpl(); + executionContext.put(ISsoManager.PROCESS_ENGINE_SSO_CONSENTS_EVALUATION, true); + + // start process engine + startProcessEngine(pendingReq, executionContext); + + } + + + /** + * Select a specific process and starting process engine. + * + * @param pendingReq current pending request + * @param executionContext current context for process-engine + * @throws EaafException In case of an process-engine error + */ + private void startProcessEngine(final RequestImpl pendingReq, + final ExecutionContext executionContext) throws EaafException { + try { + // put pending-request ID on execurtionContext + executionContext.put(EAAFConstants.PROCESS_ENGINE_PENDINGREQUESTID, + pendingReq.getPendingRequestId()); + + // create process instance + final String processDefinitionId = + moduleRegistration.selectProcess(executionContext, pendingReq); + + if (processDefinitionId == null) { + log.warn("No suitable process found for PendingReqId " + pendingReq.getPendingRequestId()); + throw new EaafException("process.02", new Object[] {pendingReq.getPendingRequestId()}); + + } + + final String processInstanceId = + processEngine.createProcessInstance(processDefinitionId, executionContext); + + // keep process instance id in protocol pending-request + pendingReq.setProcessInstanceId(processInstanceId); + + // store pending-request + requestStoreage.storePendingRequest(pendingReq); + + // start process + processEngine.start(pendingReq); + + } catch (final ProcessExecutionException e) { + final Throwable cause = e.getCause(); + if (cause != null && cause instanceof TaskExecutionException) { + final Throwable taskCause = cause.getCause(); + if (taskCause != null && taskCause instanceof EaafException) { + final EaafException moaTaskCause = (EaafException) taskCause; + log.warn(taskCause.getMessage(), taskCause); + throw moaTaskCause; + + } + } + + throw new EaafException("process.01", + new Object[] {pendingReq.getProcessInstanceId(), pendingReq.getPendingRequestId()}, e); + } + + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/RequestStorage.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/RequestStorage.java index e1598b8f..1afa879f 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/RequestStorage.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/RequestStorage.java @@ -1,218 +1,224 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.auth; + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. + */ -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; +package at.gv.egiz.eaaf.core.impl.idp.auth; import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.IRequestStorage; -import at.gv.egiz.eaaf.core.api.idp.process.ProcessInstanceStoreDAO; +import at.gv.egiz.eaaf.core.api.idp.process.ProcessInstanceStoreDao; import at.gv.egiz.eaaf.core.api.storage.ITransactionStorage; import at.gv.egiz.eaaf.core.api.utils.IPendingRequestIdGenerationStrategy; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.core.exceptions.EAAFStorageException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; import at.gv.egiz.eaaf.core.exceptions.PendingReqIdValidationException; import at.gv.egiz.eaaf.core.impl.idp.controller.protocols.RequestImpl; -import at.gv.egiz.eaaf.core.impl.utils.TransactionIDUtils; +import at.gv.egiz.eaaf.core.impl.utils.TransactionIdUtils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; @Service("RequestStorage") -public class RequestStorage implements IRequestStorage{ - private static final Logger log = LoggerFactory.getLogger(RequestStorage.class); - - @Autowired(required=true) ITransactionStorage transactionStorage; - @Autowired(required=true) ProcessInstanceStoreDAO processInstanceStore; - @Autowired(required=true) IPendingRequestIdGenerationStrategy pendingReqIdGenerationStrategy; - - @Override - public IRequest getPendingRequest(String pendingReqID) throws PendingReqIdValidationException { - - try { - final String internalPendingReqId = - pendingReqIdGenerationStrategy.validateAndGetPendingRequestId(pendingReqID); - log.debug("PendingReqId is valid"); - - //get pending-request from storage - final IRequest pendingRequest = getInternalPendingRequest(internalPendingReqId); - - //set transactionID and sessionID to Logger - TransactionIDUtils.setAllLoggingVariables(pendingRequest); - - return pendingRequest; - - } catch (final PendingReqIdValidationException e) { - log.info("PendingRequestId is invalid. Reason: {} ", e.getMessage()); - - // search invalid pending-request for errorHandling - IRequest invalidPendingRequest = null; - try { - if (StringUtils.isNotEmpty(e.getInvalidInternalPendingReqId())) - invalidPendingRequest = transactionStorage.get(e.getInvalidInternalPendingReqId(), IRequest.class); - - } catch (final EAAFException e1) { - log.info("No PendingRequst found with pendingRequestID " + pendingReqID); - return null; - - } - - e.setInvalidPendingReq(invalidPendingRequest); - throw e; - - } catch (EAAFException | NullPointerException e) { - log.info("No PendingRequst found with pendingRequestID " + pendingReqID); - return null; - - } - } - - @Override - public void storePendingRequest(IRequest pendingRequest) throws EAAFException { - try { - if (pendingRequest instanceof IRequest) { - try { - //validate pending-requestId - final String internalPendingRequestId = pendingReqIdGenerationStrategy.getPendingRequestIdWithOutChecks(pendingRequest.getPendingRequestId()); - - //store pending request - transactionStorage.put(internalPendingRequestId, pendingRequest, -1); - - } catch (final PendingReqIdValidationException e) { - log.warn("Invalid pending-request-Id. Reason: {}", e.getMessage()); - log.warn("Do NOT store pending-request with invalid pending-request-Id. The process will break soon!"); - - } - - } else - throw new EAAFException("PendigRequest is NOT of type 'IRequest'", null); - - } catch (final EAAFException e) { - log.warn("PendingRequest with ID=" + pendingRequest.getPendingRequestId() + - " can not stored.", e); - throw new EAAFStorageException("PendingRequest with Id: " + pendingRequest.getPendingRequestId() - + " can not be stored", e); - - } - - } - - @Override - public void removePendingRequest(String pendingReqID) { - - if (pendingReqID != null) { - String internalPendingReqId = null; - try { - internalPendingReqId = pendingReqIdGenerationStrategy.getPendingRequestIdWithOutChecks(pendingReqID); - - } catch (final PendingReqIdValidationException e) { - internalPendingReqId = e.getInvalidInternalPendingReqId(); - - } - - try { - //remove process-management execution instance# - if (internalPendingReqId != null) { - final IRequest pendingReq = getInternalPendingRequest(internalPendingReqId); - if (pendingReq != null && - pendingReq.getProcessInstanceId() != null) - processInstanceStore.remove(pendingReq.getProcessInstanceId()); - - //remove pending-request - transactionStorage.remove(internalPendingReqId); - } - - } catch (final EAAFException e) { - log.warn("Removing process associated with pending-request:" + pendingReqID + " FAILED.", e); - - } - - } - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.storage.IRequestStorage#changePendingRequestID(at.gv.egovernment.moa.id.moduls.IRequest) - */ - @Override - public String changePendingRequestID(IRequest pendingRequest) throws EAAFException { - if (pendingRequest instanceof RequestImpl) { - - //get old internal pendingReqId - String oldInternalRequestID = null; - try { - oldInternalRequestID = - pendingReqIdGenerationStrategy.getPendingRequestIdWithOutChecks(pendingRequest.getPendingRequestId()); - - } catch (final PendingReqIdValidationException e) { - //it's no problem, because it must be valid before when pending-request was loaded and we change it now - oldInternalRequestID = e.getInvalidInternalPendingReqId(); - - } - - - //generate new pendingReqId and get internalPendingReqId - final String newRequestID = pendingReqIdGenerationStrategy.generateExternalPendingRequestId(); - log.debug("Change pendingRequestID from " + pendingRequest.getPendingRequestId() + " to " + newRequestID); - ((RequestImpl)pendingRequest).setPendingRequestId(newRequestID); - - String newInternalPendingRequestId = null; - try { - newInternalPendingRequestId = pendingReqIdGenerationStrategy.getPendingRequestIdWithOutChecks(newRequestID); - - } catch (final PendingReqIdValidationException e) { - throw new EAAFException("internal.99", new Object[]{"Generate invalid pendingRequestId. Something looks WRONG"}, e); - - } - - - //change Key in cache - transactionStorage.changeKey(oldInternalRequestID, newInternalPendingRequestId, pendingRequest); - - //only delete oldRequestID, no change. - return newRequestID; - - } else { - log.error("PendingRequest object is not of type 'RequestImpl.class'"); - throw new EAAFException("PendingRequest object is not of type 'RequestImpl.class'", null); - - } - - } - - private IRequest getInternalPendingRequest(String internalPendingReqId) throws EAAFException { - final IRequest pendingRequest = transactionStorage.get(internalPendingReqId, IRequest.class); - if (pendingRequest == null) { - log.info("No PendingRequst found with pendingRequestID " + internalPendingReqId); - return null; - - } - - return pendingRequest; - - } +public class RequestStorage implements IRequestStorage { + private static final Logger log = LoggerFactory.getLogger(RequestStorage.class); + + @Autowired(required = true) + ITransactionStorage transactionStorage; + @Autowired(required = true) + ProcessInstanceStoreDao processInstanceStore; + @Autowired(required = true) + IPendingRequestIdGenerationStrategy pendingReqIdGenerationStrategy; + + @Override + public IRequest getPendingRequest(final String pendingReqID) + throws PendingReqIdValidationException { + + try { + final String internalPendingReqId = + pendingReqIdGenerationStrategy.validateAndGetPendingRequestId(pendingReqID); + log.debug("PendingReqId is valid"); + + // get pending-request from storage + final IRequest pendingRequest = getInternalPendingRequest(internalPendingReqId); + + // set transactionID and sessionID to Logger + TransactionIdUtils.setAllLoggingVariables(pendingRequest); + + return pendingRequest; + + } catch (final PendingReqIdValidationException e) { + log.info("PendingRequestId is invalid. Reason: {} ", e.getMessage()); + + // search invalid pending-request for errorHandling + IRequest invalidPendingRequest = null; + try { + if (StringUtils.isNotEmpty(e.getInvalidInternalPendingReqId())) { + invalidPendingRequest = + transactionStorage.get(e.getInvalidInternalPendingReqId(), IRequest.class); + } + + } catch (final EaafException e1) { + log.info("No PendingRequst found with pendingRequestID " + pendingReqID); + return null; + + } + + e.setInvalidPendingReq(invalidPendingRequest); + throw e; + + } catch (EaafException | NullPointerException e) { + log.info("No PendingRequst found with pendingRequestID " + pendingReqID); + return null; + + } + } + + @Override + public void storePendingRequest(final IRequest pendingRequest) throws EaafException { + try { + // validate pending-requestId + final String internalPendingRequestId = pendingReqIdGenerationStrategy + .getPendingRequestIdWithOutChecks(pendingRequest.getPendingRequestId()); + + // store pending request + transactionStorage.put(internalPendingRequestId, pendingRequest, -1); + + } catch (final PendingReqIdValidationException e) { + log.warn("Invalid pending-request-Id. Reason: {}", e.getMessage()); + log.warn( + "Do NOT store pending-request with invalid pending-request-Id. The process will break soon!"); + + } catch (final EaafException e) { + log.warn( + "PendingRequest with ID=" + pendingRequest.getPendingRequestId() + " can not stored.", e); + throw new EaafStorageException( + "PendingRequest with Id: " + pendingRequest.getPendingRequestId() + " can not be stored", + e); + + } + + } + + @Override + public void removePendingRequest(final String pendingReqID) { + + if (pendingReqID != null) { + String internalPendingReqId = null; + try { + internalPendingReqId = + pendingReqIdGenerationStrategy.getPendingRequestIdWithOutChecks(pendingReqID); + + } catch (final PendingReqIdValidationException e) { + internalPendingReqId = e.getInvalidInternalPendingReqId(); + + } + + try { + // remove process-management execution instance# + if (internalPendingReqId != null) { + final IRequest pendingReq = getInternalPendingRequest(internalPendingReqId); + if (pendingReq != null && pendingReq.getProcessInstanceId() != null) { + processInstanceStore.remove(pendingReq.getProcessInstanceId()); + } + + // remove pending-request + transactionStorage.remove(internalPendingReqId); + } + + } catch (final EaafException e) { + log.warn("Removing process associated with pending-request:" + pendingReqID + " FAILED.", + e); + + } + + } + } + + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.storage.IRequestStorage#changePendingRequestID(at.gv.egovernment.moa. + * id.moduls.IRequest) + */ + @Override + public String changePendingRequestID(final IRequest pendingRequest) throws EaafException { + if (pendingRequest instanceof RequestImpl) { + + // get old internal pendingReqId + String oldInternalRequestID = null; + try { + oldInternalRequestID = pendingReqIdGenerationStrategy + .getPendingRequestIdWithOutChecks(pendingRequest.getPendingRequestId()); + + } catch (final PendingReqIdValidationException e) { + // it's no problem, because it must be valid before when pending-request was loaded and we + // change it now + oldInternalRequestID = e.getInvalidInternalPendingReqId(); + + } + + + // generate new pendingReqId and get internalPendingReqId + final String newRequestID = pendingReqIdGenerationStrategy.generateExternalPendingRequestId(); + log.debug("Change pendingRequestID from " + pendingRequest.getPendingRequestId() + " to " + + newRequestID); + ((RequestImpl) pendingRequest).setPendingRequestId(newRequestID); + + String newInternalPendingRequestId = null; + try { + newInternalPendingRequestId = + pendingReqIdGenerationStrategy.getPendingRequestIdWithOutChecks(newRequestID); + + } catch (final PendingReqIdValidationException e) { + throw new EaafException("internal.99", + new Object[] {"Generate invalid pendingRequestId. Something looks WRONG"}, e); + + } + + + // change Key in cache + transactionStorage.changeKey(oldInternalRequestID, newInternalPendingRequestId, + pendingRequest); + + // only delete oldRequestID, no change. + return newRequestID; + + } else { + log.error("PendingRequest object is not of type 'RequestImpl.class'"); + throw new EaafException("PendingRequest object is not of type 'RequestImpl.class'", null); + + } + + } + + private IRequest getInternalPendingRequest(final String internalPendingReqId) + throws EaafException { + final IRequest pendingRequest = transactionStorage.get(internalPendingReqId, IRequest.class); + if (pendingRequest == null) { + log.info("No PendingRequst found with pendingRequestID " + internalPendingReqId); + return null; + + } + + return pendingRequest; + + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/builder/AbstractAuthenticationDataBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/builder/AbstractAuthenticationDataBuilder.java index 2108e041..491fdf4a 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/builder/AbstractAuthenticationDataBuilder.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/builder/AbstractAuthenticationDataBuilder.java @@ -1,29 +1,22 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.auth.builder; import java.io.ByteArrayInputStream; @@ -32,18 +25,6 @@ import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Map.Entry; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.lang.NonNull; -import org.springframework.util.Assert; -import org.springframework.util.Base64Utils; -import org.w3c.dom.DOMException; -import org.w3c.dom.Element; -import org.w3c.dom.Node; - import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.data.EAAFConstants; import at.gv.egiz.eaaf.core.api.data.ExtendedPVPAttributeDefinitions; @@ -51,674 +32,748 @@ import at.gv.egiz.eaaf.core.api.data.PVPAttributeDefinitions; import at.gv.egiz.eaaf.core.api.idp.IAuthData; import at.gv.egiz.eaaf.core.api.idp.IAuthenticationDataBuilder; import at.gv.egiz.eaaf.core.api.idp.IConfigurationWithSP; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; import at.gv.egiz.eaaf.core.api.idp.auth.data.IAuthProcessDataContainer; import at.gv.egiz.eaaf.core.api.idp.auth.data.IIdentityLink; -import at.gv.egiz.eaaf.core.exceptions.EAAFAuthenticationException; -import at.gv.egiz.eaaf.core.exceptions.EAAFBuilderException; -import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.core.exceptions.EAAFParserException; -import at.gv.egiz.eaaf.core.exceptions.EAAFStorageException; +import at.gv.egiz.eaaf.core.exceptions.EaafAuthenticationException; +import at.gv.egiz.eaaf.core.exceptions.EaafBuilderException; +import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.exceptions.EaafParserException; +import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; import at.gv.egiz.eaaf.core.exceptions.XPathException; import at.gv.egiz.eaaf.core.impl.data.Pair; import at.gv.egiz.eaaf.core.impl.idp.AuthenticationData; import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; import at.gv.egiz.eaaf.core.impl.idp.auth.data.SimpleIdentityLinkAssertionParser; import at.gv.egiz.eaaf.core.impl.utils.XPathUtils; - +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.lang.NonNull; +import org.springframework.util.Assert; +import org.springframework.util.Base64Utils; +import org.w3c.dom.DOMException; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + public abstract class AbstractAuthenticationDataBuilder implements IAuthenticationDataBuilder { - private static final Logger log = LoggerFactory.getLogger(AbstractAuthenticationDataBuilder.class); - - /** - * Identify authProcessData that should be directly mapped into authData - */ - public static final String GENERIC_AUTHDATA_IDENTIFIER = "authData_"; - - public static final String CONFIG_PROP_ENABLE_IDL_ATTRIBUTE_ESCAPEING = "configuration.bugfix.enable.idl.escaping"; - - protected Collection includedToGenericAuthData = null; - @Autowired protected IConfigurationWithSP basicConfig; - - @Override - public IAuthData buildAuthenticationData(IRequest pendingReq) throws EAAFAuthenticationException { - IAuthData authData = null; - final IAuthProcessDataContainer authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); - - try { - if (authProcessData.isEIDProcess()) { - log.debug("Building AuthData from new E-ID information ... "); - authData = getAuthDataInstance(pendingReq); - Assert.notNull(authData, "AuthData is null"); - - log.trace("Adding generic AuthData information ... "); - buildInternalAuthDataGeneric(authData, authProcessData, pendingReq); - - log.trace("Build service-specific AuthData information ... "); - buildServiceSpecificAuthenticationData(authData, pendingReq); - - } else { - log.info("User authentication uses the deprecated. Building AuthData from deprecated information ... "); - authData = buildDeprecatedAuthData(pendingReq); - Assert.notNull(authData, "AuthData is null"); - - } - - } catch ( final EAAFAuthenticationException e) { - throw e; - - } catch (XPathException | DOMException | EAAFException e) { - log.warn("Can not build authentication data from auth. process information"); - throw new EAAFAuthenticationException("builder.11", new Object[]{e.getMessage()}, e); - - } - - log.trace("AuthData generation finished"); - return authData; - - } - - /** - * * @param pendingReq current pendingRequest - * - * @param pendingReq current pendingRequest - * @return {@link IAuthData} but never null - * @throws EAAFException - */ - @NonNull - abstract protected IAuthData getAuthDataInstance(IRequest pendingReq) throws EAAFException; - - /** - * Build service-specific AuthData by using information from E-ID - * This builder uses vSZ, MDS and Consent as input information - * - * @param pendingReq current pendingRequest - * @return {@link IAuthData} but never null - * @throws EAAFException - */ - abstract protected void buildServiceSpecificAuthenticationData(IAuthData authData, IRequest pendingReq) throws EAAFException; - - - /** - * Add generic E-ID information into already existing AuthData - * - * @param authData - * @param authProcessData - * @param pendingReq - */ - private void buildInternalAuthDataGeneric(@NonNull IAuthData authData, - @NonNull IAuthProcessDataContainer authProcessData, @NonNull IRequest pendingReq) { - Assert.notNull(pendingReq, "PendingRequest is null"); - Assert.notNull(authData, "AuthData is null"); - Assert.notNull(authProcessData, "AuthProcessData is null"); - - if (!(authData instanceof AuthenticationData)) { - log.error("AuthData has no suitable type! Requires: {}", AuthenticationData.class.getName()); - throw new RuntimeException("AuthData has no suitable type! Requires: " + AuthenticationData.class.getName()); - - } - - final AuthenticationData internalAuthData = (AuthenticationData)authData; - - //TODO: check if it is needed -// if (authProcessData.getGenericSessionDataStorage() != null && -// !authProcessData.getGenericSessionDataStorage().isEmpty()) -// includedToGenericAuthData = authProcessData.getGenericSessionDataStorage().keySet(); -// else - includedToGenericAuthData = new ArrayList(); - - //#################################################### - //set general authData info's - internalAuthData.setAuthenticationIssuer(pendingReq.getAuthURL()); - internalAuthData.setSsoSession(pendingReq.needSingleSignOnFunctionality()); - internalAuthData.setBaseIDTransferRestrication(pendingReq.getServiceProviderConfiguration().hasBaseIdTransferRestriction()); - - //#################################################### - //set MDS and vSZ - internalAuthData.setFamilyName(authProcessData.getGenericDataFromSession(ExtendedPVPAttributeDefinitions.PRINCIPAL_NAME_NAME, String.class)); - internalAuthData.setGivenName(authProcessData.getGenericDataFromSession(ExtendedPVPAttributeDefinitions.GIVEN_NAME_NAME, String.class)); - internalAuthData.setDateOfBirth(authProcessData.getGenericDataFromSession(ExtendedPVPAttributeDefinitions.BIRTHDATE_NAME, String.class)); - internalAuthData.setEncSourceId(authProcessData.getGenericDataFromSession(ExtendedPVPAttributeDefinitions.EID_ENCRYPTED_SOURCEID_NAME, String.class)); - internalAuthData.setEncSourceIdType(authProcessData.getGenericDataFromSession(ExtendedPVPAttributeDefinitions.EID_ENCRYPTED_SOURCEID_TYPE_NAME, String.class)); - - //#################################################### - //set QAA level - setQAALevel(internalAuthData, authProcessData, pendingReq); - - - //#################################################### - //set isForeigner flag - setFlagForeigner(internalAuthData, authProcessData, pendingReq); - - - //#################################################### - //set citizen country-code - setCitizenCountryCode(internalAuthData, authProcessData, pendingReq); - - - //set generic authProcessData to authdata - for (final Entry el : authProcessData.getGenericSessionDataStorage().entrySet()) { - if (el.getKey().startsWith(GENERIC_AUTHDATA_IDENTIFIER)) { - log.trace("Find generic authProcessData {}. Map it directly to authData", el.getKey()); - try { - internalAuthData.setGenericData(el.getKey(), el.getValue()); - - } catch (final EAAFStorageException e) { - log.warn("Can NOT set authData with key: {}", el.getKey(), null, e); - - } - - } - - } - - - } - - /** - * Parse citzen country-code into AuthData - * - * @param internalAuthData - * @param authProcessData - * @param pendingReq - */ - private void setCitizenCountryCode(AuthenticationData authData, IAuthProcessDataContainer authProcessData, - IRequest pendingReq) { - includedToGenericAuthData.remove(PVPAttributeDefinitions.EID_ISSUING_NATION_NAME); - final String pvpCCCAttr = authProcessData.getGenericDataFromSession(PVPAttributeDefinitions.EID_ISSUING_NATION_NAME, String.class); - if (StringUtils.isNotEmpty(pvpCCCAttr)) { - authData.setCiticenCountryCode(pvpCCCAttr); - log.debug("Find PVP-Attr: " + PVPAttributeDefinitions.EID_ISSUING_NATION_FRIENDLY_NAME); - - } else { - if (authData.isForeigner()) { - //TODO!!!! - - } else { - authData.setCiticenCountryCode(basicConfig.getBasicConfiguration( - IConfigurationWithSP.CONFIG_PROPS_AUTH_DEFAULT_COUNTRYCODE, - EAAFConstants.COUNTRYCODE_AUSTRIA)); - - } - } - - } - - /** - * parse QAA Level into AuthData - * - * @param authData - * @param authProcessData - * @param pendingReq - */ - private void setQAALevel(@NonNull AuthenticationData authData, - @NonNull IAuthProcessDataContainer authProcessData, @NonNull IRequest pendingReq) { - includedToGenericAuthData.remove(PVPAttributeDefinitions.EID_CITIZEN_EIDAS_QAA_LEVEL_NAME); - String currentLoA = null; - if (StringUtils.isNotEmpty(authProcessData.getQAALevel())) - currentLoA = authProcessData.getQAALevel(); - else { - currentLoA = authProcessData.getGenericDataFromSession(PVPAttributeDefinitions.EID_CITIZEN_EIDAS_QAA_LEVEL_NAME, String.class); - if (StringUtils.isNotEmpty(currentLoA)) { - log.debug("Find PVP-Attr '" + PVPAttributeDefinitions.EID_CITIZEN_EIDAS_QAA_LEVEL_FRIENDLY_NAME + "':" + currentLoA - + " --> Parse QAA-Level from that attribute."); - - } - } - if (StringUtils.isNotEmpty(currentLoA)) { - if (currentLoA.startsWith(EAAFConstants.EIDAS_LOA_PREFIX)) { - authData.seteIDASLoA(currentLoA); - - } else - log.info("Only eIDAS LoAs are supported by this implementation"); - - } else { - log.info("No QAA level found. Set to default level " + EAAFConstants.EIDAS_LOA_LOW); - authData.seteIDASLoA(EAAFConstants.EIDAS_LOA_LOW); - - } - - } - - /** - * Parse Foreigner information into AuthData - * - * @param authData - * @param authProcessData - * @param pendingReq - */ - private void setFlagForeigner(AuthenticationData authData, IAuthProcessDataContainer authProcessData, IRequest pendingReq) { - //TODO: change to new eIDAS-token attribute identifier - if (authProcessData.getGenericDataFromSession(PVPAttributeDefinitions.EID_STORK_TOKEN_NAME) != null) { - log.debug("Find PVP-Attr: " + PVPAttributeDefinitions.EID_STORK_TOKEN_FRIENDLY_NAME - + " --> Set 'isForeigner' flag to TRUE"); - authData.setForeigner(true); - - } else { - authData.setForeigner(authProcessData.isForeigner()); - - } - } - - /** - * Build authentication data by using information from citizen-card or mobile-phone signature - * This builder uses IdentityLink, AuthBlock, full MIS mandate as input information - * - * @param pendingReq current pendingRequest - * @return {@link IAuthData} but never null - * @throws EAAFException - */ - @Deprecated - @NonNull - abstract protected IAuthData buildDeprecatedAuthData(IRequest pendingReq) throws EAAFException; - - @Deprecated - protected void generateDeprecatedBasicAuthData(AuthenticationData authData, IRequest pendingReq, - IAuthProcessDataContainer authProcessData) throws EAAFBuilderException, EAAFConfigurationException, XPathException, DOMException, EAAFParserException { - - if (authProcessData.getGenericSessionDataStorage() != null && - !authProcessData.getGenericSessionDataStorage().isEmpty()) - includedToGenericAuthData = authProcessData.getGenericSessionDataStorage().keySet(); - else - includedToGenericAuthData = new ArrayList(); - - //#################################################### - //set general authData info's - authData.setAuthenticationIssuer(pendingReq.getAuthURL()); - authData.setSsoSession(pendingReq.needSingleSignOnFunctionality()); - authData.setBaseIDTransferRestrication(pendingReq.getServiceProviderConfiguration().hasBaseIdTransferRestriction()); - - - //#################################################### - //parse user info's from identityLink - IIdentityLink idlFromPVPAttr = null; - final IIdentityLink identityLink = authProcessData.getIdentityLink(); - if (identityLink != null) { - parseBasicUserInfosFromIDL(authData, identityLink, includedToGenericAuthData); - - } else { - // identityLink is not direct in MOASession - final String pvpAttrIDL = authProcessData.getGenericDataFromSession(PVPAttributeDefinitions.EID_IDENTITY_LINK_NAME, String.class); - //find PVP-Attr. which contains the IdentityLink - if (StringUtils.isNotEmpty(pvpAttrIDL)) { - log.debug("Find PVP-Attr: " + PVPAttributeDefinitions.EID_IDENTITY_LINK_FRIENDLY_NAME - + " --> Parse basic user info's from that attribute."); - InputStream idlStream = null; - try { - idlStream = new ByteArrayInputStream(Base64Utils.decodeFromString(pvpAttrIDL)); - idlFromPVPAttr = new SimpleIdentityLinkAssertionParser(idlStream).parseIdentityLink(); - parseBasicUserInfosFromIDL(authData, idlFromPVPAttr, includedToGenericAuthData); - - //set identitylink into AuthProcessData - authProcessData.setIdentityLink(idlFromPVPAttr);; - - } catch (final EAAFParserException e) { - log.warn("Received IdentityLink is not valid", e); - - } catch (final Exception e) { - log.warn("Received IdentityLink is not valid", e); - - } finally { - try { - includedToGenericAuthData.remove(PVPAttributeDefinitions.EID_IDENTITY_LINK_NAME); - if (idlStream != null) - idlStream.close(); - - } catch (final IOException e) { - log.warn("Close InputStream FAILED.", e); - - } - } - } - - //if no basic user info's are set yet, parse info's single PVP-Attributes - if (StringUtils.isEmpty(authData.getFamilyName())) { - log.debug("No IdentityLink found or not parseable --> Parse basic user info's from single PVP-Attributes."); - authData.setFamilyName(authProcessData.getGenericDataFromSession(PVPAttributeDefinitions.PRINCIPAL_NAME_NAME, String.class)); - authData.setGivenName(authProcessData.getGenericDataFromSession(PVPAttributeDefinitions.GIVEN_NAME_NAME, String.class)); - authData.setDateOfBirth(authProcessData.getGenericDataFromSession(PVPAttributeDefinitions.BIRTHDATE_NAME, String.class)); - authData.setIdentificationValue(authProcessData.getGenericDataFromSession(PVPAttributeDefinitions.EID_SOURCE_PIN_NAME, String.class)); - authData.setIdentificationType(authProcessData.getGenericDataFromSession(PVPAttributeDefinitions.EID_SOURCE_PIN_TYPE_NAME, String.class)); - - //remove corresponding keys from genericSessionData if exists - includedToGenericAuthData.remove(PVPAttributeDefinitions.PRINCIPAL_NAME_NAME); - includedToGenericAuthData.remove(PVPAttributeDefinitions.GIVEN_NAME_NAME); - includedToGenericAuthData.remove(PVPAttributeDefinitions.BIRTHDATE_NAME); - includedToGenericAuthData.remove(PVPAttributeDefinitions.EID_SOURCE_PIN_NAME); - includedToGenericAuthData.remove(PVPAttributeDefinitions.EID_SOURCE_PIN_TYPE_NAME); - } - - } - - if (authData.getIdentificationType() != null && - !authData.getIdentificationType().equals(EAAFConstants.URN_PREFIX_BASEID)) { - log.trace("IdentificationType is not a baseID --> clear it. "); - authData.setBPK(authData.getIdentificationValue()); - authData.setBPKType(authData.getIdentificationType()); - - authData.setIdentificationValue(null); - authData.setIdentificationType(null); - } - - - //#################################################### - //set QAA level - setQAALevel(authData, authProcessData, pendingReq); - - - //#################################################### - //set isForeigner flag - setFlagForeigner(authData, authProcessData, pendingReq); - - - //#################################################### - //set citizen country-code - setCitizenCountryCode(authData, authProcessData, pendingReq); - - - //#################################################### - // set bPK and IdentityLink - final String pvpbPKValue = getbPKValueFromPVPAttribute(authProcessData); - final String pvpbPKTypeAttr = getbPKTypeFromPVPAttribute(authProcessData); - final Pair pvpEncbPKAttr = getEncryptedbPKFromPVPAttribute(authProcessData, authData, pendingReq.getServiceProviderConfiguration()); - - //check if a unique ID for this citizen exists - if (StringUtils.isEmpty(authData.getIdentificationValue()) && - StringUtils.isEmpty(pvpbPKValue) && StringUtils.isEmpty(authData.getBPK()) && - pvpEncbPKAttr == null) { - log.info("Can not build authData, because moaSession include no bPK, encrypted bPK or baseID"); - throw new EAAFBuilderException("builder.08", new Object[]{"No " + PVPAttributeDefinitions.BPK_FRIENDLY_NAME - + " or " + PVPAttributeDefinitions.EID_SOURCE_PIN_FRIENDLY_NAME - + " or " + PVPAttributeDefinitions.ENC_BPK_LIST_FRIENDLY_NAME}, - "No " + PVPAttributeDefinitions.BPK_FRIENDLY_NAME - + " or " + PVPAttributeDefinitions.EID_SOURCE_PIN_FRIENDLY_NAME - + " or " + PVPAttributeDefinitions.ENC_BPK_LIST_FRIENDLY_NAME); - - } - - //check if bPK already added to AuthData matches OA - if (StringUtils.isNotEmpty(authData.getBPK()) - && matchsReceivedbPKToOnlineApplication(pendingReq.getServiceProviderConfiguration(), authData.getBPKType()) ) { - log.debug("Correct bPK is already included in AuthData."); - - //check if bPK received by PVP-Attribute matches OA - } else if (StringUtils.isNotEmpty(pvpbPKValue) && - matchsReceivedbPKToOnlineApplication(pendingReq.getServiceProviderConfiguration(), pvpbPKTypeAttr)) { - log.debug("Receive correct bPK from PVP-Attribute"); - authData.setBPK(pvpbPKValue); - authData.setBPKType(pvpbPKTypeAttr); - - // baseID is in AuthSesson --> calculate bPK directly - } else if (StringUtils.isNotEmpty(authData.getIdentificationValue())) { - log.debug("Citizen baseID is in MOASession --> calculate bPK from this."); - final Pair result = buildOAspecificbPK(pendingReq, authData); - authData.setBPK(result.getFirst()); - authData.setBPKType(result.getSecond()); - - //check if decrypted bPK exists - } else if (pvpEncbPKAttr != null) { - log.debug("Receive bPK as encrypted bPK and decryption was possible."); - authData.setBPK(pvpEncbPKAttr.getFirst()); - authData.setBPKType(pvpEncbPKAttr.getSecond()); - - //ask SZR to get bPK - } else { - String notValidbPK = authData.getBPK(); - String notValidbPKType = authData.getBPKType(); - if (StringUtils.isEmpty(notValidbPK) && - StringUtils.isEmpty(notValidbPKType)) { - notValidbPK = pvpbPKValue; - notValidbPKType = pvpbPKTypeAttr; - - if (StringUtils.isEmpty(notValidbPK) && - StringUtils.isEmpty(notValidbPKType)) { - log.error("No bPK in MOASession. THIS error should not occur any more."); - throw new NullPointerException("No bPK in MOASession. THIS error should not occur any more."); - } - } - - final Pair baseIDFromSZR = getbaseIDFromSZR(authData, notValidbPK, notValidbPKType); - if (baseIDFromSZR != null) { - log.info("Receive citizen baseID from SRZ. Authentication can be completed"); - authData.setIdentificationValue(baseIDFromSZR.getFirst()); - authData.setIdentificationType(baseIDFromSZR.getSecond()); - final Pair result = buildOAspecificbPK(pendingReq, authData); - authData.setBPK(result.getFirst()); - authData.setBPKType(result.getSecond()); - - } else { - log.warn("Can not build authData, because moaSession include no valid bPK, encrypted bPK or sourceID"); - throw new EAAFBuilderException("builder.13", new Object[]{pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier()}, - "No valid " + PVPAttributeDefinitions.BPK_FRIENDLY_NAME - + " or " + PVPAttributeDefinitions.EID_SOURCE_PIN_FRIENDLY_NAME - + " or " + PVPAttributeDefinitions.ENC_BPK_LIST_FRIENDLY_NAME); - - } - } - - //build IdentityLink - if (authProcessData.getIdentityLink() != null) - authData.setIdentityLink(buildOAspecificIdentityLink( - pendingReq.getServiceProviderConfiguration(), - authProcessData.getIdentityLink(), - authData.getBPK(), - authData.getBPKType())); - else - log.info("Can NOT set IdentityLink. Msg: No IdentityLink found"); - - } - - //extract a encrypted bPK from PVP attrobute - @Deprecated - protected abstract Pair getEncryptedbPKFromPVPAttribute(IAuthProcessDataContainer authProcessDataContainer, - AuthenticationData authData, ISPConfiguration spConfig) throws EAAFBuilderException; - - //request baseId from SRZ - @Deprecated - protected abstract Pair getbaseIDFromSZR(AuthenticationData authData, String notValidbPK, - String notValidbPKType); - - @Deprecated - protected Pair buildOAspecificbPK(IRequest pendingReq, AuthenticationData authData) throws EAAFBuilderException { - final ISPConfiguration oaParam = pendingReq.getServiceProviderConfiguration(); - - final String baseID = authData.getIdentificationValue(); - final String baseIDType = authData.getIdentificationType(); - Pair sectorSpecId = null; - - if (EAAFConstants.URN_PREFIX_BASEID.equals(baseIDType)) { - //SAML1 legacy target parameter work-around - final String spTargetId = oaParam.getAreaSpecificTargetIdentifier(); - log.debug("Use OA target identifier '" + spTargetId + "' from configuration"); - - //calculate sector specific unique identifier - sectorSpecId = new BPKBuilder().generateAreaSpecificPersonIdentifier(baseID, spTargetId); - - } else { - log.error("!!!baseID-element does not include a baseID. This should not be happen any more!!!"); - sectorSpecId = Pair.newInstance(baseID, baseIDType); - - } - - log.trace("Authenticate user with bPK:" + sectorSpecId.getFirst() + " Type:" + sectorSpecId.getSecond()); - return sectorSpecId; - - } - - @Deprecated - protected IIdentityLink buildOAspecificIdentityLink(ISPConfiguration spConfig, IIdentityLink idl, String bPK, String bPKType) throws EAAFConfigurationException, XPathException, DOMException, EAAFParserException { - if (spConfig.hasBaseIdTransferRestriction()) { - log.debug("SP: " + spConfig.getUniqueIdentifier() + " has baseId transfer restriction. Remove baseId from IDL ..."); - final Element idlassertion = idl.getSamlAssertion(); - //set bpk/wpbk; - final Node prIdentification = XPathUtils.selectSingleNode(idlassertion, SimpleIdentityLinkAssertionParser.PERSON_IDENT_VALUE_XPATH); - prIdentification.getFirstChild().setNodeValue(bPK); - //set bkp/wpbk type - final Node prIdentificationType = XPathUtils.selectSingleNode(idlassertion, SimpleIdentityLinkAssertionParser.PERSON_IDENT_TYPE_XPATH); - prIdentificationType.getFirstChild().setNodeValue(bPKType); - - final SimpleIdentityLinkAssertionParser idlparser = new SimpleIdentityLinkAssertionParser(idlassertion); - return idlparser.parseIdentityLink(); - - } else - return idl; - - } - - /** - * Check a bPK-Type against a Service-Provider configuration
- * If bPK-Type is null the result is false. - * - * @param oaParam Service-Provider configuration, never null - * @param bPKType bPK-Type to check - * @return true, if bPK-Type matchs to Service-Provider configuration, otherwise false - */ - @Deprecated - protected boolean matchsReceivedbPKToOnlineApplication(ISPConfiguration oaParam, String bPKType) { - return oaParam.getAreaSpecificTargetIdentifier().equals(bPKType); - - } - - /** - * Parse information from an IdentityLink into AuthData object - * - * @param authData - * @param identityLink - * @param includedGenericSessionData - */ - @Deprecated - private void parseBasicUserInfosFromIDL(AuthenticationData authData, IIdentityLink identityLink, Collection includedGenericSessionData) { - authData.setIdentificationValue(identityLink.getIdentificationValue()); - authData.setIdentificationType(identityLink.getIdentificationType()); - - /* GivenNames and FamilyNames with simple Apostrophe were escaped with ' - * in IdentityLinkParser since 5 years. This feature was bug-fix for an SL1.0 AuthBlock problem. - * However, the authentication attributes (SAML2, eIDAS, OpenID-Connect) also includes this escaped values, - * but there it is not neccesary. We fix this problem in 3.4.3, but the fix can be deactivated - * for dependency reasons. - */ - if (basicConfig.getBasicConfigurationBoolean(CONFIG_PROP_ENABLE_IDL_ATTRIBUTE_ESCAPEING, false)) { - authData.setGivenName(identityLink.getGivenName().replaceAll("'", "'")); - authData.setFamilyName(identityLink.getFamilyName().replaceAll("'", "'")); - - } else { - authData.setGivenName(identityLink.getGivenName()); - authData.setFamilyName(identityLink.getFamilyName()); - - } - - authData.setDateOfBirth(identityLink.getDateOfBirth()); - - - //remove corresponding keys from genericSessionData if exists - includedGenericSessionData.remove(PVPAttributeDefinitions.PRINCIPAL_NAME_NAME); - includedGenericSessionData.remove(PVPAttributeDefinitions.GIVEN_NAME_NAME); - includedGenericSessionData.remove(PVPAttributeDefinitions.BIRTHDATE_NAME); - includedGenericSessionData.remove(PVPAttributeDefinitions.EID_SOURCE_PIN_NAME); - includedGenericSessionData.remove(PVPAttributeDefinitions.EID_SOURCE_PIN_TYPE_NAME); - - } - - /** - * Get bPK from PVP Attribute 'BPK_NAME', which could be exist in - * MOASession as 'GenericData'
session.getGenericDataFromSession(PVPConstants.BPK_NAME, String.class)
- * - * @param session MOASession, but never null - * @return bPK, which was received by PVP-Attribute, or null if no attribute exists - */ - @Deprecated - private String getbPKValueFromPVPAttribute(IAuthProcessDataContainer session) { - String pvpbPKValueAttr = session.getGenericDataFromSession(PVPAttributeDefinitions.BPK_NAME, String.class); - if (StringUtils.isNotEmpty(pvpbPKValueAttr)) { - - //fix a wrong bPK-value prefix, which was used in some PVP Standardportal implementations - if (pvpbPKValueAttr.startsWith("bPK:")) { - log.warn("Attribute " + PVPAttributeDefinitions.BPK_NAME - + " contains a not standardize prefix! Staring attribute value correction process ..."); - pvpbPKValueAttr = pvpbPKValueAttr.substring("bPK:".length()); - - } - - final String[] spitted = pvpbPKValueAttr.split(":"); - if (spitted.length == 2) { - log.debug("Find PVP-Attr: " + PVPAttributeDefinitions.BPK_FRIENDLY_NAME); - return spitted[1]; - - - - } else if (spitted.length > 2) { - log.warn("Attribute " + PVPAttributeDefinitions.BPK_NAME + " has a wrong encoding and can NOT be USED!" - + " Value:" + pvpbPKValueAttr); - return null; - - } else { - log.debug("Find PVP-Attr: " + PVPAttributeDefinitions.BPK_FRIENDLY_NAME + " without prefix. Use it as it is"); - return spitted[0]; - - } - - } - - return null; - } - - /** - * Get bPK-Type from PVP Attribute 'EID_SECTOR_FOR_IDENTIFIER_NAME', which could be exist in - * MOASession as 'GenericData'
session.getGenericDataFromSession(PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME, String.class)
- * - * @param session MOASession, but never null - * @return bPKType, which was received by PVP-Attribute, or null if no attribute exists - */ - @Deprecated - private String getbPKTypeFromPVPAttribute(IAuthProcessDataContainer session) { - final String pvpbPKTypeAttr = session.getGenericDataFromSession(PVPAttributeDefinitions.EID_SECTOR_FOR_IDENTIFIER_NAME, String.class); - - if (StringUtils.isNotEmpty(pvpbPKTypeAttr)) { -// //fix a wrong bPK-Type encoding, which was used in some PVP Standardportal implementations -// if (pvpbPKTypeAttr.startsWith(EAAFConstants.URN_PREFIX_CDID) && -// !pvpbPKTypeAttr.substring(EAAFConstants.URN_PREFIX_CDID.length(), -// EAAFConstants.URN_PREFIX_CDID.length() + 1).equals("+")) { -// log.warn("Receive uncorrect encoded bBKType attribute " + pvpbPKTypeAttr + " Starting attribute value correction ... "); -// pvpbPKTypeAttr = EAAFConstants.URN_PREFIX_CDID + "+" + pvpbPKTypeAttr.substring(EAAFConstants.URN_PREFIX_CDID.length() + 1); -// -// } - log.debug("Find PVP-Attr: " + PVPAttributeDefinitions.EID_SECTOR_FOR_IDENTIFIER_FRIENDLY_NAME); - return pvpbPKTypeAttr; - } - - return null; - - - /* - * INFO: This code could be used to extract the bPKType from 'PVPConstants.BPK_NAME', - * because the prefix of BPK_NAME attribute contains the postfix of the bPKType - * - * Now, all PVP Standardportals should be able to send 'EID_SECTOR_FOR_IDENTIFIER' - * PVP attributes - */ -// String pvpbPKValueAttr = session.getGenericDataFromSession(PVPConstants.BPK_NAME, String.class); -// String[] spitted = pvpbPKValueAttr.split(":"); -// if (MiscUtil.isEmpty(authData.getBPKType())) { -// Logger.debug("PVP assertion contains NO bPK/wbPK target attribute. " + -// "Starting target extraction from bPK/wbPK prefix ..."); -// //exract bPK/wbPK type from bpk attribute value prefix if type is -// //not transmitted as single attribute -// Pattern pattern = Pattern.compile("[a-zA-Z]{2}(-[a-zA-Z]+)?"); -// Matcher matcher = pattern.matcher(spitted[0]); -// if (matcher.matches()) { -// //find public service bPK -// authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + spitted[0]); -// Logger.debug("Found bPK prefix. Set target to " + authData.getBPKType()); -// -// } else { -// //find business service wbPK -// authData.setBPKType(Constants.URN_PREFIX_WBPK+ "+" + spitted[0]); -// Logger.debug("Found wbPK prefix. Set target to " + authData.getBPKType()); -// -// } -// } - - } + private static final Logger log = + LoggerFactory.getLogger(AbstractAuthenticationDataBuilder.class); + + /** + * Identify authProcessData that should be directly mapped into authData. + */ + public static final String GENERIC_AUTHDATA_IDENTIFIER = "authData_"; + + public static final String CONFIG_PROP_ENABLE_IDL_ATTRIBUTE_ESCAPEING = + "configuration.bugfix.enable.idl.escaping"; + + protected Collection includedToGenericAuthData = null; + @Autowired + protected IConfigurationWithSP basicConfig; + + @Override + public IAuthData buildAuthenticationData(final IRequest pendingReq) + throws EaafAuthenticationException { + IAuthData authData = null; + final IAuthProcessDataContainer authProcessData = + pendingReq.getSessionData(AuthProcessDataWrapper.class); + + try { + if (authProcessData.isEIDProcess()) { + log.debug("Building AuthData from new E-ID information ... "); + authData = getAuthDataInstance(pendingReq); + Assert.notNull(authData, "AuthData is null"); + + log.trace("Adding generic AuthData information ... "); + buildInternalAuthDataGeneric(authData, authProcessData, pendingReq); + + log.trace("Build service-specific AuthData information ... "); + buildServiceSpecificAuthenticationData(authData, pendingReq); + + } else { + log.info( + "User authentication uses the deprecated. Building AuthData from deprecated information ... "); + authData = buildDeprecatedAuthData(pendingReq); + Assert.notNull(authData, "AuthData is null"); + + } + + } catch (final EaafAuthenticationException e) { + throw e; + + } catch (XPathException | DOMException | EaafException e) { + log.warn("Can not build authentication data from auth. process information"); + throw new EaafAuthenticationException("builder.11", new Object[] {e.getMessage()}, e); + + } + + log.trace("AuthData generation finished"); + return authData; + + } + + /** + * * @param pendingReq current pendingRequest. + * + * @param pendingReq current pendingRequest + * @return {@link IAuthData} but never null + * @throws EaafException In case of an error + */ + @NonNull + protected abstract IAuthData getAuthDataInstance(IRequest pendingReq) throws EaafException; + + /** + * Build service-specific AuthData by using information from E-ID This builder uses vSZ, MDS and + * Consent as input information. + * + * @param pendingReq current pendingRequest + * @return {@link IAuthData} but never null + * @throws EaafException In case of an error + */ + protected abstract void buildServiceSpecificAuthenticationData(IAuthData authData, + IRequest pendingReq) throws EaafException; + + + /** + * Add generic E-ID information into already existing AuthData. + * + * @param authData AuthData object + * @param authProcessData Authentication information holder from current pending request + * @param pendingReq current pending request + */ + private void buildInternalAuthDataGeneric(@NonNull final IAuthData authData, + @NonNull final IAuthProcessDataContainer authProcessData, + @NonNull final IRequest pendingReq) { + Assert.notNull(pendingReq, "PendingRequest is null"); + Assert.notNull(authData, "AuthData is null"); + Assert.notNull(authProcessData, "AuthProcessData is null"); + + if (!(authData instanceof AuthenticationData)) { + log.error("AuthData has no suitable type! Requires: {}", AuthenticationData.class.getName()); + throw new RuntimeException( + "AuthData has no suitable type! Requires: " + AuthenticationData.class.getName()); + + } + + final AuthenticationData internalAuthData = (AuthenticationData) authData; + + // TODO: check if it is needed + // if (authProcessData.getGenericSessionDataStorage() != null && + // !authProcessData.getGenericSessionDataStorage().isEmpty()) + // includedToGenericAuthData = authProcessData.getGenericSessionDataStorage().keySet(); + // else + includedToGenericAuthData = new ArrayList<>(); + + // #################################################### + // set general authData info's + internalAuthData.setAuthenticationIssuer(pendingReq.getAuthUrl()); + internalAuthData.setSsoSession(pendingReq.needSingleSignOnFunctionality()); + internalAuthData.setBaseIdTransferRestrication( + pendingReq.getServiceProviderConfiguration().hasBaseIdTransferRestriction()); + + // #################################################### + // set MDS and vSZ + internalAuthData.setFamilyName(authProcessData + .getGenericDataFromSession(PVPAttributeDefinitions.PRINCIPAL_NAME_NAME, String.class)); + internalAuthData.setGivenName(authProcessData + .getGenericDataFromSession(PVPAttributeDefinitions.GIVEN_NAME_NAME, String.class)); + internalAuthData.setDateOfBirth(authProcessData + .getGenericDataFromSession(PVPAttributeDefinitions.BIRTHDATE_NAME, String.class)); + internalAuthData.setEncSourceId(authProcessData.getGenericDataFromSession( + ExtendedPVPAttributeDefinitions.EID_ENCRYPTED_SOURCEID_NAME, String.class)); + internalAuthData.setEncSourceIdType(authProcessData.getGenericDataFromSession( + ExtendedPVPAttributeDefinitions.EID_ENCRYPTED_SOURCEID_TYPE_NAME, String.class)); + + // #################################################### + // set QAA level + setQaaLevel(internalAuthData, authProcessData, pendingReq); + + + // #################################################### + // set isForeigner flag + setFlagForeigner(internalAuthData, authProcessData, pendingReq); + + + // #################################################### + // set citizen country-code + setCitizenCountryCode(internalAuthData, authProcessData, pendingReq); + + + // set generic authProcessData to authdata + for (final Entry el : authProcessData.getGenericSessionDataStorage() + .entrySet()) { + if (el.getKey().startsWith(GENERIC_AUTHDATA_IDENTIFIER)) { + log.trace("Find generic authProcessData {}. Map it directly to authData", el.getKey()); + try { + internalAuthData.setGenericData(el.getKey(), el.getValue()); + + } catch (final EaafStorageException e) { + log.warn("Can NOT set authData with key: {}", el.getKey(), null, e); + + } + + } + + } + + + } + + /** + * Parse citzen country-code into AuthData. + * + * @param authData Current authentication data + * @param authProcessData Authentication information holder from current pending request + * @param pendingReq Current pending request + */ + private void setCitizenCountryCode(final AuthenticationData authData, + final IAuthProcessDataContainer authProcessData, final IRequest pendingReq) { + includedToGenericAuthData.remove(PVPAttributeDefinitions.EID_ISSUING_NATION_NAME); + final String pvpCccAttr = authProcessData + .getGenericDataFromSession(PVPAttributeDefinitions.EID_ISSUING_NATION_NAME, String.class); + if (StringUtils.isNotEmpty(pvpCccAttr)) { + authData.setCiticenCountryCode(pvpCccAttr); + log.debug("Find PVP-Attr: " + PVPAttributeDefinitions.EID_ISSUING_NATION_FRIENDLY_NAME); + + } else { + if (authData.isForeigner()) { + // TODO!!!! + + } else { + authData.setCiticenCountryCode(basicConfig.getBasicConfiguration( + IConfigurationWithSP.CONFIG_PROPS_AUTH_DEFAULT_COUNTRYCODE, + EAAFConstants.COUNTRYCODE_AUSTRIA)); + + } + } + + } + + /** + * parse QAA Level into AuthData. + * + * @param authData current authentication data + * @param authProcessData Authentication information holder from current pending request + * @param pendingReq current pending request + */ + private void setQaaLevel(@NonNull final AuthenticationData authData, + @NonNull final IAuthProcessDataContainer authProcessData, + @NonNull final IRequest pendingReq) { + includedToGenericAuthData.remove(PVPAttributeDefinitions.EID_CITIZEN_EIDAS_QAA_LEVEL_NAME); + String currentLoA = null; + if (StringUtils.isNotEmpty(authProcessData.getQAALevel())) { + currentLoA = authProcessData.getQAALevel(); + } else { + currentLoA = authProcessData.getGenericDataFromSession( + PVPAttributeDefinitions.EID_CITIZEN_EIDAS_QAA_LEVEL_NAME, String.class); + if (StringUtils.isNotEmpty(currentLoA)) { + log.debug( + "Find PVP-Attr '" + PVPAttributeDefinitions.EID_CITIZEN_EIDAS_QAA_LEVEL_FRIENDLY_NAME + + "':" + currentLoA + " --> Parse QAA-Level from that attribute."); + + } + } + if (StringUtils.isNotEmpty(currentLoA)) { + if (currentLoA.startsWith(EAAFConstants.EIDAS_LOA_PREFIX)) { + authData.setEidasLoa(currentLoA); + + } else { + log.info("Only eIDAS LoAs are supported by this implementation"); + } + + } else { + log.info("No QAA level found. Set to default level " + EAAFConstants.EIDAS_LOA_LOW); + authData.setEidasLoa(EAAFConstants.EIDAS_LOA_LOW); + + } + + } + + + private void setFlagForeigner(final AuthenticationData authData, + final IAuthProcessDataContainer authProcessData, final IRequest pendingReq) { + // TODO: change to new eIDAS-token attribute identifier + if (authProcessData + .getGenericDataFromSession(PVPAttributeDefinitions.EID_STORK_TOKEN_NAME) != null) { + log.debug("Find PVP-Attr: " + PVPAttributeDefinitions.EID_STORK_TOKEN_FRIENDLY_NAME + + " --> Set 'isForeigner' flag to TRUE"); + authData.setForeigner(true); + + } else { + authData.setForeigner(authProcessData.isForeigner()); + + } + } + + /** + * Build authentication data by using information from citizen-card or mobile-phone signature This + * builder uses IdentityLink, AuthBlock, full MIS mandate as input information. + * + * @param pendingReq current pendingRequest + * @return {@link IAuthData} but never null + * @throws EaafException In case of an error + */ + @Deprecated + @NonNull + protected abstract IAuthData buildDeprecatedAuthData(IRequest pendingReq) throws EaafException; + + @Deprecated + protected void generateDeprecatedBasicAuthData(final AuthenticationData authData, + final IRequest pendingReq, final IAuthProcessDataContainer authProcessData) + throws EaafBuilderException, EaafConfigurationException, XPathException, DOMException, + EaafParserException { + + if (authProcessData.getGenericSessionDataStorage() != null + && !authProcessData.getGenericSessionDataStorage().isEmpty()) { + includedToGenericAuthData = authProcessData.getGenericSessionDataStorage().keySet(); + } else { + includedToGenericAuthData = new ArrayList<>(); + } + + // #################################################### + // set general authData info's + authData.setAuthenticationIssuer(pendingReq.getAuthUrl()); + authData.setSsoSession(pendingReq.needSingleSignOnFunctionality()); + authData.setBaseIdTransferRestrication( + pendingReq.getServiceProviderConfiguration().hasBaseIdTransferRestriction()); + + + // #################################################### + // parse user info's from identityLink + IIdentityLink idlFromPvpAttr = null; + final IIdentityLink identityLink = authProcessData.getIdentityLink(); + if (identityLink != null) { + parseBasicUserInfosFromIdl(authData, identityLink, includedToGenericAuthData); + + } else { + // identityLink is not direct in MOASession + final String pvpAttrIdl = authProcessData + .getGenericDataFromSession(PVPAttributeDefinitions.EID_IDENTITY_LINK_NAME, String.class); + // find PVP-Attr. which contains the IdentityLink + if (StringUtils.isNotEmpty(pvpAttrIdl)) { + log.debug("Find PVP-Attr: " + PVPAttributeDefinitions.EID_IDENTITY_LINK_FRIENDLY_NAME + + " --> Parse basic user info's from that attribute."); + InputStream idlStream = null; + try { + idlStream = new ByteArrayInputStream(Base64Utils.decodeFromString(pvpAttrIdl)); + idlFromPvpAttr = new SimpleIdentityLinkAssertionParser(idlStream).parseIdentityLink(); + parseBasicUserInfosFromIdl(authData, idlFromPvpAttr, includedToGenericAuthData); + + // set identitylink into AuthProcessData + authProcessData.setIdentityLink(idlFromPvpAttr); + + } catch (final EaafParserException e) { + log.warn("Received IdentityLink is not valid", e); + + } catch (final Exception e) { + log.warn("Received IdentityLink is not valid", e); + + } finally { + try { + includedToGenericAuthData.remove(PVPAttributeDefinitions.EID_IDENTITY_LINK_NAME); + if (idlStream != null) { + idlStream.close(); + } + + } catch (final IOException e) { + log.warn("Close InputStream FAILED.", e); + + } + } + } + + // if no basic user info's are set yet, parse info's single PVP-Attributes + if (StringUtils.isEmpty(authData.getFamilyName())) { + log.debug( + "No IdentityLink found or not parseable --> Parse basic user info's from single PVP-Attributes."); + authData.setFamilyName(authProcessData + .getGenericDataFromSession(PVPAttributeDefinitions.PRINCIPAL_NAME_NAME, String.class)); + authData.setGivenName(authProcessData + .getGenericDataFromSession(PVPAttributeDefinitions.GIVEN_NAME_NAME, String.class)); + authData.setDateOfBirth(authProcessData + .getGenericDataFromSession(PVPAttributeDefinitions.BIRTHDATE_NAME, String.class)); + authData.setIdentificationValue(authProcessData + .getGenericDataFromSession(PVPAttributeDefinitions.EID_SOURCE_PIN_NAME, String.class)); + authData.setIdentificationType(authProcessData.getGenericDataFromSession( + PVPAttributeDefinitions.EID_SOURCE_PIN_TYPE_NAME, String.class)); + + // remove corresponding keys from genericSessionData if exists + includedToGenericAuthData.remove(PVPAttributeDefinitions.PRINCIPAL_NAME_NAME); + includedToGenericAuthData.remove(PVPAttributeDefinitions.GIVEN_NAME_NAME); + includedToGenericAuthData.remove(PVPAttributeDefinitions.BIRTHDATE_NAME); + includedToGenericAuthData.remove(PVPAttributeDefinitions.EID_SOURCE_PIN_NAME); + includedToGenericAuthData.remove(PVPAttributeDefinitions.EID_SOURCE_PIN_TYPE_NAME); + } + + } + + if (authData.getIdentificationType() != null + && !authData.getIdentificationType().equals(EAAFConstants.URN_PREFIX_BASEID)) { + log.trace("IdentificationType is not a baseID --> clear it. "); + authData.setBpk(authData.getIdentificationValue()); + authData.setBpkType(authData.getIdentificationType()); + + authData.setIdentificationValue(null); + authData.setIdentificationType(null); + } + + + // #################################################### + // set QAA level + setQaaLevel(authData, authProcessData, pendingReq); + + + // #################################################### + // set isForeigner flag + setFlagForeigner(authData, authProcessData, pendingReq); + + + // #################################################### + // set citizen country-code + setCitizenCountryCode(authData, authProcessData, pendingReq); + + + // #################################################### + // set bPK and IdentityLink + final String pvpBpkValue = getBpkValueFromPvpAttribute(authProcessData); + final String pvpBpkTypeAttr = getBpkTypeFromPvpAttribute(authProcessData); + final Pair pvpEncBpkAttr = getEncryptedBpkFromPvpAttribute(authProcessData, + authData, pendingReq.getServiceProviderConfiguration()); + + // check if a unique ID for this citizen exists + if (StringUtils.isEmpty(authData.getIdentificationValue()) && StringUtils.isEmpty(pvpBpkValue) + && StringUtils.isEmpty(authData.getBpk()) && pvpEncBpkAttr == null) { + log.info( + "Can not build authData, because moaSession include no bPK, encrypted bPK or baseID"); + throw new EaafBuilderException("builder.08", + new Object[] {"No " + PVPAttributeDefinitions.BPK_FRIENDLY_NAME + " or " + + PVPAttributeDefinitions.EID_SOURCE_PIN_FRIENDLY_NAME + " or " + + PVPAttributeDefinitions.ENC_BPK_LIST_FRIENDLY_NAME}, + "No " + PVPAttributeDefinitions.BPK_FRIENDLY_NAME + " or " + + PVPAttributeDefinitions.EID_SOURCE_PIN_FRIENDLY_NAME + " or " + + PVPAttributeDefinitions.ENC_BPK_LIST_FRIENDLY_NAME); + + } + + // check if bPK already added to AuthData matches OA + if (StringUtils.isNotEmpty(authData.getBpk()) && matchsReceivedBpkToOnlineApplication( + pendingReq.getServiceProviderConfiguration(), authData.getBpkType())) { + log.debug("Correct bPK is already included in AuthData."); + + // check if bPK received by PVP-Attribute matches OA + } else if (StringUtils.isNotEmpty(pvpBpkValue) && matchsReceivedBpkToOnlineApplication( + pendingReq.getServiceProviderConfiguration(), pvpBpkTypeAttr)) { + log.debug("Receive correct bPK from PVP-Attribute"); + authData.setBpk(pvpBpkValue); + authData.setBpkType(pvpBpkTypeAttr); + + // baseID is in AuthSesson --> calculate bPK directly + } else if (StringUtils.isNotEmpty(authData.getIdentificationValue())) { + log.debug("Citizen baseID is in MOASession --> calculate bPK from this."); + final Pair result = buildOAspecificbPK(pendingReq, authData); + authData.setBpk(result.getFirst()); + authData.setBpkType(result.getSecond()); + + // check if decrypted bPK exists + } else if (pvpEncBpkAttr != null) { + log.debug("Receive bPK as encrypted bPK and decryption was possible."); + authData.setBpk(pvpEncBpkAttr.getFirst()); + authData.setBpkType(pvpEncBpkAttr.getSecond()); + + // ask SZR to get bPK + } else { + String notValidbPK = authData.getBpk(); + String notValidBpkType = authData.getBpkType(); + if (StringUtils.isEmpty(notValidbPK) && StringUtils.isEmpty(notValidBpkType)) { + notValidbPK = pvpBpkValue; + notValidBpkType = pvpBpkTypeAttr; + + if (StringUtils.isEmpty(notValidbPK) && StringUtils.isEmpty(notValidBpkType)) { + log.error("No bPK in MOASession. THIS error should not occur any more."); + throw new NullPointerException( + "No bPK in MOASession. THIS error should not occur any more."); + } + } + + final Pair baseIdFromSzr = + getbaseIdFromSzr(authData, notValidbPK, notValidBpkType); + if (baseIdFromSzr != null) { + log.info("Receive citizen baseID from SRZ. Authentication can be completed"); + authData.setIdentificationValue(baseIdFromSzr.getFirst()); + authData.setIdentificationType(baseIdFromSzr.getSecond()); + final Pair result = buildOAspecificbPK(pendingReq, authData); + authData.setBpk(result.getFirst()); + authData.setBpkType(result.getSecond()); + + } else { + log.warn( + "Can not build authData, because moaSession include no valid bPK, encrypted bPK or sourceID"); + throw new EaafBuilderException("builder.13", + new Object[] { + pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier()}, + "No valid " + PVPAttributeDefinitions.BPK_FRIENDLY_NAME + " or " + + PVPAttributeDefinitions.EID_SOURCE_PIN_FRIENDLY_NAME + " or " + + PVPAttributeDefinitions.ENC_BPK_LIST_FRIENDLY_NAME); + + } + } + + // build IdentityLink + if (authProcessData.getIdentityLink() != null) { + authData + .setIdentityLink(buildOAspecificIdentityLink(pendingReq.getServiceProviderConfiguration(), + authProcessData.getIdentityLink(), authData.getBpk(), authData.getBpkType())); + } else { + log.info("Can NOT set IdentityLink. Msg: No IdentityLink found"); + } + + } + + // extract a encrypted bPK from PVP attrobute + @Deprecated + protected abstract Pair getEncryptedBpkFromPvpAttribute( + IAuthProcessDataContainer authProcessDataContainer, AuthenticationData authData, + IspConfiguration spConfig) throws EaafBuilderException; + + // request baseId from SRZ + @Deprecated + protected abstract Pair getbaseIdFromSzr(AuthenticationData authData, + String notValidBpk, String notValidBpkType); + + @Deprecated + protected Pair buildOAspecificbPK(final IRequest pendingReq, + final AuthenticationData authData) throws EaafBuilderException { + final IspConfiguration oaParam = pendingReq.getServiceProviderConfiguration(); + + final String baseID = authData.getIdentificationValue(); + final String baseIdType = authData.getIdentificationType(); + Pair sectorSpecId = null; + + if (EAAFConstants.URN_PREFIX_BASEID.equals(baseIdType)) { + // SAML1 legacy target parameter work-around + final String spTargetId = oaParam.getAreaSpecificTargetIdentifier(); + log.debug("Use OA target identifier '" + spTargetId + "' from configuration"); + + new BpkBuilder(); + // calculate sector specific unique identifier + sectorSpecId = BpkBuilder.generateAreaSpecificPersonIdentifier(baseID, spTargetId); + + } else { + log.error( + "!!!baseID-element does not include a baseID. This should not be happen any more!!!"); + sectorSpecId = Pair.newInstance(baseID, baseIdType); + + } + + log.trace("Authenticate user with bPK:" + sectorSpecId.getFirst() + " Type:" + + sectorSpecId.getSecond()); + return sectorSpecId; + + } + + @Deprecated + protected IIdentityLink buildOAspecificIdentityLink(final IspConfiguration spConfig, + final IIdentityLink idl, final String bpk, final String bpkType) + throws EaafConfigurationException, XPathException, DOMException, EaafParserException { + if (spConfig.hasBaseIdTransferRestriction()) { + log.debug("SP: " + spConfig.getUniqueIdentifier() + + " has baseId transfer restriction. Remove baseId from IDL ..."); + final Element idlassertion = idl.getSamlAssertion(); + // set bpk/wpbk; + final Node prIdentification = XPathUtils.selectSingleNode(idlassertion, + SimpleIdentityLinkAssertionParser.PERSON_IDENT_VALUE_XPATH); + prIdentification.getFirstChild().setNodeValue(bpk); + // set bkp/wpbk type + final Node prIdentificationType = XPathUtils.selectSingleNode(idlassertion, + SimpleIdentityLinkAssertionParser.PERSON_IDENT_TYPE_XPATH); + prIdentificationType.getFirstChild().setNodeValue(bpkType); + + final SimpleIdentityLinkAssertionParser idlparser = + new SimpleIdentityLinkAssertionParser(idlassertion); + return idlparser.parseIdentityLink(); + + } else { + return idl; + } + + } + + /** + * Check a bPK-Type against a Service-Provider configuration
+ * If bPK-Type is null the result is false. + * + * @param oaParam Service-Provider configuration, never null + * @param bpkType bPK-Type to check + * @return true, if bPK-Type matchs to Service-Provider configuration, otherwise false + */ + @Deprecated + protected boolean matchsReceivedBpkToOnlineApplication(final IspConfiguration oaParam, + final String bpkType) { + return oaParam.getAreaSpecificTargetIdentifier().equals(bpkType); + + } + + /** + * Parse information from an IdentityLink into AuthData object. + * + * @param authData current authentication data + * @param identityLink User's identityLink + * @param includedGenericSessionData Generic AuthSession Data from PVP attributes + */ + @Deprecated + private void parseBasicUserInfosFromIdl(final AuthenticationData authData, + final IIdentityLink identityLink, final Collection includedGenericSessionData) { + authData.setIdentificationValue(identityLink.getIdentificationValue()); + authData.setIdentificationType(identityLink.getIdentificationType()); + + /* + * GivenNames and FamilyNames with simple Apostrophe were escaped with ' in + * IdentityLinkParser since 5 years. This feature was bug-fix for an SL1.0 AuthBlock problem. + * However, the authentication attributes (SAML2, eIDAS, OpenID-Connect) also includes this + * escaped values, but there it is not neccesary. We fix this problem in 3.4.3, but the fix can + * be deactivated for dependency reasons. + */ + if (basicConfig.getBasicConfigurationBoolean(CONFIG_PROP_ENABLE_IDL_ATTRIBUTE_ESCAPEING, + false)) { + authData.setGivenName(identityLink.getGivenName().replaceAll("'", "'")); + authData.setFamilyName(identityLink.getFamilyName().replaceAll("'", "'")); + + } else { + authData.setGivenName(identityLink.getGivenName()); + authData.setFamilyName(identityLink.getFamilyName()); + + } + + authData.setDateOfBirth(identityLink.getDateOfBirth()); + + + // remove corresponding keys from genericSessionData if exists + includedGenericSessionData.remove(PVPAttributeDefinitions.PRINCIPAL_NAME_NAME); + includedGenericSessionData.remove(PVPAttributeDefinitions.GIVEN_NAME_NAME); + includedGenericSessionData.remove(PVPAttributeDefinitions.BIRTHDATE_NAME); + includedGenericSessionData.remove(PVPAttributeDefinitions.EID_SOURCE_PIN_NAME); + includedGenericSessionData.remove(PVPAttributeDefinitions.EID_SOURCE_PIN_TYPE_NAME); + + } + + /** + * Get bPK from PVP Attribute 'BPK_NAME', which could be exist in MOASession as 'GenericData'.
+ * + *
+   * session.getGenericDataFromSession(PVPConstants.BPK_NAME, String.class)
+   * 
+ * + * @param session MOASession, but never null + * @return bPK, which was received by PVP-Attribute, or null if no attribute exists + */ + @Deprecated + private String getBpkValueFromPvpAttribute(final IAuthProcessDataContainer session) { + String pvpBpkValueAttr = + session.getGenericDataFromSession(PVPAttributeDefinitions.BPK_NAME, String.class); + if (StringUtils.isNotEmpty(pvpBpkValueAttr)) { + + // fix a wrong bPK-value prefix, which was used in some PVP Standardportal implementations + if (pvpBpkValueAttr.startsWith("bPK:")) { + log.warn("Attribute " + PVPAttributeDefinitions.BPK_NAME + + " contains a not standardize prefix! Staring attribute value correction process ..."); + pvpBpkValueAttr = pvpBpkValueAttr.substring("bPK:".length()); + + } + + final String[] spitted = pvpBpkValueAttr.split(":"); + if (spitted.length == 2) { + log.debug("Find PVP-Attr: " + PVPAttributeDefinitions.BPK_FRIENDLY_NAME); + return spitted[1]; + + + + } else if (spitted.length > 2) { + log.warn("Attribute " + PVPAttributeDefinitions.BPK_NAME + + " has a wrong encoding and can NOT be USED!" + " Value:" + pvpBpkValueAttr); + return null; + + } else { + log.debug("Find PVP-Attr: " + PVPAttributeDefinitions.BPK_FRIENDLY_NAME + + " without prefix. Use it as it is"); + return spitted[0]; + + } + + } + + return null; + } + + /** + * Get bPK-Type from PVP Attribute 'EID_SECTOR_FOR_IDENTIFIER_NAME', which could be exist in + * MOASession as 'GenericData'.
+ * + *
+   * session.getGenericDataFromSession(PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME, String.class)
+   * 
+ * + * @param session MOASession, but never null + * @return bPKType, which was received by PVP-Attribute, or null if no attribute + * exists + */ + @Deprecated + private String getBpkTypeFromPvpAttribute(final IAuthProcessDataContainer session) { + final String pvpBpkTypeAttr = session.getGenericDataFromSession( + PVPAttributeDefinitions.EID_SECTOR_FOR_IDENTIFIER_NAME, String.class); + + if (StringUtils.isNotEmpty(pvpBpkTypeAttr)) { + // //fix a wrong bPK-Type encoding, which was used in some PVP Standardportal implementations + // if (pvpbPKTypeAttr.startsWith(EAAFConstants.URN_PREFIX_CDID) && + // !pvpbPKTypeAttr.substring(EAAFConstants.URN_PREFIX_CDID.length(), + // EAAFConstants.URN_PREFIX_CDID.length() + 1).equals("+")) { + // log.warn("Receive uncorrect encoded bBKType attribute " + pvpbPKTypeAttr + " Starting + // attribute value correction ... "); + // pvpbPKTypeAttr = EAAFConstants.URN_PREFIX_CDID + "+" + + // pvpbPKTypeAttr.substring(EAAFConstants.URN_PREFIX_CDID.length() + 1); + // + // } + log.debug( + "Find PVP-Attr: " + PVPAttributeDefinitions.EID_SECTOR_FOR_IDENTIFIER_FRIENDLY_NAME); + return pvpBpkTypeAttr; + } + + return null; + + + /* + * INFO: This code could be used to extract the bPKType from 'PVPConstants.BPK_NAME', because + * the prefix of BPK_NAME attribute contains the postfix of the bPKType + * + * Now, all PVP Standardportals should be able to send 'EID_SECTOR_FOR_IDENTIFIER' PVP + * attributes + */ + // String pvpbPKValueAttr = session.getGenericDataFromSession(PVPConstants.BPK_NAME, + // String.class); + // String[] spitted = pvpbPKValueAttr.split(":"); + // if (MiscUtil.isEmpty(authData.getBPKType())) { + // Logger.debug("PVP assertion contains NO bPK/wbPK target attribute. " + + // "Starting target extraction from bPK/wbPK prefix ..."); + // //exract bPK/wbPK type from bpk attribute value prefix if type is + // //not transmitted as single attribute + // Pattern pattern = Pattern.compile("[a-zA-Z]{2}(-[a-zA-Z]+)?"); + // Matcher matcher = pattern.matcher(spitted[0]); + // if (matcher.matches()) { + // //find public service bPK + // authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + spitted[0]); + // Logger.debug("Found bPK prefix. Set target to " + authData.getBPKType()); + // + // } else { + // //find business service wbPK + // authData.setBPKType(Constants.URN_PREFIX_WBPK+ "+" + spitted[0]); + // Logger.debug("Found wbPK prefix. Set target to " + authData.getBPKType()); + // + // } + // } + + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/builder/BPKBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/builder/BPKBuilder.java deleted file mode 100644 index 602546a2..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/builder/BPKBuilder.java +++ /dev/null @@ -1,302 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * Copyright 2003 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ - - -package at.gv.egiz.eaaf.core.impl.idp.auth.builder; - -import java.security.InvalidKeyException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.text.SimpleDateFormat; -import java.util.Date; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.util.Base64Utils; - -import at.gv.egiz.eaaf.core.api.data.EAAFConstants; -import at.gv.egiz.eaaf.core.exceptions.EAAFBuilderException; -import at.gv.egiz.eaaf.core.impl.data.Pair; - -/** - * Builder for the bPK, as defined in - * "Ableitung f¨r die bereichsspezifische Personenkennzeichnung" - * version 1.0.1 from "reference.e-government.gv.at". - * - */ -public class BPKBuilder { - private static final Logger log = LoggerFactory.getLogger(BPKBuilder.class); - - /** - * Calculates an area specific unique person-identifier from a baseID - * - * @param baseID baseId from user but never null - * @param targetIdentifier target identifier for area specific identifier calculation but never null - * @return Pair consists of (unique person identifier for this target, targetArea) but never null - * @throws EAAFBuilderException if some input data are not valid - */ - public static Pair generateAreaSpecificPersonIdentifier(String baseID, String targetIdentifier) throws EAAFBuilderException { - return generateAreaSpecificPersonIdentifier(baseID, EAAFConstants.URN_PREFIX_BASEID, targetIdentifier); - - } - - /** - * Calculates an area specific unique person-identifier from an unique identifier with a specific type - * - * @param baseID baseId from user but never null - * @param baseIdType Type of the baseID but never null - * @param targetIdentifier target identifier for area specific identifier calculation but never null - * @return Pair consists of (unique person identifier for this target, targetArea) but never null - * @throws EAAFBuilderException if some input data are not valid - */ - public static Pair generateAreaSpecificPersonIdentifier(String baseID, String baseIdType, String targetIdentifier) throws EAAFBuilderException{ - if (StringUtils.isEmpty(baseID)) - throw new EAAFBuilderException("builder.00", new Object[]{"baseID is empty or null"}, - "BaseId is empty or null"); - - if (StringUtils.isEmpty(baseIdType)) - throw new EAAFBuilderException("builder.00", new Object[]{"the type of baseID is empty or null"}, - "Type of baseId is empty or null"); - - if (StringUtils.isEmpty(targetIdentifier)) - throw new EAAFBuilderException("builder.00", new Object[]{"SP specific target identifier is empty or null"}, - "SP specific target identifier is empty or null"); - - if (baseIdType.equals(EAAFConstants.URN_PREFIX_BASEID)) { - log.trace("Find baseID. Starting unique identifier caluclation for this target"); - - if (targetIdentifier.startsWith(EAAFConstants.URN_PREFIX_CDID) || - targetIdentifier.startsWith(EAAFConstants.URN_PREFIX_WBPK)) { - log.trace("Calculate bPK, wbPK, or STORK identifier for target: " + targetIdentifier); - return Pair.newInstance(calculatebPKwbPK(baseID + "+" + targetIdentifier), targetIdentifier); - - } else if (targetIdentifier.startsWith(EAAFConstants.URN_PREFIX_EIDAS)) { - log.trace("Calculate eIDAS identifier for target: " + targetIdentifier); - final String[] splittedTarget = targetIdentifier.split("\\+"); - final String cititzenCountryCode = splittedTarget[1]; - final String eIDASOutboundCountry = splittedTarget[2]; - - if (cititzenCountryCode.equalsIgnoreCase(eIDASOutboundCountry)) { - log.warn("Suspect configuration FOUND!!! CitizenCountry equals DestinationCountry"); - - } - return buildeIDASIdentifer(baseID, baseIdType, cititzenCountryCode, eIDASOutboundCountry); - - - } else - throw new EAAFBuilderException("builder.00", - new Object[]{"Target identifier: " + targetIdentifier + " is NOT allowed or unknown"}, - "Target identifier: " + targetIdentifier + " is NOT allowed or unknown"); - - } else { - log.trace("BaseID is not of type " + EAAFConstants.URN_PREFIX_BASEID + ". Check type against requested target ..."); - if (baseIdType.equals(targetIdentifier)) { - log.debug("Unique identifier is already area specific. Is nothing todo"); - return Pair.newInstance(baseID, targetIdentifier); - - } else { - log.warn("Get unique identifier for target: " + baseIdType + " but target: " + targetIdentifier + " is required!"); - throw new EAAFBuilderException("builder.00", - new Object[]{"Get unique identifier for target: " + baseIdType + " but target: " + targetIdentifier + " is required"}, - "Get unique identifier for target: " + baseIdType + " but target: " + targetIdentifier + " is required"); - - } - } - } - - - /** - * Builds the eIDAS from the given parameters. - * - * @param baseID baseID of the citizen - * @param baseIDType Type of the baseID - * @param sourceCountry CountryCode of that country, which build the eIDAs ID - * @param destinationCountry CountryCode of that country, which receives the eIDAs ID - * - * @return Pair in a BASE64 encoding - * @throws EAAFBuilderException if some input data are not valid - */ - private static Pair buildeIDASIdentifer(String baseID, String baseIDType, String sourceCountry, String destinationCountry) - throws EAAFBuilderException { - String bPK = null; - String bPKType = null; - - // check if we have been called by public sector application - if (baseIDType.startsWith(EAAFConstants.URN_PREFIX_BASEID)) { - bPKType = EAAFConstants.URN_PREFIX_EIDAS + sourceCountry + "+" + destinationCountry; - log.debug("Building eIDAS identification from: [identValue]+" + bPKType); - bPK = calculatebPKwbPK(baseID + "+" + bPKType); - - } else { // if not, sector identification value is already calculated by BKU - log.debug("eIDAS eIdentifier already provided by BKU"); - bPK = baseID; - } - - if ((StringUtils.isEmpty(bPK) || - StringUtils.isEmpty(sourceCountry) || - StringUtils.isEmpty(destinationCountry))) { - throw new EAAFBuilderException("builder.00", - new Object[]{"eIDAS-ID", "Unvollständige Parameterangaben: identificationValue=" + - bPK + ", Zielland=" + destinationCountry + ", Ursprungsland=" + sourceCountry} - ,"eIDAS-ID: Unvollständige Parameterangaben: identificationValue=" + - bPK + ", Zielland=" + destinationCountry + ", Ursprungsland=" + sourceCountry); - } - - log.trace("eIDAS pseudonym generation finished. "); - final String eIdentifier = sourceCountry + "/" + destinationCountry + "/" + bPK; - - return Pair.newInstance(eIdentifier, bPKType); - } - - public static String encryptBPK(String bpk, String target, PublicKey publicKey) throws EAAFBuilderException { - final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); - if (target.startsWith(EAAFConstants.URN_PREFIX_CDID)) - target = target.substring((EAAFConstants.URN_PREFIX_CDID).length()); - - final String input = "V1::urn:publicid:gv.at:cdid+" + target + "::" - + bpk + "::" - + sdf.format(new Date()); - //System.out.println(input); - byte[] result; - try { - final byte[] inputBytes = input.getBytes("ISO-8859-1"); - result = encrypt(inputBytes, publicKey); - return new String(Base64Utils.encode(result), "ISO-8859-1").replaceAll("\r\n", ""); - //return new String(Base64Utils.encode(result, "ISO-8859-1")).replaceAll("\r\n", ""); - - - } catch (final Exception e) { - throw new EAAFBuilderException("bPK encryption FAILED", null, - e.getMessage(), e); - - } - } - - public static String decryptBPK(String encryptedBpk, String target, PrivateKey privateKey) throws EAAFBuilderException { - String decryptedString; - try { - //byte[] encryptedBytes = Base64Utils.decode(encryptedBpk, false, "ISO-8859-1"); - final byte[] encryptedBytes = Base64Utils.decode(encryptedBpk.getBytes("ISO-8859-1")); - final byte[] decryptedBytes = decrypt(encryptedBytes, privateKey); - decryptedString = new String(decryptedBytes, "ISO-8859-1"); - - } catch (final Exception e) { - throw new EAAFBuilderException("bPK decryption FAILED", null, - e.getMessage(), e); - - } - - String tmp = decryptedString.substring(decryptedString.indexOf('+') + 1); - final String sector = tmp.substring(0, tmp.indexOf("::")); - tmp = tmp.substring(tmp.indexOf("::") + 2); - final String bPK = tmp.substring(0, tmp.indexOf("::")); - - if (target.startsWith(EAAFConstants.URN_PREFIX_CDID + "+")) - target = target.substring((EAAFConstants.URN_PREFIX_CDID + "+").length()); - - if (target.equals(sector)) - return bPK; - - else { - log.error("Decrypted bPK does not match to request bPK target."); - return null; - } - } - - private static String calculatebPKwbPK(String basisbegriff) throws EAAFBuilderException { - try { - final MessageDigest md = MessageDigest.getInstance("SHA-1"); - final byte[] hash = md.digest(basisbegriff.getBytes("ISO-8859-1")); - final String hashBase64 = new String(Base64Utils.encode(hash), "ISO-8859-1").replaceAll("\r\n", ""); //Base64Utils.encode(hash); - return hashBase64; - - } catch (final Exception ex) { - throw new EAAFBuilderException("builder.00", new Object[]{"bPK/wbPK", ex.toString()}, - ex.getMessage(), ex); - - } - - } - - private static byte[] encrypt(byte[] inputBytes, PublicKey publicKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { - byte[] result; - Cipher cipher = null; - try { - cipher = Cipher.getInstance("RSA/ECB/OAEPPadding"); // try with bouncycastle - - } catch(final NoSuchAlgorithmException e) { - cipher = Cipher.getInstance("RSA/ECB/OAEP"); // try with iaik provider - } - cipher.init(Cipher.ENCRYPT_MODE, publicKey); - result = cipher.doFinal(inputBytes); - - return result; - } - - private static byte[] decrypt(byte[] encryptedBytes, PrivateKey privateKey) - throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{ - byte[] result; - Cipher cipher = null; - try { - cipher = Cipher.getInstance("RSA/ECB/OAEPPadding"); // try with bouncycastle - - } catch(final NoSuchAlgorithmException e) { - cipher = Cipher.getInstance("RSA/ECB/OAEP"); // try with iaik provider - - } - cipher.init(Cipher.DECRYPT_MODE, privateKey); - result = cipher.doFinal(encryptedBytes); - return result; - - } -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/builder/BpkBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/builder/BpkBuilder.java new file mode 100644 index 00000000..765a6669 --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/builder/BpkBuilder.java @@ -0,0 +1,312 @@ +/* + * Copyright 2014 Federal Chancellery Austria MOA-ID has been developed in a cooperation between + * BRZ, the Federal Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + + + +package at.gv.egiz.eaaf.core.impl.idp.auth.builder; + +import java.security.InvalidKeyException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.text.SimpleDateFormat; +import java.util.Date; +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; +import at.gv.egiz.eaaf.core.exceptions.EaafBuilderException; +import at.gv.egiz.eaaf.core.impl.data.Pair; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.util.Base64Utils; + +/** + * Builder for the bPK, as defined in + * "Ableitung f¨r die bereichsspezifische Personenkennzeichnung" version + * 1.0.1 from "reference.e-government.gv.at". + * + */ +public class BpkBuilder { + private static final Logger log = LoggerFactory.getLogger(BpkBuilder.class); + + /** + * Calculates an area specific unique person-identifier from a baseID. + * + * @param baseID baseId from user but never null + * @param targetIdentifier target identifier for area specific identifier calculation but never + * null + * @return Pair consists of (unique person identifier for this target, targetArea) but never null + * @throws EaafBuilderException if some input data are not valid + */ + public static Pair generateAreaSpecificPersonIdentifier(final String baseID, + final String targetIdentifier) throws EaafBuilderException { + return generateAreaSpecificPersonIdentifier(baseID, EAAFConstants.URN_PREFIX_BASEID, + targetIdentifier); + + } + + /** + * Calculates an area specific unique person-identifier from an unique identifier with a specific + * type. + * + * @param baseID baseId from user but never null + * @param baseIdType Type of the baseID but never null + * @param targetIdentifier target identifier for area specific identifier calculation but never + * null + * @return Pair consists of (unique person identifier for this target, targetArea) but never null + * @throws EaafBuilderException if some input data are not valid + */ + public static Pair generateAreaSpecificPersonIdentifier(final String baseID, + final String baseIdType, final String targetIdentifier) throws EaafBuilderException { + if (StringUtils.isEmpty(baseID)) { + throw new EaafBuilderException("builder.00", new Object[] {"baseID is empty or null"}, + "BaseId is empty or null"); + } + + if (StringUtils.isEmpty(baseIdType)) { + throw new EaafBuilderException("builder.00", + new Object[] {"the type of baseID is empty or null"}, "Type of baseId is empty or null"); + } + + if (StringUtils.isEmpty(targetIdentifier)) { + throw new EaafBuilderException("builder.00", + new Object[] {"SP specific target identifier is empty or null"}, + "SP specific target identifier is empty or null"); + } + + if (baseIdType.equals(EAAFConstants.URN_PREFIX_BASEID)) { + log.trace("Find baseID. Starting unique identifier caluclation for this target"); + + if (targetIdentifier.startsWith(EAAFConstants.URN_PREFIX_CDID) + || targetIdentifier.startsWith(EAAFConstants.URN_PREFIX_WBPK)) { + log.trace("Calculate bPK, wbPK, or STORK identifier for target: " + targetIdentifier); + return Pair.newInstance(calculatebPKwbPK(baseID + "+" + targetIdentifier), + targetIdentifier); + + } else if (targetIdentifier.startsWith(EAAFConstants.URN_PREFIX_EIDAS)) { + log.trace("Calculate eIDAS identifier for target: " + targetIdentifier); + final String[] splittedTarget = targetIdentifier.split("\\+"); + final String cititzenCountryCode = splittedTarget[1]; + final String eidasOutboundCountry = splittedTarget[2]; + + if (cititzenCountryCode.equalsIgnoreCase(eidasOutboundCountry)) { + log.warn("Suspect configuration FOUND!!! CitizenCountry equals DestinationCountry"); + + } + return buildEidasIdentifer(baseID, baseIdType, cititzenCountryCode, eidasOutboundCountry); + + + } else { + throw new EaafBuilderException("builder.00", + new Object[] {"Target identifier: " + targetIdentifier + " is NOT allowed or unknown"}, + "Target identifier: " + targetIdentifier + " is NOT allowed or unknown"); + } + + } else { + log.trace("BaseID is not of type " + EAAFConstants.URN_PREFIX_BASEID + + ". Check type against requested target ..."); + if (baseIdType.equals(targetIdentifier)) { + log.debug("Unique identifier is already area specific. Is nothing todo"); + return Pair.newInstance(baseID, targetIdentifier); + + } else { + log.warn("Get unique identifier for target: " + baseIdType + " but target: " + + targetIdentifier + " is required!"); + throw new EaafBuilderException("builder.00", + new Object[] {"Get unique identifier for target: " + baseIdType + " but target: " + + targetIdentifier + " is required"}, + "Get unique identifier for target: " + baseIdType + " but target: " + targetIdentifier + + " is required"); + + } + } + } + + + /** + * Builds the eIDAS from the given parameters. + * + * @param baseId baseID of the citizen + * @param baseIdType Type of the baseID + * @param sourceCountry CountryCode of that country, which build the eIDAs ID + * @param destinationCountry CountryCode of that country, which receives the eIDAs ID + * + * @return Pair eIDAs/bPKType in a BASE64 encoding + * @throws EaafBuilderException if some input data are not valid + */ + private static Pair buildEidasIdentifer(final String baseId, + final String baseIdType, final String sourceCountry, final String destinationCountry) + throws EaafBuilderException { + String bpk = null; + String bpkType = null; + + // check if we have been called by public sector application + if (baseIdType.startsWith(EAAFConstants.URN_PREFIX_BASEID)) { + bpkType = EAAFConstants.URN_PREFIX_EIDAS + sourceCountry + "+" + destinationCountry; + log.debug("Building eIDAS identification from: [identValue]+" + bpkType); + bpk = calculatebPKwbPK(baseId + "+" + bpkType); + + } else { // if not, sector identification value is already calculated by BKU + log.debug("eIDAS eIdentifier already provided by BKU"); + bpk = baseId; + } + + if ((StringUtils.isEmpty(bpk) || StringUtils.isEmpty(sourceCountry) + || StringUtils.isEmpty(destinationCountry))) { + throw new EaafBuilderException("builder.00", + new Object[] {"eIDAS-ID", + "Unvollständige Parameterangaben: identificationValue=" + bpk + ", Zielland=" + + destinationCountry + ", Ursprungsland=" + sourceCountry}, + "eIDAS-ID: Unvollständige Parameterangaben: identificationValue=" + bpk + ", Zielland=" + + destinationCountry + ", Ursprungsland=" + sourceCountry); + } + + log.trace("eIDAS pseudonym generation finished. "); + final String eIdentifier = sourceCountry + "/" + destinationCountry + "/" + bpk; + + return Pair.newInstance(eIdentifier, bpkType); + } + + /** + * Create an encrypted bPK. + * + * @param bpk unencrypted bPK + * @param target bPK target + * @param publicKey Public-Key used for encryption + * @return encrypted bPK + * @throws EaafBuilderException In case of an error + */ + public static String encryptBpk(final String bpk, String target, final PublicKey publicKey) + throws EaafBuilderException { + final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); + if (target.startsWith(EAAFConstants.URN_PREFIX_CDID)) { + target = target.substring((EAAFConstants.URN_PREFIX_CDID).length()); + } + + final String input = + "V1::urn:publicid:gv.at:cdid+" + target + "::" + bpk + "::" + sdf.format(new Date()); + // System.out.println(input); + byte[] result; + try { + final byte[] inputBytes = input.getBytes("ISO-8859-1"); + result = encrypt(inputBytes, publicKey); + return new String(Base64Utils.encode(result), "ISO-8859-1").replaceAll("\r\n", ""); + // return new String(Base64Utils.encode(result, "ISO-8859-1")).replaceAll("\r\n", ""); + + + } catch (final Exception e) { + throw new EaafBuilderException("bPK encryption FAILED", null, e.getMessage(), e); + + } + } + + /** + * Decrypt an encrypted bPK. + * + * @param encryptedBpk encrypted bPK + * @param target bPK target + * @param privateKey private-key for decryption + * @return bPK + * @throws EaafBuilderException In case of an error + */ + public static String decryptBpk(final String encryptedBpk, String target, + final PrivateKey privateKey) throws EaafBuilderException { + String decryptedString; + try { + // byte[] encryptedBytes = Base64Utils.decode(encryptedBpk, false, "ISO-8859-1"); + final byte[] encryptedBytes = Base64Utils.decode(encryptedBpk.getBytes("ISO-8859-1")); + final byte[] decryptedBytes = decrypt(encryptedBytes, privateKey); + decryptedString = new String(decryptedBytes, "ISO-8859-1"); + + } catch (final Exception e) { + throw new EaafBuilderException("bPK decryption FAILED", null, e.getMessage(), e); + + } + + String tmp = decryptedString.substring(decryptedString.indexOf('+') + 1); + final String sector = tmp.substring(0, tmp.indexOf("::")); + tmp = tmp.substring(tmp.indexOf("::") + 2); + final String bPK = tmp.substring(0, tmp.indexOf("::")); + + if (target.startsWith(EAAFConstants.URN_PREFIX_CDID + "+")) { + target = target.substring((EAAFConstants.URN_PREFIX_CDID + "+").length()); + } + + if (target.equals(sector)) { + return bPK; + } else { + log.error("Decrypted bPK does not match to request bPK target."); + return null; + } + } + + private static String calculatebPKwbPK(final String basisbegriff) throws EaafBuilderException { + try { + final MessageDigest md = MessageDigest.getInstance("SHA-1"); + final byte[] hash = md.digest(basisbegriff.getBytes("ISO-8859-1")); + final String hashBase64 = + new String(Base64Utils.encode(hash), "ISO-8859-1").replaceAll("\r\n", ""); // Base64Utils.encode(hash); + return hashBase64; + + } catch (final Exception ex) { + throw new EaafBuilderException("builder.00", new Object[] {"bPK/wbPK", ex.toString()}, + ex.getMessage(), ex); + + } + + } + + private static byte[] encrypt(final byte[] inputBytes, final PublicKey publicKey) + throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, + IllegalBlockSizeException, BadPaddingException { + byte[] result; + Cipher cipher = null; + try { + cipher = Cipher.getInstance("RSA/ECB/OAEPPadding"); // try with bouncycastle + + } catch (final NoSuchAlgorithmException e) { + cipher = Cipher.getInstance("RSA/ECB/OAEP"); // try with iaik provider + } + cipher.init(Cipher.ENCRYPT_MODE, publicKey); + result = cipher.doFinal(inputBytes); + + return result; + } + + private static byte[] decrypt(final byte[] encryptedBytes, final PrivateKey privateKey) + throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, + IllegalBlockSizeException, BadPaddingException { + byte[] result; + Cipher cipher = null; + try { + cipher = Cipher.getInstance("RSA/ECB/OAEPPadding"); // try with bouncycastle + + } catch (final NoSuchAlgorithmException e) { + cipher = Cipher.getInstance("RSA/ECB/OAEP"); // try with iaik provider + + } + cipher.init(Cipher.DECRYPT_MODE, privateKey); + result = cipher.doFinal(encryptedBytes); + return result; + + } +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/data/AuthProcessDataWrapper.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/data/AuthProcessDataWrapper.java index e096b8e6..7c143ca2 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/data/AuthProcessDataWrapper.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/data/AuthProcessDataWrapper.java @@ -1,24 +1,20 @@ /******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ /******************************************************************************* *******************************************************************************/ @@ -29,226 +25,276 @@ package at.gv.egiz.eaaf.core.impl.idp.auth.data; import java.util.Date; import java.util.HashMap; import java.util.Map; - +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; +import at.gv.egiz.eaaf.core.api.idp.EaafAuthProcessDataConstants; +import at.gv.egiz.eaaf.core.api.idp.auth.data.IAuthProcessDataContainer; +import at.gv.egiz.eaaf.core.api.idp.auth.data.IIdentityLink; +import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import at.gv.egiz.eaaf.core.api.data.EAAFConstants; -import at.gv.egiz.eaaf.core.api.idp.EAAFAuthProcessDataConstants; -import at.gv.egiz.eaaf.core.api.idp.auth.data.IAuthProcessDataContainer; -import at.gv.egiz.eaaf.core.api.idp.auth.data.IIdentityLink; -import at.gv.egiz.eaaf.core.exceptions.EAAFStorageException; - -public class AuthProcessDataWrapper implements IAuthProcessDataContainer, EAAFAuthProcessDataConstants { - private static final Logger log = LoggerFactory.getLogger(AuthProcessDataWrapper.class); - - protected Map authProcessData; - - public AuthProcessDataWrapper(Map authProcessData) { - this.authProcessData = authProcessData; - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#getIssueInstant() - */ - @Override - public String getIssueInstant() { - return wrapStringObject(VALUE_ISSUEINSTANT, null, String.class); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setIssueInstant(java.lang.String) - */ - @Override - public void setIssueInstant(String issueInstant) { - authProcessData.put(VALUE_ISSUEINSTANT, issueInstant); - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#isAuthenticated() - */ - @Override - public boolean isAuthenticated() { - return wrapStringObject(FLAG_IS_AUTHENTICATED, false, Boolean.class); - - } - - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setAuthenticated(boolean) - */ - @Override - public void setAuthenticated(boolean authenticated) { - authProcessData.put(FLAG_IS_AUTHENTICATED, authenticated); - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#getIdentityLink() - */ - @Override - public IIdentityLink getIdentityLink() { - return wrapStringObject(VALUE_IDENTITYLINK, null, IIdentityLink.class); - - } - - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setIdentityLink(at.gv.egovernment.moa.id.auth.data.IdentityLink) - */ - @Override - public void setIdentityLink(IIdentityLink identityLink) { - authProcessData.put(VALUE_IDENTITYLINK, identityLink); - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#isMandateUsed() - */ - @Override - public boolean isMandateUsed() { - return wrapStringObject(FLAG_USE_MANDATE, false, Boolean.class); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setUseMandates(boolean) - */ - @Override - public void setUseMandates(boolean useMandates) { - authProcessData.put(FLAG_USE_MANDATE, useMandates); - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#getQAALevel() - */ - @Override - public String getQAALevel() { - return wrapStringObject(VALUE_QAALEVEL, null, String.class); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setQAALevel(java.lang.String) - */ - @Override - public void setQAALevel(String qAALevel) { - authProcessData.put(VALUE_QAALEVEL, qAALevel); - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#isForeigner() - */ - @Override - public boolean isForeigner() { - return wrapStringObject(FLAG_IS_FOREIGNER, false, Boolean.class); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setForeigner(boolean) - */ - @Override - public void setForeigner(boolean isForeigner) { - authProcessData.put(FLAG_IS_FOREIGNER, isForeigner); - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#isOW() - */ - @Override - public boolean isOW() { - return wrapStringObject(FLAG_IS_ORGANWALTER, false, Boolean.class); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setOW(boolean) - */ - @Override - public void setOW(boolean isOW) { - authProcessData.put(FLAG_IS_ORGANWALTER, isOW); - - } - - @Override - public boolean isEIDProcess() { - return wrapStringObject(FLAG_IS_NEW_EID_PROCESS, false, Boolean.class); - } - - @Override - public void setEIDProcess(boolean value) { - authProcessData.put(FLAG_IS_NEW_EID_PROCESS, value); - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#getSessionCreated() - */ - @Override - public Date getSessionCreated() { - return wrapStringObject(EAAFConstants.AUTH_DATA_CREATED, null, Date.class); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#getGenericSessionDataStorage() - */ - @Override - public Map getGenericSessionDataStorage() { - final Map result = new HashMap(); - for (final String el : authProcessData.keySet()) { - if (el.startsWith(GENERIC_PREFIX)) - result.put(el.substring(GENERIC_PREFIX.length()), authProcessData.get(el)); - - } - - return result; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#getGenericDataFromSession(java.lang.String) - */ - @Override - public Object getGenericDataFromSession(String key) { - return authProcessData.get(GENERIC_PREFIX + key); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#getGenericDataFromSession(java.lang.String, java.lang.Class) - */ - @Override - public T getGenericDataFromSession(String key, Class clazz) { - return wrapStringObject(GENERIC_PREFIX + key, null, clazz); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setGenericDataToSession(java.lang.String, java.lang.Object) - */ - @Override - public void setGenericDataToSession(String key, Object object) throws EAAFStorageException { - authProcessData.put(GENERIC_PREFIX + key, object); - - } - - protected T wrapStringObject(String key, Object defaultValue, Class clazz) { - if (StringUtils.isNotEmpty(key)) { - final Object obj = authProcessData.get(key); - if (obj != null && clazz.isInstance(obj)) - return (T) obj; - } - - if (defaultValue == null) - return null; - - else if (clazz.isInstance(defaultValue)) - return (T)defaultValue; - - else { - log.error("DefaultValue: " + defaultValue.getClass().getName() + " is not of Type:" + clazz.getName()); - throw new IllegalStateException("DefaultValue: " + defaultValue.getClass().getName() + " is not of Type:" + clazz.getName()); - - } - } +public class AuthProcessDataWrapper + implements IAuthProcessDataContainer, EaafAuthProcessDataConstants { + private static final Logger log = LoggerFactory.getLogger(AuthProcessDataWrapper.class); + + protected Map authProcessData; + + public AuthProcessDataWrapper(final Map authProcessData) { + this.authProcessData = authProcessData; + + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#getIssueInstant() + */ + @Override + public String getIssueInstant() { + return wrapStringObject(VALUE_ISSUEINSTANT, null, String.class); + } + + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setIssueInstant(java.lang.String) + */ + @Override + public void setIssueInstant(final String issueInstant) { + authProcessData.put(VALUE_ISSUEINSTANT, issueInstant); + + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#isAuthenticated() + */ + @Override + public boolean isAuthenticated() { + return wrapStringObject(FLAG_IS_AUTHENTICATED, false, Boolean.class); + + } + + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setAuthenticated(boolean) + */ + @Override + public void setAuthenticated(final boolean authenticated) { + authProcessData.put(FLAG_IS_AUTHENTICATED, authenticated); + + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#getIdentityLink() + */ + @Override + public IIdentityLink getIdentityLink() { + return wrapStringObject(VALUE_IDENTITYLINK, null, IIdentityLink.class); + + } + + + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setIdentityLink(at.gv.egovernment.moa + * .id.auth.data.IdentityLink) + */ + @Override + public void setIdentityLink(final IIdentityLink identityLink) { + authProcessData.put(VALUE_IDENTITYLINK, identityLink); + + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#isMandateUsed() + */ + @Override + public boolean isMandateUsed() { + return wrapStringObject(FLAG_USE_MANDATE, false, Boolean.class); + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setUseMandates(boolean) + */ + @Override + public void setUseMandates(final boolean useMandates) { + authProcessData.put(FLAG_USE_MANDATE, useMandates); + + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#getQAALevel() + */ + @Override + public String getQAALevel() { + return wrapStringObject(VALUE_QAALEVEL, null, String.class); + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setQAALevel(java.lang.String) + */ + @Override + public void setQAALevel(final String qAALevel) { + authProcessData.put(VALUE_QAALEVEL, qAALevel); + + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#isForeigner() + */ + @Override + public boolean isForeigner() { + return wrapStringObject(FLAG_IS_FOREIGNER, false, Boolean.class); + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setForeigner(boolean) + */ + @Override + public void setForeigner(final boolean isForeigner) { + authProcessData.put(FLAG_IS_FOREIGNER, isForeigner); + + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#isOW() + */ + @Override + public boolean isOW() { + return wrapStringObject(FLAG_IS_ORGANWALTER, false, Boolean.class); + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setOW(boolean) + */ + @Override + public void setOW(final boolean isOW) { + authProcessData.put(FLAG_IS_ORGANWALTER, isOW); + + } + + @Override + public boolean isEIDProcess() { + return wrapStringObject(FLAG_IS_NEW_EID_PROCESS, false, Boolean.class); + } + + @Override + public void setEIDProcess(final boolean value) { + authProcessData.put(FLAG_IS_NEW_EID_PROCESS, value); + + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#getSessionCreated() + */ + @Override + public Date getSessionCreated() { + return wrapStringObject(EAAFConstants.AUTH_DATA_CREATED, null, Date.class); + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#getGenericSessionDataStorage() + */ + @Override + public Map getGenericSessionDataStorage() { + final Map result = new HashMap<>(); + for (final Map.Entry el : authProcessData.entrySet()) { + if (el.getKey().startsWith(GENERIC_PREFIX)) { + result.put(el.getKey().substring(GENERIC_PREFIX.length()), el.getValue()); + } + + } + + return result; + } + + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#getGenericDataFromSession(java.lang. + * String) + */ + @Override + public Object getGenericDataFromSession(final String key) { + return authProcessData.get(GENERIC_PREFIX + key); + } + + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#getGenericDataFromSession(java.lang. + * String, java.lang.Class) + */ + @Override + public T getGenericDataFromSession(final String key, final Class clazz) { + return wrapStringObject(GENERIC_PREFIX + key, null, clazz); + } + + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setGenericDataToSession(java.lang. + * String, java.lang.Object) + */ + @Override + public void setGenericDataToSession(final String key, final Object object) + throws EaafStorageException { + authProcessData.put(GENERIC_PREFIX + key, object); + + } + + protected T wrapStringObject(final String key, final Object defaultValue, + final Class clazz) { + if (StringUtils.isNotEmpty(key)) { + final Object obj = authProcessData.get(key); + if (obj != null && clazz.isInstance(obj)) { + return (T) obj; + } + } + + if (defaultValue == null) { + return null; + } else if (clazz.isInstance(defaultValue)) { + return (T) defaultValue; + } else { + log.error("DefaultValue: " + defaultValue.getClass().getName() + " is not of Type:" + + clazz.getName()); + throw new IllegalStateException("DefaultValue: " + defaultValue.getClass().getName() + + " is not of Type:" + clazz.getName()); + + } + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/data/IdentityLink.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/data/IdentityLink.java index 367643ec..a1faa0a4 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/data/IdentityLink.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/data/IdentityLink.java @@ -1,306 +1,375 @@ /******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. + * Copyright 2014 Federal Chancellery Austria MOA-ID has been developed in a cooperation between + * BRZ, the Federal Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. ******************************************************************************/ /* - * Copyright 2003 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * Copyright 2003 Federal Chancellery Austria MOA-ID has been developed in a cooperation between + * BRZ, the Federal Chancellery Austria - ICT staff unit, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: http://www.osor.eu/eupl/ * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. */ package at.gv.egiz.eaaf.core.impl.idp.auth.data; +import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.Serializable; import java.security.PublicKey; - import javax.xml.transform.TransformerException; - -import org.w3c.dom.Element; - import at.gv.egiz.eaaf.core.api.idp.auth.data.IIdentityLink; -import at.gv.egiz.eaaf.core.impl.utils.DOMUtils; +import at.gv.egiz.eaaf.core.impl.utils.DomUtils; +import at.gv.egiz.eaaf.core.impl.utils.XPathUtils; +import org.w3c.dom.Element; /** - * Data contained in an identity link issued by BMI, relevant to the MOA ID component. - *
"IdentityLink" is the translation of "Personenbindung". - * + * Data contained in an identity link issued by BMI, relevant to the MOA ID component.
+ * "IdentityLink" is the translation of "Personenbindung". + * * @author Paul Ivancsics * @version $Id$ */ -public class IdentityLink implements Serializable, IIdentityLink{ - - private static final long serialVersionUID = 1L; - - /** - * "identificationValue" is the translation of "Stammzahl". - */ - private String identificationValue; - /** - * "identificationType" type of the identificationValue in the IdentityLink. - */ - private String identificationType; - /** - * first name - */ - private String givenName; - /** - * family name - */ - private String familyName; - - /** - * date of birth - */ - private String dateOfBirth; +public class IdentityLink implements Serializable, IIdentityLink { + + private static final long serialVersionUID = 1L; + + /** + * "identificationValue" is the translation of "Stammzahl". + */ + private String identificationValue; + /** + * "identificationType" type of the identificationValue in the IdentityLink. + */ + private String identificationType; + /** + * first name + */ + private String givenName; + /** + * family name + */ + private String familyName; + + /** + * date of birth + */ + private String dateOfBirth; /** * the original saml:Assertion-Element */ - private Element samlAssertion; + private transient Element samlAssertion; /** * the serializes saml:Assertion */ private String serializedSamlAssertion; - /** - * Element /saml:Assertion/saml:AttributeStatement/saml:Subject/saml:SubjectConfirmation/saml:SubjectConfirmationData/pr:Person - */ - private Element prPerson; /** - * we need for each dsig:Reference Element all - * transformation elements + * Element + * /saml:Assertion/saml:AttributeStatement/saml:Subject/saml:SubjectConfirmation/saml:SubjectConfirmationData/pr:Person + */ + private transient Element prPerson = null; + /** + * we need for each dsig:Reference Element all transformation elements */ - private Element[] dsigReferenceTransforms; - + private transient Element[] dsigReferenceTransforms = null; + /** * The issuing time of the identity link SAML assertion. */ private String issueInstant; /** - * we need all public keys stored in - * the identity link + * we need all public keys stored in the identity link */ private PublicKey[] publicKey; - /** - * Constructor for IdentityLink - */ - public IdentityLink() { - } + /** + * Constructor for IdentityLink + */ + public IdentityLink() {} - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getDateOfBirth() - */ + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getDateOfBirth() + */ @Override -public String getDateOfBirth() { + public String getDateOfBirth() { return dateOfBirth; } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getFamilyName() - */ + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getFamilyName() + */ @Override -public String getFamilyName() { + public String getFamilyName() { return familyName; } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getGivenName() - */ + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getGivenName() + */ @Override -public String getGivenName() { + public String getGivenName() { return givenName; } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getName() - */ + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getName() + */ @Override @Deprecated public String getName() { return givenName + " " + familyName; - + } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getIdentificationValue() - */ + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getIdentificationValue() + */ @Override -public String getIdentificationValue() { + public String getIdentificationValue() { return identificationValue; } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getIdentificationType() - */ - @Override - public String getIdentificationType() { - return identificationType; - } + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getIdentificationType() + */ + @Override + public String getIdentificationType() { + return identificationType; + } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setDateOfBirth(java.lang.String) - */ + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setDateOfBirth(java.lang.String) + */ @Override -public void setDateOfBirth(String dateOfBirth) { + public void setDateOfBirth(final String dateOfBirth) { this.dateOfBirth = dateOfBirth; } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setFamilyName(java.lang.String) - */ + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setFamilyName(java.lang.String) + */ @Override -public void setFamilyName(String familyName) { + public void setFamilyName(final String familyName) { this.familyName = familyName; } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setGivenName(java.lang.String) - */ + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setGivenName(java.lang.String) + */ @Override -public void setGivenName(String givenName) { + public void setGivenName(final String givenName) { this.givenName = givenName; } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setIdentificationValue(java.lang.String) - */ + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setIdentificationValue(java.lang.String) + */ @Override -public void setIdentificationValue(String identificationValue) { + public void setIdentificationValue(final String identificationValue) { this.identificationValue = identificationValue; } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setIdentificationType(java.lang.String) - */ - @Override - public void setIdentificationType(String identificationType) { - this.identificationType = identificationType; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getSamlAssertion() - */ + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setIdentificationType(java.lang.String) + */ @Override -public Element getSamlAssertion() { - return samlAssertion; + public void setIdentificationType(final String identificationType) { + this.identificationType = identificationType; } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getSerializedSamlAssertion() - */ + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getSamlAssertion() + */ @Override -public String getSerializedSamlAssertion() { + public Element getSamlAssertion() { + if (this.samlAssertion == null) { + try { + this.samlAssertion = DomUtils.parseXmlNonValidating( + new ByteArrayInputStream(serializedSamlAssertion.getBytes("UTF-8"))); + + } catch (final Exception e) { + throw new RuntimeException(e); + + } + } + + return this.samlAssertion; + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getSerializedSamlAssertion() + */ + @Override + public String getSerializedSamlAssertion() { return serializedSamlAssertion; } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setSamlAssertion(org.w3c.dom.Element) - */ + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setSamlAssertion(org.w3c.dom.Element) + */ @Override -public void setSamlAssertion(Element samlAssertion) throws TransformerException, IOException { + public void setSamlAssertion(final Element samlAssertion) + throws TransformerException, IOException { this.samlAssertion = samlAssertion; - this.serializedSamlAssertion = DOMUtils.serializeNode(samlAssertion); + this.serializedSamlAssertion = DomUtils.serializeNode(samlAssertion); } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getDsigReferenceTransforms() - */ + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getDsigReferenceTransforms() + */ @Override -public Element[] getDsigReferenceTransforms() { - return dsigReferenceTransforms; + public Element[] getDsigReferenceTransforms() { + if (dsigReferenceTransforms != null) { + return dsigReferenceTransforms.clone(); + + } else { + return null; + + } } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setDsigReferenceTransforms(org.w3c.dom.Element[]) - */ + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.auth.data.IIdentityLink#setDsigReferenceTransforms(org.w3c.dom.Element + * []) + */ @Override -public void setDsigReferenceTransforms(Element[] dsigReferenceTransforms) { - this.dsigReferenceTransforms = dsigReferenceTransforms; + public void setDsigReferenceTransforms(final Element[] dsigReferenceTransforms) { + if (dsigReferenceTransforms != null) { + this.dsigReferenceTransforms = dsigReferenceTransforms.clone(); + + } } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getPublicKey() - */ + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getPublicKey() + */ @Override -public PublicKey[] getPublicKey() { - return publicKey; + public PublicKey[] getPublicKey() { + if (publicKey != null) { + return publicKey.clone(); + + } else { + return null; + + } } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setPublicKey(java.security.PublicKey[]) - */ + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setPublicKey(java.security.PublicKey[]) + */ @Override -public void setPublicKey(PublicKey[] publicKey) { - this.publicKey = publicKey; + public void setPublicKey(final PublicKey[] publicKey) { + if (publicKey != null) { + this.publicKey = publicKey.clone(); + + } } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getPrPerson() - */ + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getPrPerson() + */ @Override -public Element getPrPerson() { + public Element getPrPerson() { + if (prPerson == null) { + prPerson = (Element) XPathUtils.selectSingleNode( + getSamlAssertion(), SimpleIdentityLinkAssertionParser.PERSON_XPATH); + + } + return prPerson; } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setPrPerson(org.w3c.dom.Element) - */ + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setPrPerson(org.w3c.dom.Element) + */ @Override -public void setPrPerson(Element prPerson) { + public void setPrPerson(final Element prPerson) { this.prPerson = prPerson; } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getIssueInstant() - */ + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getIssueInstant() + */ @Override -public String getIssueInstant() { + public String getIssueInstant() { return issueInstant; } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setIssueInstant(java.lang.String) - */ + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setIssueInstant(java.lang.String) + */ @Override -public void setIssueInstant(String issueInstant) { + public void setIssueInstant(final String issueInstant) { this.issueInstant = issueInstant; } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/data/SimpleIdentityLinkAssertionParser.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/data/SimpleIdentityLinkAssertionParser.java index 658e6a42..220469d3 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/data/SimpleIdentityLinkAssertionParser.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/data/SimpleIdentityLinkAssertionParser.java @@ -1,46 +1,36 @@ /******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. + * Copyright 2014 Federal Chancellery Austria MOA-ID has been developed in a cooperation between + * BRZ, the Federal Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. ******************************************************************************/ /* - * Copyright 2003 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * Copyright 2003 Federal Chancellery Austria MOA-ID has been developed in a cooperation between + * BRZ, the Federal Chancellery Austria - ICT staff unit, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: http://www.osor.eu/eupl/ * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. */ @@ -50,22 +40,19 @@ import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.List; - -import org.springframework.util.Base64Utils; -import org.w3c.dom.Element; -import org.w3c.dom.traversal.NodeIterator; - import at.gv.egiz.eaaf.core.api.data.XMLNamespaceConstants; import at.gv.egiz.eaaf.core.api.idp.auth.data.IIdentityLink; -import at.gv.egiz.eaaf.core.exceptions.EAAFParserException; -import at.gv.egiz.eaaf.core.impl.utils.DOMUtils; +import at.gv.egiz.eaaf.core.exceptions.EaafParserException; +import at.gv.egiz.eaaf.core.impl.utils.DomUtils; import at.gv.egiz.eaaf.core.impl.utils.XPathUtils; +import org.springframework.util.Base64Utils; +import org.w3c.dom.Element; +import org.w3c.dom.traversal.NodeIterator; /** - * Parses MDS from an identity link <saml:Assertion> - *
+ * Parses MDS from an identity link <saml:Assertion>
* This IDL parser extract NO key information! - + * */ public class SimpleIdentityLinkAssertionParser { @@ -79,246 +66,163 @@ public class SimpleIdentityLinkAssertionParser { private static final String SAML = XMLNamespaceConstants.SAML_PREFIX + ":"; /** Xpath prefix for reaching XML-DSIG Namespaces */ private static final String DSIG = XMLNamespaceConstants.DSIG_PREFIX + ":"; - /** Xpath prefix for reaching ECDS Namespaces */ - private static final String ECDSA = XMLNamespaceConstants.ECDSA_PREFIX + ":"; - /** Xpath expression to the root element */ - private static final String ROOT = ""; - /** Xpath expression to the SAMLSubjectConfirmationData element */ + /** Xpath expression to the root element */ + private static final String ROOT = ""; + /** Xpath expression to the SAMLSubjectConfirmationData element */ private static final String SAML_SUBJECT_CONFIRMATION_DATA_XPATH = - ROOT - + SAML - + "AttributeStatement/" - + SAML - + "Subject/" - + SAML - + "SubjectConfirmation/" - + SAML - + "SubjectConfirmationData"; + ROOT + SAML + "AttributeStatement/" + SAML + "Subject/" + SAML + "SubjectConfirmation/" + SAML + + "SubjectConfirmationData"; /** Xpath expression to the PersonData element */ - private static final String PERSON_XPATH = - SAML_SUBJECT_CONFIRMATION_DATA_XPATH - + "/" - + PDATA - + "Person"; - /** Xpath expression to the PersonData GivenName element */ + public static final String PERSON_XPATH = + SAML_SUBJECT_CONFIRMATION_DATA_XPATH + "/" + PDATA + "Person"; + /** Xpath expression to the PersonData GivenName element */ public static final String PERSON_GIVEN_NAME_XPATH = - PERSON_XPATH - + "/" - + PDATA - + "Name/" - + PDATA - + "GivenName"; + PERSON_XPATH + "/" + PDATA + "Name/" + PDATA + "GivenName"; /** Xpath expression to the PersonData FamilyName element */ public static final String PERSON_FAMILY_NAME_XPATH = - PERSON_XPATH - + "/" - + PDATA - + "Name/" - + PDATA - + "FamilyName"; + PERSON_XPATH + "/" + PDATA + "Name/" + PDATA + "FamilyName"; /** Xpath expression to the PersonData DateOfBirth element */ public static final String PERSON_DATE_OF_BIRTH_XPATH = - PERSON_XPATH - + "/" - + PDATA - + "DateOfBirth"; - /** Xpath expression to the Identification element */ - private static final String PERSON_IDENT_XPATH = - PERSON_XPATH - + "/" - + PDATA - + "Identification"; - - /** Xpath expression to the Identification Value element */ + PERSON_XPATH + "/" + PDATA + "DateOfBirth"; + /** Xpath expression to the Identification Value element */ public static final String PERSON_IDENT_VALUE_XPATH = - PERSON_XPATH - + "/" - + PDATA - + "Identification/" - + PDATA - + "Value"; + PERSON_XPATH + "/" + PDATA + "Identification/" + PDATA + "Value"; - /** Xpath expression to the Identification Value element */ - public static final String PERSON_IDENT_TYPE_XPATH = - PERSON_XPATH - + "/" - + PDATA - + "Identification/" - + PDATA - + "Type"; + /** Xpath expression to the Identification Value element */ + public static final String PERSON_IDENT_TYPE_XPATH = + PERSON_XPATH + "/" + PDATA + "Identification/" + PDATA + "Type"; - /** Xpath expression to the RSAKeyValue element */ - private static final String RSA_KEY_VALUE_XPATH = - ROOT - + SAML - + "AttributeStatement/" - + SAML - + "Attribute/" - + SAML - + "AttributeValue/" - + DSIG - + "RSAKeyValue"; + /** Xpath expression to the DSIG X509Certificate element */ + private static final String DSIG_CERTIFICATES_XPATH = ROOT + DSIG + "Signature/" + DSIG + + "KeyInfo/" + DSIG + "X509Data/" + DSIG + "X509Certificate"; + /** Xpath expression to the DSIG Transforms element */ + private static final String DSIG_REFERENCE_TRANSFORMATION_XPATH = + ROOT + DSIG + "Signature/" + DSIG + "SignedInfo/" + DSIG + "Reference/" + DSIG + "Transforms"; - /** Xpath expression to the ECKeyValue element */ - private static final String ECDSA_KEY_VALUE_XPATH = - ROOT - + SAML - + "AttributeStatement/" - + SAML - + "Attribute/" - + SAML - + "AttributeValue/" - + ECDSA - + "ECDSAKeyValue"; + /** The IssueInstant attribute of the SAML assertion */ + private static final String ISSUE_INSTANT_ATTR = "IssueInstant"; - - /** Xpath expression to the RSA Modulus element */ - private static final String RSA_KEY_MODULUS_XPATH = DSIG + "Modulus"; - /** Xpath expression to the RSA Exponent element */ - private static final String RSA_KEY_EXPONENT_XPATH = DSIG + "Exponent"; - /** Xpath expression to the DSIG X509Certificate element */ - private static final String DSIG_CERTIFICATES_XPATH = - ROOT - + DSIG - + "Signature/" - + DSIG - + "KeyInfo/" - + DSIG - + "X509Data/" - + DSIG - + "X509Certificate"; - /** Xpath expression to the DSIG Transforms element */ - private static final String DSIG_REFERENCE_TRANSFORMATION_XPATH = - ROOT - + DSIG - + "Signature/" - + DSIG - + "SignedInfo/" - + DSIG - + "Reference/" - + DSIG - + "Transforms"; - - /** The IssueInstant attribute of the SAML assertion */ - private static final String ISSUE_INSTANT_ATTR = "IssueInstant"; - - public static final String ASSERTIONID = "AssertionID"; - - /**This is the root element of the XML-Document provided by the Security Layer Card*/ + public static final String ASSERTIONID = "AssertionID"; + + /** This is the root element of the XML-Document provided by the Security Layer Card */ private Element assertionElem; /** - * Constructor for IdentityLinkAssertionParser. - * A DOM-representation of the incoming String will be created + * Constructor for IdentityLinkAssertionParser. A DOM-representation of the incoming + * String will be created + * * @param xmlAssertion <saml:Assertion> as String - * @throws EAAFParserException on any parsing error + * @throws EaafParserException on any parsing error */ - public SimpleIdentityLinkAssertionParser(String xmlAssertion) throws EAAFParserException { + public SimpleIdentityLinkAssertionParser(final String xmlAssertion) throws EaafParserException { try { - InputStream s = new ByteArrayInputStream(xmlAssertion.getBytes("UTF-8")); - assertionElem = DOMUtils.parseXmlValidating(s); - - } - catch (Throwable t) { - throw new EAAFParserException("parser.01", new Object[] { t.toString()}, t); - + final InputStream s = new ByteArrayInputStream(xmlAssertion.getBytes("UTF-8")); + assertionElem = DomUtils.parseXmlValidating(s); + + } catch (final Throwable t) { + throw new EaafParserException("parser.01", new Object[] {t.toString()}, t); + } } - + /** * Sets the <@link assertionElem>. + * * @param xmlAssertion the assertion element - * @throws EAAFParserException on any parsing error + * @throws EaafParserException on any parsing error */ - public SimpleIdentityLinkAssertionParser(Element xmlAssertion) throws EAAFParserException { + public SimpleIdentityLinkAssertionParser(final Element xmlAssertion) throws EaafParserException { assertionElem = xmlAssertion; } /** - * Constructor for IdentityLinkAssertionParser. - * A DOM-representation of the incoming Inputstream will be created + * Constructor for IdentityLinkAssertionParser. A DOM-representation of the incoming + * Inputstream will be created + * * @param xmlAssertion <saml:Assertion> as InputStream - * @throws EAAFParserException on any parsing error + * @throws EaafParserException on any parsing error */ - public SimpleIdentityLinkAssertionParser(InputStream xmlAssertion) throws EAAFParserException { + public SimpleIdentityLinkAssertionParser(final InputStream xmlAssertion) + throws EaafParserException { try { - assertionElem = DOMUtils.parseXmlValidating(xmlAssertion); - - } - catch (Throwable t) { - throw new EAAFParserException("parser.01", new Object[] { t.toString() }, t); - + assertionElem = DomUtils.parseXmlValidating(xmlAssertion); + + } catch (final Throwable t) { + throw new EaafParserException("parser.01", new Object[] {t.toString()}, t); + } } /** * Parses the identity link from the <saml:Assertion> + * * @return Identity link - * @throws EAAFParserException on any parsing error + * @throws EaafParserException on any parsing error */ - public IIdentityLink parseIdentityLink() throws EAAFParserException { + public IIdentityLink parseIdentityLink() throws EaafParserException { IIdentityLink identityLink; try { identityLink = new IdentityLink(); identityLink.setSamlAssertion(assertionElem); identityLink.setIssueInstant(assertionElem.getAttribute(ISSUE_INSTANT_ATTR)); - identityLink.setPrPerson((Element) - XPathUtils.selectSingleNode(assertionElem, PERSON_XPATH)); + identityLink.setPrPerson((Element) XPathUtils.selectSingleNode(assertionElem, PERSON_XPATH)); identityLink.setIdentificationValue( - XPathUtils.getElementValue(assertionElem, PERSON_IDENT_VALUE_XPATH, "")); - identityLink.setIdentificationType( - XPathUtils.getElementValue(assertionElem, PERSON_IDENT_TYPE_XPATH, "")); - - String givenname = XPathUtils.getElementValue(assertionElem, PERSON_GIVEN_NAME_XPATH, ""); - String familyname = XPathUtils.getElementValue(assertionElem, PERSON_FAMILY_NAME_XPATH, ""); + XPathUtils.getElementValue(assertionElem, PERSON_IDENT_VALUE_XPATH, "")); + identityLink.setIdentificationType( + XPathUtils.getElementValue(assertionElem, PERSON_IDENT_TYPE_XPATH, "")); + + final String givenname = + XPathUtils.getElementValue(assertionElem, PERSON_GIVEN_NAME_XPATH, ""); + final String familyname = + XPathUtils.getElementValue(assertionElem, PERSON_FAMILY_NAME_XPATH, ""); + + // replace ' in name with ' + // givenname = givenname.replaceAll("'", "'"); + // familyname = familyname.replaceAll("'", "'"); - // replace ' in name with ' -// givenname = givenname.replaceAll("'", "'"); -// familyname = familyname.replaceAll("'", "'"); - identityLink.setGivenName(givenname); identityLink.setFamilyName(familyname); identityLink.setDateOfBirth( - XPathUtils.getElementValue(assertionElem, PERSON_DATE_OF_BIRTH_XPATH, "")); - NodeIterator dsigRefTransforms = - XPathUtils.selectNodeIterator(assertionElem, DSIG_REFERENCE_TRANSFORMATION_XPATH); - List transElems = new ArrayList(); - Element transformsElem; - while ((transformsElem = (Element) dsigRefTransforms.nextNode()) != null) { - transElems.add(transformsElem); - } - Element[] result = new Element[transElems.size()]; - transElems.toArray(result); - identityLink.setDsigReferenceTransforms(result); - - //identityLink.setPublicKey(getPublicKeys()); - - } - catch (Throwable t) { - throw new EAAFParserException("parser.01", new Object[] { t.toString() }, t); + XPathUtils.getElementValue(assertionElem, PERSON_DATE_OF_BIRTH_XPATH, "")); + final NodeIterator dsigRefTransforms = + XPathUtils.selectNodeIterator(assertionElem, DSIG_REFERENCE_TRANSFORMATION_XPATH); + final List transElems = new ArrayList(); + Element transformsElem; + while ((transformsElem = (Element) dsigRefTransforms.nextNode()) != null) { + transElems.add(transformsElem); + } + final Element[] result = new Element[transElems.size()]; + transElems.toArray(result); + identityLink.setDsigReferenceTransforms(result); + + // identityLink.setPublicKey(getPublicKeys()); + + } catch (final Throwable t) { + throw new EaafParserException("parser.01", new Object[] {t.toString()}, t); } return identityLink; } /** - * Parses a string array of decoded base64 certificates from - * the <InfoboxReadResponse> found in the dsig-signature - * @return String[] with raw-certificates from the dsig-signature keyinfo - * @throws Exception - */ + * Parses a string array of decoded base64 certificates from the + * <InfoboxReadResponse> found in the dsig-signature + * + * @return String[] with raw-certificates from the dsig-signature keyinfo + * @throws Exception + */ public String[] getCertificates() throws Exception { - List certs = new ArrayList(); - NodeIterator rsaIter = - XPathUtils.selectNodeIterator(assertionElem, DSIG_CERTIFICATES_XPATH); + final List certs = new ArrayList(); + final NodeIterator rsaIter = + XPathUtils.selectNodeIterator(assertionElem, DSIG_CERTIFICATES_XPATH); Element certElem; while ((certElem = (Element) rsaIter.nextNode()) != null) { - String content = DOMUtils.getText(certElem); - certs.add(new String(Base64Utils.decodeFromString(content))); - + final String content = DomUtils.getText(certElem); + certs.add(new String(Base64Utils.decodeFromString(content), "UTF-8")); + } - String[] result = new String[certs.size()]; + final String[] result = new String[certs.size()]; certs.toArray(result); return result; diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/modules/AbstractAuthServletTask.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/modules/AbstractAuthServletTask.java index ce9ba57c..c785e1cb 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/modules/AbstractAuthServletTask.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/modules/AbstractAuthServletTask.java @@ -1,29 +1,22 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.auth.modules; import java.io.ByteArrayOutputStream; @@ -34,21 +27,8 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.fileupload.FileItem; -import org.apache.commons.fileupload.FileItemFactory; -import org.apache.commons.fileupload.FileUploadException; -import org.apache.commons.fileupload.disk.DiskFileItemFactory; -import org.apache.commons.fileupload.servlet.ServletFileUpload; -import org.apache.commons.lang3.ArrayUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.io.ResourceLoader; - import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.IRequestStorage; import at.gv.egiz.eaaf.core.api.data.EAAFConstants; @@ -56,216 +36,233 @@ import at.gv.egiz.eaaf.core.api.idp.IConfiguration; import at.gv.egiz.eaaf.core.api.idp.auth.services.IProtocolAuthenticationService; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; import at.gv.egiz.eaaf.core.api.logging.IRevisionLogger; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; import at.gv.egiz.eaaf.core.impl.idp.controller.ProtocolFinalizationController; import at.gv.egiz.eaaf.core.impl.idp.process.springweb.AbstractTask; -import at.gv.egiz.eaaf.core.impl.utils.DataURLBuilder; +import at.gv.egiz.eaaf.core.impl.utils.DataUrlBuilder; +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.FileItemFactory; +import org.apache.commons.fileupload.FileUploadException; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.fileupload.servlet.ServletFileUpload; +import org.apache.commons.lang3.ArrayUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ResourceLoader; /** - * Task based counterpart to {@link AuthServlet}, providing the same utility methods (error handling, parameter parsing - * etc.).

The code has been taken from {@link AuthServlet}. + * Task based counterpart to {@link AuthServlet}, providing the same utility methods (error + * handling, parameter parsing etc.). + *

+ * The code has been taken from {@link AuthServlet}. */ public abstract class AbstractAuthServletTask extends AbstractTask { - private static final Logger log = LoggerFactory.getLogger(AbstractAuthServletTask.class); - - @Autowired(required=true) IProtocolAuthenticationService protAuchService; - @Autowired(required=true) protected IRequestStorage requestStoreage; - @Autowired(required=true) protected IConfiguration authConfig; - @Autowired(required=true) protected ResourceLoader resourceLoader; - - @Autowired protected IRevisionLogger revisionsLogger; - - protected static final String ERROR_CODE_PARAM = "errorid"; - - protected IRequest pendingReq = null; - - @Override - public abstract void execute(ExecutionContext executionContext, HttpServletRequest request, - HttpServletResponse response) throws TaskExecutionException; - - - @Override - protected final IRequest internalExecute(IRequest pendingReq, ExecutionContext executionContext, HttpServletRequest request, - HttpServletResponse response) throws TaskExecutionException { - //set pending-request object - this.pendingReq = pendingReq; - - //add latest pendingRequestId on execution context - executionContext.put(EAAFConstants.PROCESS_ENGINE_PENDINGREQUESTID, pendingReq.getPendingRequestId()); - - //execute task specific action - execute(executionContext, request, response); - - //return pending-request object - return this.pendingReq; - } - - /** - * Redirect the authentication process to protocol specific finalization endpoint. - * @param executionContext - * - * @param pendingReq Actually processed protocol specific authentication request - * @param httpResp - * @throws IOException - * @throws EAAFException - */ - protected void performRedirectToProtocolFinialization(ExecutionContext executionContext, IRequest pendingReq, HttpServletRequest httpReq, HttpServletResponse httpResp) throws EAAFException, IOException { - final Object frontChannelRedirectFlagObj = executionContext.get(EAAFConstants.PROCESS_ENGINE_REQUIRES_NO_POSTAUTH_REDIRECT); - if (frontChannelRedirectFlagObj != null && frontChannelRedirectFlagObj instanceof Boolean && - (Boolean)frontChannelRedirectFlagObj) { - log.info("AuthProcess finished. Forward to Protocol finalization."); - protAuchService.finalizeAuthentication(httpReq, httpResp, pendingReq); - - } else { - log.info("AuthProcess finished. Redirect to Protocol Dispatcher."); - requestStoreage.storePendingRequest(pendingReq); - performRedirectToItself(pendingReq, httpResp, ProtocolFinalizationController.ENDPOINT_FINALIZEPROTOCOL); - - } - - - - } - - /** - * Redirect the authentication process to IDP itself - * - * @param pendingReq Actually processed protocol specific authentication request - * @param httpResp - * @param idpEndPoint Servlet EndPoint that should receive the redirect - */ - protected void performRedirectToItself(IRequest pendingReq, HttpServletResponse httpResp, String idpEndPoint) { - final String redirectURL = new DataURLBuilder().buildDataURL(pendingReq.getAuthURL(), - idpEndPoint, pendingReq.getPendingRequestId()); - - httpResp.setContentType("text/html"); - httpResp.setStatus(302); - httpResp.addHeader("Location", redirectURL); - log.debug("REDIRECT TO: " + redirectURL); - - } - - - /** - * Parses the request input stream for parameters, assuming parameters are - * encoded UTF-8 (no standard exists how browsers should encode them). - * - * @param req - * servlet request - * - * @return mapping parameter name -> value - * - * @throws IOException - * if parsing request parameters fails. - * - * @throws FileUploadException - * if parsing request parameters fails. - */ - protected Map getParameters(HttpServletRequest req) throws IOException, - FileUploadException { - - final Map parameters = new HashMap(); - - if (ServletFileUpload.isMultipartContent(req)) { - // request is encoded as mulitpart/form-data - final FileItemFactory factory = new DiskFileItemFactory(); - ServletFileUpload upload = null; - upload = new ServletFileUpload(factory); - List items = null; - items = upload.parseRequest(req); - for (int i = 0; i < items.size(); i++) { - final FileItem item = (FileItem) items.get(i); - if (item.isFormField()) { - // Process only form fields - no file upload items - parameters.put(item.getFieldName(), item.getString("UTF-8")); - - //log requests on trace - if (log.isTraceEnabled()) { - final String logString = item.getString("UTF-8"); - - // TODO use RegExp - final String startS = ""; - final String endS = "urn:publicid:gv.at:baseid"; - String logWithMaskedBaseid = logString; - final int start = logString.indexOf(startS); - if (start > -1) { - final int end = logString.indexOf(endS); - if (end > -1) { - logWithMaskedBaseid = logString.substring(0, start); - logWithMaskedBaseid += startS; - logWithMaskedBaseid += "xxxxxxxxxxxxxxxxxxxxxxxx"; - logWithMaskedBaseid += logString.substring(end, - logString.length()); - } - } - - log.debug("Processed multipart/form-data request parameter: \nName: " - + item.getFieldName() - + "\nValue: " - + logWithMaskedBaseid); - } - - } - } - } - - else { - final Iterator> requestParamIt = req.getParameterMap().entrySet().iterator(); - while (requestParamIt.hasNext()) { - final Entry entry = requestParamIt.next(); - final String key = entry.getKey(); - final String[] values = entry.getValue(); - // take the last value from the value array since the legacy code above also does it this way - parameters.put(key, ArrayUtils.isEmpty(values) ? null : values[values.length-1]); - } - - } - - return parameters; - } - - /** - * Reads bytes up to a delimiter, consuming the delimiter. - * - * @param in - * input stream - * @param delimiter - * delimiter character - * @return String constructed from the read bytes - * @throws IOException - */ - protected String readBytesUpTo(InputStream in, char delimiter) - throws IOException { - final ByteArrayOutputStream bout = new ByteArrayOutputStream(); - boolean done = false; - int b; - while (!done && (b = in.read()) >= 0) { - if (b == delimiter) - done = true; - else - bout.write(b); - } - return bout.toString(); - } - - /** - * Adds a parameter to a URL. - * - * @param url - * the URL - * @param paramname - * parameter name - * @param paramvalue - * parameter value - * @return the URL with parameter added - */ - protected static String addURLParameter(String url, String paramname, - String paramvalue) { - final String param = paramname + "=" + paramvalue; - if (url.indexOf("?") < 0) - return url + "?" + param; - else - return url + "&" + param; - } + private static final Logger log = LoggerFactory.getLogger(AbstractAuthServletTask.class); + + @Autowired(required = true) + IProtocolAuthenticationService protAuchService; + @Autowired(required = true) + protected IRequestStorage requestStoreage; + @Autowired(required = true) + protected IConfiguration authConfig; + @Autowired(required = true) + protected ResourceLoader resourceLoader; + + @Autowired + protected IRevisionLogger revisionsLogger; + + protected static final String ERROR_CODE_PARAM = "errorid"; + + protected IRequest pendingReq = null; + + @Override + public abstract void execute(ExecutionContext executionContext, HttpServletRequest request, + HttpServletResponse response) throws TaskExecutionException; + + + @Override + protected final IRequest internalExecute(final IRequest pendingReq, + final ExecutionContext executionContext, final HttpServletRequest request, + final HttpServletResponse response) throws TaskExecutionException { + // set pending-request object + this.pendingReq = pendingReq; + + // add latest pendingRequestId on execution context + executionContext.put(EAAFConstants.PROCESS_ENGINE_PENDINGREQUESTID, + pendingReq.getPendingRequestId()); + + // execute task specific action + execute(executionContext, request, response); + + // return pending-request object + return this.pendingReq; + } + + /** + * Redirect the authentication process to protocol specific finalization endpoint. + * + * @param executionContext + * + * @param pendingReq Actually processed protocol specific authentication request + * @param httpResp http response object + * @throws IOException In case of a general error + * @throws EaafException In case of an application error + */ + protected void performRedirectToProtocolFinialization(final ExecutionContext executionContext, + final IRequest pendingReq, final HttpServletRequest httpReq, + final HttpServletResponse httpResp) throws EaafException, IOException { + final Object frontChannelRedirectFlagObj = + executionContext.get(EAAFConstants.PROCESS_ENGINE_REQUIRES_NO_POSTAUTH_REDIRECT); + if (frontChannelRedirectFlagObj != null && frontChannelRedirectFlagObj instanceof Boolean + && (Boolean) frontChannelRedirectFlagObj) { + log.info("AuthProcess finished. Forward to Protocol finalization."); + protAuchService.finalizeAuthentication(httpReq, httpResp, pendingReq); + + } else { + log.info("AuthProcess finished. Redirect to Protocol Dispatcher."); + requestStoreage.storePendingRequest(pendingReq); + performRedirectToItself(pendingReq, httpResp, + ProtocolFinalizationController.ENDPOINT_FINALIZEPROTOCOL); + + } + + + + } + + /** + * Redirect the authentication process to IDP itself. + * + * @param pendingReq Actually processed protocol specific authentication request + * @param httpResp http response + * @param idpEndPoint Servlet EndPoint that should receive the redirect + */ + protected void performRedirectToItself(final IRequest pendingReq, + final HttpServletResponse httpResp, final String idpEndPoint) { + final String redirectUrl = new DataUrlBuilder().buildDataUrl(pendingReq.getAuthUrl(), + idpEndPoint, pendingReq.getPendingRequestId()); + + httpResp.setContentType("text/html"); + httpResp.setStatus(302); + httpResp.addHeader("Location", redirectUrl); + log.debug("REDIRECT TO: " + redirectUrl); + + } + + + /** + * Parses the request input stream for parameters, assuming parameters are encoded UTF-8 (no + * standard exists how browsers should encode them). + * + * @param req servlet request + * + * @return mapping parameter name -> value + * + * @throws IOException if parsing request parameters fails. + * + * @throws FileUploadException if parsing request parameters fails. + */ + protected Map getParameters(final HttpServletRequest req) + throws IOException, FileUploadException { + + final Map parameters = new HashMap<>(); + + if (ServletFileUpload.isMultipartContent(req)) { + // request is encoded as mulitpart/form-data + final FileItemFactory factory = new DiskFileItemFactory(); + ServletFileUpload upload = null; + upload = new ServletFileUpload(factory); + List items = null; + items = upload.parseRequest(req); + for (int i = 0; i < items.size(); i++) { + final FileItem item = (FileItem) items.get(i); + if (item.isFormField()) { + // Process only form fields - no file upload items + parameters.put(item.getFieldName(), item.getString("UTF-8")); + + // log requests on trace + if (log.isTraceEnabled()) { + final String logString = item.getString("UTF-8"); + + // TODO use RegExp + final String startS = ""; + final String endS = "urn:publicid:gv.at:baseid"; + String logWithMaskedBaseid = logString; + final int start = logString.indexOf(startS); + if (start > -1) { + final int end = logString.indexOf(endS); + if (end > -1) { + logWithMaskedBaseid = logString.substring(0, start); + logWithMaskedBaseid += startS; + logWithMaskedBaseid += "xxxxxxxxxxxxxxxxxxxxxxxx"; + logWithMaskedBaseid += logString.substring(end, logString.length()); + } + } + + log.debug("Processed multipart/form-data request parameter: \nName: " + + item.getFieldName() + "\nValue: " + logWithMaskedBaseid); + } + + } + } + + } else { + final Iterator> requestParamIt = + req.getParameterMap().entrySet().iterator(); + while (requestParamIt.hasNext()) { + final Entry entry = requestParamIt.next(); + final String key = entry.getKey(); + final String[] values = entry.getValue(); + // take the last value from the value array since the legacy code above also does it this + // way + parameters.put(key, ArrayUtils.isEmpty(values) ? null : values[values.length - 1]); + } + + } + + return parameters; + } + + /** + * Reads bytes up to a delimiter, consuming the delimiter. + * + * @param in input stream + * @param delimiter delimiter character + * @return String constructed from the read bytes + * @throws IOException In case of a general error + */ + protected String readBytesUpTo(final InputStream in, final char delimiter) throws IOException { + final ByteArrayOutputStream bout = new ByteArrayOutputStream(); + boolean done = false; + int b; + while (!done && (b = in.read()) >= 0) { + if (b == delimiter) { + done = true; + } else { + bout.write(b); + } + } + return bout.toString("UTF-8"); + + } + + /** + * Adds a parameter to a URL. + * + * @param url the URL + * @param paramname parameter name + * @param paramvalue parameter value + * @return the URL with parameter added + */ + protected static String addUrlParameter(final String url, final String paramname, + final String paramvalue) { + final String param = paramname + "=" + paramvalue; + if (url.indexOf("?") < 0) { + return url + "?" + param; + } else { + return url + "&" + param; + } + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/modules/ModuleRegistration.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/modules/ModuleRegistration.java index 6789c802..b04b000e 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/modules/ModuleRegistration.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/modules/ModuleRegistration.java @@ -1,43 +1,38 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.auth.modules; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; -import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.ServiceLoader; - import javax.annotation.PostConstruct; - +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.idp.auth.modules.AuthModule; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.api.idp.process.ProcessEngine; +import at.gv.egiz.eaaf.core.impl.idp.process.ProcessDefinitionParserException; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -45,135 +40,124 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.core.io.Resource; -import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.core.api.idp.auth.modules.AuthModule; -import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; -import at.gv.egiz.eaaf.core.api.idp.process.ProcessEngine; -import at.gv.egiz.eaaf.core.impl.idp.process.ProcessDefinitionParserException; - /** - * This class handles registering modules. The modules are detected either with - * the ServiceLoader mechanism or via Spring. All detected modules are ranked - * according to their priority. + * This class handles registering modules. The modules are detected either with the ServiceLoader + * mechanism or via Spring. All detected modules are ranked according to their priority. */ public class ModuleRegistration { - private static ModuleRegistration instance = new ModuleRegistration(); - - private final List priorizedModules = new ArrayList<>(); - - @Autowired - private ApplicationContext ctx; - - @Autowired - private ProcessEngine processEngine; - - private final Logger log = LoggerFactory.getLogger(getClass()); - - public static ModuleRegistration getInstance() { - return instance; - } - - private ModuleRegistration() { - } - - @PostConstruct - private void init() { - // load modules via the ServiceLoader - initServiceLoaderModules(); - - // load modules via Spring - initSpringModules(); - - // order modules according to their priority - sortModules(); - - instance = this; - } - - /** - * Discovers modules which use the ServiceLoader mechanism. - */ - private void initServiceLoaderModules() { - log.info("Looking for auth modules."); - final ServiceLoader loader = ServiceLoader.load(AuthModule.class); - final Iterator modules = loader.iterator(); - while (modules.hasNext()) { - final AuthModule module = modules.next(); - log.info("Detected module {}", module.getClass().getName()); - registerModuleProcessDefinitions(module); - priorizedModules.add(module); - } - } - - /** - * Discovers modules which use Spring. - */ - private void initSpringModules() { - log.debug("Discovering Spring modules."); - final Map modules = ctx.getBeansOfType(AuthModule.class); - for (final AuthModule module : modules.values()) { - registerModuleProcessDefinitions(module); - priorizedModules.add(module); - } - } - - /** - * Registers the resource uris for the module. - * - * @param module - * the module. - */ - private void registerModuleProcessDefinitions(AuthModule module) { - for (final String uri : module.getProcessDefinitions()) { - final Resource resource = ctx.getResource(uri); - if (resource.isReadable()) { - log.info("Registering process definition '{}'.", uri); - try (InputStream processDefinitionInputStream = resource.getInputStream()) { - processEngine.registerProcessDefinition(processDefinitionInputStream); - } catch (final IOException e) { - log.error("Process definition '{}' could NOT be read.", uri, e); - } catch (final ProcessDefinitionParserException e) { - log.error("Error while parsing process definition '{}'", uri, e); - } - } else { - log.error("Process definition '{}' cannot be read.", uri); - } - } - } - - /** - * Order the modules in descending order according to their priority. - */ - private void sortModules() { - Collections.sort(priorizedModules, new Comparator() { - @Override - public int compare(AuthModule thisAuthModule, AuthModule otherAuthModule) { - final int thisOrder = thisAuthModule.getPriority(); - final int otherOrder = otherAuthModule.getPriority(); - return (thisOrder < otherOrder ? 1 : (thisOrder == otherOrder ? 0 : -1)); - } - }); - } - - /** - * Returns the process description id of the first process, in the highest ranked - * module, which is able to work with the given execution context. - * - * @param context - * the {@link ExecutionContext}. - * @param pendingReq the current processed {@link IRequest} - * @return the process id or {@code null} - */ - public String selectProcess(ExecutionContext context, IRequest pendingReq) { - for (final AuthModule module : priorizedModules) { - final String id = module.selectProcess(context, pendingReq); - if (StringUtils.isNotEmpty(id)) { - log.debug("Process with id '{}' selected, for context '{}'.", id, context); - return id; - } - } - log.info("No process is able to handle context '{}'.", context); - return null; - } + //private static ModuleRegistration instance = new ModuleRegistration(); + + private final List priorizedModules = new ArrayList<>(); + + @Autowired + private ApplicationContext ctx; + + @Autowired + private ProcessEngine processEngine; + + private final Logger log = LoggerFactory.getLogger(getClass()); + +// public static ModuleRegistration getInstance() { +// return ctx.; +// } + + private ModuleRegistration() { + + } + + @PostConstruct + private void init() { + // load modules via the ServiceLoader + initServiceLoaderModules(); + + // load modules via Spring + initSpringModules(); + + // order modules according to their priority + sortModules(); + + //instance = this; + } + + /** + * Discovers modules which use the ServiceLoader mechanism. + */ + private void initServiceLoaderModules() { + log.info("Looking for auth modules."); + final ServiceLoader loader = ServiceLoader.load(AuthModule.class); + final Iterator modules = loader.iterator(); + while (modules.hasNext()) { + final AuthModule module = modules.next(); + log.info("Detected module {}", module.getClass().getName()); + registerModuleProcessDefinitions(module); + priorizedModules.add(module); + } + } + + /** + * Discovers modules which use Spring. + */ + private void initSpringModules() { + log.debug("Discovering Spring modules."); + final Map modules = ctx.getBeansOfType(AuthModule.class); + for (final AuthModule module : modules.values()) { + registerModuleProcessDefinitions(module); + priorizedModules.add(module); + } + } + + /** + * Registers the resource uris for the module. + * + * @param module the module. + */ + private void registerModuleProcessDefinitions(final AuthModule module) { + for (final String uri : module.getProcessDefinitions()) { + final Resource resource = ctx.getResource(uri); + if (resource.isReadable()) { + log.info("Registering process definition '{}'.", uri); + try (InputStream processDefinitionInputStream = resource.getInputStream()) { + processEngine.registerProcessDefinition(processDefinitionInputStream); + } catch (final IOException e) { + log.error("Process definition '{}' could NOT be read.", uri, e); + } catch (final ProcessDefinitionParserException e) { + log.error("Error while parsing process definition '{}'", uri, e); + } + } else { + log.error("Process definition '{}' cannot be read.", uri); + } + } + } + + /** + * Order the modules in descending order according to their priority. + */ + private void sortModules() { + Collections.sort(priorizedModules, (thisAuthModule, otherAuthModule) -> { + final int thisOrder = thisAuthModule.getPriority(); + final int otherOrder = otherAuthModule.getPriority(); + return (thisOrder < otherOrder ? 1 : (thisOrder == otherOrder ? 0 : -1)); + }); + } + + /** + * Returns the process description id of the first process, in the highest ranked module, which is + * able to work with the given execution context. + * + * @param context the {@link ExecutionContext}. + * @param pendingReq the current processed {@link IRequest} + * @return the process id or {@code null} + */ + public String selectProcess(final ExecutionContext context, final IRequest pendingReq) { + for (final AuthModule module : priorizedModules) { + final String id = module.selectProcess(context, pendingReq); + if (StringUtils.isNotEmpty(id)) { + log.debug("Process with id '{}' selected, for context '{}'.", id, context); + return id; + } + } + log.info("No process is able to handle context '{}'.", context); + return null; + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java index 2edf8a75..a5030851 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/auth/services/ProtocolAuthenticationService.java @@ -1,25 +1,22 @@ -/******************************************************************************* - * Copyright 2019 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2019 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.auth.services; import java.io.IOException; @@ -27,499 +24,518 @@ import java.io.PrintWriter; import java.io.StringWriter; import java.util.Arrays; import java.util.List; - import javax.naming.ConfigurationException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.text.StringEscapeUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.lang.NonNull; -import org.springframework.lang.Nullable; -import org.springframework.stereotype.Service; - import at.gv.egiz.components.eventlog.api.EventConstants; import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.IRequestStorage; import at.gv.egiz.eaaf.core.api.IStatusMessenger; import at.gv.egiz.eaaf.core.api.data.EAAFConstants; -import at.gv.egiz.eaaf.core.api.gui.IGUIBuilderConfiguration; -import at.gv.egiz.eaaf.core.api.gui.IGUIBuilderConfigurationFactory; -import at.gv.egiz.eaaf.core.api.gui.IGUIFormBuilder; +import at.gv.egiz.eaaf.core.api.gui.IGuiBuilderConfiguration; +import at.gv.egiz.eaaf.core.api.gui.IGuiBuilderConfigurationFactory; +import at.gv.egiz.eaaf.core.api.gui.IGuiFormBuilder; import at.gv.egiz.eaaf.core.api.gui.ModifyableGuiBuilderConfiguration; import at.gv.egiz.eaaf.core.api.idp.IAction; import at.gv.egiz.eaaf.core.api.idp.IAuthData; import at.gv.egiz.eaaf.core.api.idp.IAuthenticationDataBuilder; import at.gv.egiz.eaaf.core.api.idp.IModulInfo; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; import at.gv.egiz.eaaf.core.api.idp.auth.IAuthenticationManager; -import at.gv.egiz.eaaf.core.api.idp.auth.ISSOManager; +import at.gv.egiz.eaaf.core.api.idp.auth.ISsoManager; import at.gv.egiz.eaaf.core.api.idp.auth.services.IProtocolAuthenticationService; -import at.gv.egiz.eaaf.core.api.idp.slo.SLOInformationInterface; +import at.gv.egiz.eaaf.core.api.idp.slo.SloInformationInterface; import at.gv.egiz.eaaf.core.api.logging.IRevisionLogger; import at.gv.egiz.eaaf.core.api.logging.IStatisticLogger; import at.gv.egiz.eaaf.core.api.utils.IPendingRequestIdGenerationStrategy; import at.gv.egiz.eaaf.core.exceptions.AuthnRequestValidatorException; -import at.gv.egiz.eaaf.core.exceptions.EAAFAuthenticationException; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.core.exceptions.EAAFSSOException; -import at.gv.egiz.eaaf.core.exceptions.GUIBuildException; +import at.gv.egiz.eaaf.core.exceptions.EaafAuthenticationException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.exceptions.EaafSsoException; +import at.gv.egiz.eaaf.core.exceptions.GuiBuildException; import at.gv.egiz.eaaf.core.exceptions.InvalidProtocolRequestException; import at.gv.egiz.eaaf.core.exceptions.ProcessExecutionException; import at.gv.egiz.eaaf.core.exceptions.ProtocolNotActiveException; -import at.gv.egiz.eaaf.core.impl.gui.AbstractGUIFormBuilderConfiguration; +import at.gv.egiz.eaaf.core.impl.gui.AbstractGuiFormBuilderConfiguration; import at.gv.egiz.eaaf.core.impl.idp.controller.protocols.RequestImpl; -import at.gv.egiz.eaaf.core.impl.utils.HTTPUtils; +import at.gv.egiz.eaaf.core.impl.utils.HttpUtils; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.text.StringEscapeUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.lang.NonNull; +import org.springframework.lang.Nullable; +import org.springframework.stereotype.Service; @Service public class ProtocolAuthenticationService implements IProtocolAuthenticationService { - private static final Logger log = LoggerFactory.getLogger(ProtocolAuthenticationService.class); - - private static final List ERROR_LOGGER_ON_INFO_LEVEL = - Arrays.asList( - IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_USERSTOP - ); - - @Autowired(required=true) private ApplicationContext applicationContext; - @Autowired(required=true) private IAuthenticationManager authmanager; - @Autowired(required=true) private IAuthenticationDataBuilder authDataBuilder; - @Autowired(required=true) private IGUIBuilderConfigurationFactory guiConfigFactory; - @Autowired(required=true) private IStatusMessenger statusMessager; - @Autowired(required=true) private IRequestStorage requestStorage; - @Autowired(required=true) IPendingRequestIdGenerationStrategy pendingReqIdGenerationStrategy; - - @Autowired(required=false) private ISSOManager ssoManager; - @Autowired private IStatisticLogger statisticLogger; - @Autowired private IRevisionLogger revisionsLogger; - - - private IGUIFormBuilder guiBuilder; - - /* (non-Javadoc) - * @see at.gv.egiz.eaaf.core.impl.idp.auth.services.IProtocolAuthenticationService#performAuthentication(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, at.gv.egiz.eaaf.core.api.IRequest) - */ - @Override - public void performAuthentication(final HttpServletRequest req, final HttpServletResponse resp, - final IRequest pendingReq) throws IOException, EAAFException { - try { - if (pendingReq.isNeedAuthentication()) { - //request needs authentication --> start authentication process ... - - //set pendingRequestId to support asynchrony message-processing - ((RequestImpl)pendingReq).setPendingRequestId(pendingReqIdGenerationStrategy.generateExternalPendingRequestId()); - - //load Parameters from OnlineApplicationConfiguration - final ISPConfiguration oaParam = pendingReq.getServiceProviderConfiguration(); - - if (oaParam == null) - throw new EAAFAuthenticationException( - IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_NOSPCONFIG, - new Object[] { pendingReq.getSPEntityId() }); - - if (authmanager.doAuthentication(req, resp, pendingReq)) { - //pending request is already authenticated --> protocol-specific postProcessing can start directly - finalizeAuthentication(req, resp, pendingReq); - - //transaction is finished, log transaction finished event - revisionsLogger.logEvent(EventConstants.TRANSACTION_DESTROYED, pendingReq.getUniqueTransactionIdentifier()); - - } - - } else { - executeProtocolSpecificAction(req, resp, pendingReq, null); - - } - - } catch (final Exception e) { - buildProtocolSpecificErrorResponse(e, req, resp, pendingReq); - authmanager.performOnlyIDPLogOut(req, resp, pendingReq); - - } - } - - /* (non-Javadoc) - * @see at.gv.egiz.eaaf.core.impl.idp.auth.services.IProtocolAuthenticationService#finalizeAuthentication(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, at.gv.egiz.eaaf.core.api.IRequest) - */ - @Override - public void finalizeAuthentication(final HttpServletRequest req, final HttpServletResponse resp, final IRequest pendingReq) throws EAAFException, IOException{ - log.debug("Finalize PendingRequest with ID " + pendingReq.getPendingRequestId()); - try { - - //check if pending-request has 'abortedByUser' flag set - if (pendingReq.isAbortedByUser()) { - //send authentication aborted error to Service Provider - buildProtocolSpecificErrorResponse( - new EAAFAuthenticationException( - IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_USERSTOP, - new Object[] {}), - req, resp, pendingReq); - - //do not remove the full active SSO-Session - // in case of only one Service-Provider authentication request is aborted - if ( !pendingReq.needSingleSignOnFunctionality()) { - requestStorage.removePendingRequest(pendingReq.getPendingRequestId()); - - } - - //check if pending-request are authenticated - } else if (pendingReq.isAuthenticated() && !pendingReq.isNeedUserConsent()) { - internalFinalizeAuthenticationProcess(req, resp, pendingReq); - - } else { - //suspect state: pending-request is not aborted but also are not authenticated - log.warn("PendingRequest flag for 'authenticated':{} and 'needConsent':{}", pendingReq.isAuthenticated(), pendingReq.isNeedUserConsent()); - if (pendingReq.isNeedUserConsent()) { - log.error("PendingRequest NEEDS user-consent. Can NOT fininalize authentication --> Abort authentication process!"); - - } else { - log.error("PendingRequest is NOT authenticated --> Abort authentication process!"); - - } - - handleErrorNoRedirect( - new EAAFException( - "auth.20", - null), req, resp, true); - - } - - } catch (final Exception e) { - log.error("Finalize authentication protocol FAILED." , e); - buildProtocolSpecificErrorResponse(e, req, resp, pendingReq); - - } - - //remove pending-request - if (pendingReq != null) { - requestStorage.removePendingRequest(pendingReq.getPendingRequestId()); - revisionsLogger.logEvent(EventConstants.TRANSACTION_DESTROYED, pendingReq.getUniqueTransactionIdentifier()); - - } - } - - - @Override - public void buildProtocolSpecificErrorResponse(final Throwable throwable, final HttpServletRequest req, - final HttpServletResponse resp, final IRequest protocolRequest) throws EAAFException, IOException { - try { - - final Class clazz = Class.forName(protocolRequest.requestedModule()); - - if (clazz == null || - !IModulInfo.class.isAssignableFrom(clazz)) { - log.error("Requested protocol module Class is NULL or does not implement the IModulInfo interface."); - throw new Exception("Requested protocol module Class is NULL or does not implement the IModulInfo interface."); - - } - - final IModulInfo handlingModule = (IModulInfo) applicationContext.getBean(clazz); - - if (handlingModule.generateErrorMessage( - throwable, req, resp, protocolRequest)) { - - //log Error to technical log - logExceptionToTechnicalLog(throwable); - - //log Error Message - statisticLogger.logErrorOperation(throwable, protocolRequest); - - //write revision log entries - revisionsLogger.logEvent(protocolRequest, EventConstants.TRANSACTION_ERROR, protocolRequest.getUniqueTransactionIdentifier()); - - return; - - } else { - handleErrorNoRedirect(throwable, req, resp, true); - - } - - } catch (final Throwable e) { - handleErrorNoRedirect(throwable, req, resp, true); - - } - - } - - @Override - public void handleErrorNoRedirect(final Throwable throwable, final HttpServletRequest req, - final HttpServletResponse resp, final boolean writeExceptionToStatisticLog) throws IOException, EAAFException { - - //log Exception into statistic database - if (writeExceptionToStatisticLog) - statisticLogger.logErrorOperation(throwable); - - //write errror to console - logExceptionToTechnicalLog(throwable); - - //return error to Web browser - if (throwable instanceof EAAFException || throwable instanceof ProcessExecutionException) - internalMOAIDExceptionHandler(req, resp, (Exception)throwable, false); - - else { - //write generic message for general exceptions - final String msg = statusMessager.getMessage(IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, null); - writeHTMLErrorResponse(req, resp, msg, "9199", null, (Exception) throwable); - - } - - } - - - public void setGuiBuilder(IGUIFormBuilder guiBuilder) { - this.guiBuilder = guiBuilder; - } - - /** - * Finalize the requested protocol operation - * - * @param httpReq HttpServletRequest - * @param httpResp HttpServletResponse - * @param protocolRequest Authentication request which is actually in process - * @param moaSession MOASession object, which is used to generate the protocol specific authentication information - * @throws Exception - */ - protected void internalFinalizeAuthenticationProcess(final HttpServletRequest req, final HttpServletResponse resp, - final IRequest pendingReq) throws Exception { - - String newSSOSessionId = null; - - //if Single Sign-On functionality is enabled for this request - if (pendingReq.needSingleSignOnFunctionality()) { - if (ssoManager != null) { - newSSOSessionId = ssoManager.createNewSSOSessionCookie(req, resp, pendingReq); - if (StringUtils.isEmpty(pendingReq.getInternalSSOSessionIdentifier())) - ssoManager.createNewSSOSession(pendingReq, newSSOSessionId); - - } else - log.warn("SSO is requested but there is not SSO Session-Manager available"); - - } - - //build authenticationdata from session information and OA configuration - final IAuthData authData = authDataBuilder.buildAuthenticationData(pendingReq); - - //execute the protocol-specific action - final SLOInformationInterface sloInformation = executeProtocolSpecificAction(req, resp, pendingReq, authData); - - //Store OA specific SSO session information if an SSO cookie is set - if (StringUtils.isNotEmpty(newSSOSessionId)) { - try { - ssoManager.updateSSOSession(pendingReq, newSSOSessionId, sloInformation); - - } catch (final EAAFSSOException e) { - log.warn("SSO Session information can not be stored -> SSO is not enabled!"); - authmanager.performOnlyIDPLogOut(req, resp, pendingReq); - - } - - } else { - //remove MOASession from database - authmanager.performOnlyIDPLogOut(req, resp, pendingReq); - - } - - //Advanced statistic logging - statisticLogger.logSuccessOperation(pendingReq, authData, StringUtils.isNotEmpty(newSSOSessionId)); - - } - - /** - * Executes the requested protocol action - * - * @param httpReq HttpServletRequest - * @param httpResp HttpServletResponse - * @param protocolRequest Authentication request which is actually in process - * @param authData Service-provider specific authentication data - * - * @return Return Single LogOut information or null if protocol supports no SSO - * - * @throws Exception - */ - private SLOInformationInterface executeProtocolSpecificAction(final HttpServletRequest httpReq, final HttpServletResponse httpResp, - final IRequest pendingReq, final IAuthData authData) throws Exception { - try { - // request needs no authentication --> start request processing - final Class clazz = Class.forName(pendingReq.requestedAction()); - if (clazz == null || - !IAction.class.isAssignableFrom(clazz)) { - log.error("Requested protocol-action processing Class is NULL or does not implement the IAction interface."); - throw new Exception("Requested protocol-action processing Class is NULL or does not implement the IAction interface."); - - } - - final IAction protocolAction = (IAction) applicationContext.getBean(clazz); - return protocolAction.processRequest(pendingReq, httpReq, httpResp, authData); - - } catch (final ClassNotFoundException e) { - log.error("Requested Auth. protocol processing Class is NULL or does not implement the IAction interface."); - throw new Exception("Requested Auth. protocol processing Class is NULL or does not implement the IAction interface."); - } - - } - - /** - * Write a Exception to the MOA-ID-Auth internal technical log - * - * @param loggedException Exception to log - */ - protected void logExceptionToTechnicalLog(final Throwable loggedException) { - if (!( loggedException instanceof EAAFException - || loggedException instanceof ProcessExecutionException )) { - log.error("Receive an internal error: Message=" + loggedException.getMessage(), loggedException); - - } else { - if (loggedException instanceof EAAFAuthenticationException && - ERROR_LOGGER_ON_INFO_LEVEL.contains( - ((EAAFAuthenticationException) loggedException).getErrorId())) { - if (log.isDebugEnabled() || log.isTraceEnabled()) { - log.info(loggedException.getMessage(), loggedException); - - } else { - log.info(loggedException.getMessage()); - - } - - } else { - if (log.isDebugEnabled() || log.isTraceEnabled()) { - log.warn(loggedException.getMessage(), loggedException); - - } else { - log.warn(loggedException.getMessage()); - - } - } - } - } - - private void writeHTMLErrorResponse(@NonNull final HttpServletRequest httpReq, @NonNull final HttpServletResponse httpResp, - @NonNull final String msg, @NonNull final String errorCode, @Nullable final Object[] params, @NonNull final Exception error) throws IOException, EAAFException { - - try { - final IGUIBuilderConfiguration config - = guiConfigFactory.getDefaultErrorGUI(HTTPUtils.extractAuthURLFromRequest(httpReq)); - - - String[] errorCodeParams = null; - if (params == null) - errorCodeParams = new String[] {}; - else { - errorCodeParams = new String[params.length]; - for (int i=0; i ERROR_LOGGER_ON_INFO_LEVEL = + Arrays.asList(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_USERSTOP); + + @Autowired(required = true) + private ApplicationContext applicationContext; + @Autowired(required = true) + private IAuthenticationManager authmanager; + @Autowired(required = true) + private IAuthenticationDataBuilder authDataBuilder; + @Autowired(required = true) + private IGuiBuilderConfigurationFactory guiConfigFactory; + @Autowired(required = true) + private IStatusMessenger statusMessager; + @Autowired(required = true) + private IRequestStorage requestStorage; + @Autowired(required = true) + IPendingRequestIdGenerationStrategy pendingReqIdGenerationStrategy; + + @Autowired(required = false) + private ISsoManager ssoManager; + @Autowired + private IStatisticLogger statisticLogger; + @Autowired + private IRevisionLogger revisionsLogger; + + + private IGuiFormBuilder guiBuilder; + + /* + * (non-Javadoc) + * + * @see at.gv.egiz.eaaf.core.impl.idp.auth.services.IProtocolAuthenticationService# + * performAuthentication(javax.servlet.http.HttpServletRequest, + * javax.servlet.http.HttpServletResponse, at.gv.egiz.eaaf.core.api.IRequest) + */ + @Override + public void performAuthentication(final HttpServletRequest req, final HttpServletResponse resp, + final IRequest pendingReq) throws IOException, EaafException { + try { + if (pendingReq.isNeedAuthentication()) { + // request needs authentication --> start authentication process ... + + // set pendingRequestId to support asynchrony message-processing + ((RequestImpl) pendingReq) + .setPendingRequestId(pendingReqIdGenerationStrategy.generateExternalPendingRequestId()); + + // load Parameters from OnlineApplicationConfiguration + final IspConfiguration oaParam = pendingReq.getServiceProviderConfiguration(); + + if (oaParam == null) { + throw new EaafAuthenticationException( + IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_NOSPCONFIG, + new Object[] {pendingReq.getSpEntityId()}); + } + + if (authmanager.doAuthentication(req, resp, pendingReq)) { + // pending request is already authenticated --> protocol-specific postProcessing can start + // directly + finalizeAuthentication(req, resp, pendingReq); + + // transaction is finished, log transaction finished event + revisionsLogger.logEvent(EventConstants.TRANSACTION_DESTROYED, + pendingReq.getUniqueTransactionIdentifier()); + + } + + } else { + executeProtocolSpecificAction(req, resp, pendingReq, null); + + } + + } catch (final Exception e) { + buildProtocolSpecificErrorResponse(e, req, resp, pendingReq); + authmanager.performOnlyIdpLogOut(req, resp, pendingReq); + + } + } + + /* + * (non-Javadoc) + * + * @see at.gv.egiz.eaaf.core.impl.idp.auth.services.IProtocolAuthenticationService# + * finalizeAuthentication(javax.servlet.http.HttpServletRequest, + * javax.servlet.http.HttpServletResponse, at.gv.egiz.eaaf.core.api.IRequest) + */ + @Override + public void finalizeAuthentication(final HttpServletRequest req, final HttpServletResponse resp, + final IRequest pendingReq) throws EaafException, IOException { + log.debug("Finalize PendingRequest with ID " + pendingReq.getPendingRequestId()); + try { + + // check if pending-request has 'abortedByUser' flag set + if (pendingReq.isAbortedByUser()) { + // send authentication aborted error to Service Provider + buildProtocolSpecificErrorResponse( + new EaafAuthenticationException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_USERSTOP, + new Object[] {}), + req, resp, pendingReq); + + // do not remove the full active SSO-Session + // in case of only one Service-Provider authentication request is aborted + if (!pendingReq.needSingleSignOnFunctionality()) { + requestStorage.removePendingRequest(pendingReq.getPendingRequestId()); + + } + + // check if pending-request are authenticated + } else if (pendingReq.isAuthenticated() && !pendingReq.isNeedUserConsent()) { + internalFinalizeAuthenticationProcess(req, resp, pendingReq); + + } else { + // suspect state: pending-request is not aborted but also are not authenticated + log.warn("PendingRequest flag for 'authenticated':{} and 'needConsent':{}", + pendingReq.isAuthenticated(), pendingReq.isNeedUserConsent()); + if (pendingReq.isNeedUserConsent()) { + log.error( + "PendingRequest NEEDS user-consent. Can NOT fininalize authentication --> Abort authentication process!"); + + } else { + log.error("PendingRequest is NOT authenticated --> Abort authentication process!"); + + } + + handleErrorNoRedirect(new EaafException("auth.20", null), req, resp, true); + + } + + } catch (final Exception e) { + log.error("Finalize authentication protocol FAILED.", e); + buildProtocolSpecificErrorResponse(e, req, resp, pendingReq); + + } + + // remove pending-request + requestStorage.removePendingRequest(pendingReq.getPendingRequestId()); + revisionsLogger.logEvent(EventConstants.TRANSACTION_DESTROYED, + pendingReq.getUniqueTransactionIdentifier()); + + } + + + @Override + public void buildProtocolSpecificErrorResponse(final Throwable throwable, + final HttpServletRequest req, final HttpServletResponse resp, final IRequest protocolRequest) + throws EaafException, IOException { + try { + + final Class clazz = Class.forName(protocolRequest.requestedModule()); + + if (clazz == null || !IModulInfo.class.isAssignableFrom(clazz)) { + log.error( + "Requested protocol module Class is NULL or does not implement the IModulInfo interface."); + throw new Exception( + "Requested protocol module Class is NULL or does not implement the IModulInfo interface."); + + } + + final IModulInfo handlingModule = (IModulInfo) applicationContext.getBean(clazz); + + if (handlingModule.generateErrorMessage(throwable, req, resp, protocolRequest)) { + + // log Error to technical log + logExceptionToTechnicalLog(throwable); + + // log Error Message + statisticLogger.logErrorOperation(throwable, protocolRequest); + + // write revision log entries + revisionsLogger.logEvent(protocolRequest, EventConstants.TRANSACTION_ERROR, + protocolRequest.getUniqueTransactionIdentifier()); + + return; + + } else { + handleErrorNoRedirect(throwable, req, resp, true); + + } + + } catch (final Throwable e) { + handleErrorNoRedirect(throwable, req, resp, true); + + } + + } + + @Override + public void handleErrorNoRedirect(final Throwable throwable, final HttpServletRequest req, + final HttpServletResponse resp, final boolean writeExceptionToStatisticLog) + throws IOException, EaafException { + + // log Exception into statistic database + if (writeExceptionToStatisticLog) { + statisticLogger.logErrorOperation(throwable); + } + + // write errror to console + logExceptionToTechnicalLog(throwable); + + // return error to Web browser + if (throwable instanceof EaafException || throwable instanceof ProcessExecutionException) { + internalMoaidExceptionHandler(req, resp, (Exception) throwable, false); + } else { + // write generic message for general exceptions + final String msg = + statusMessager.getMessage(IStatusMessenger.CODES_INTERNAL_ERROR_GENERIC, null); + writeHtmlErrorResponse(req, resp, msg, "9199", null, (Exception) throwable); + + } + + } + + + public void setGuiBuilder(final IGuiFormBuilder guiBuilder) { + this.guiBuilder = guiBuilder; + } + + /** + * Finalize the requested protocol operation. + * + * @param httpReq HttpServletRequest + * @param httpResp HttpServletResponse + * @param protocolRequest Authentication request which is actually in process + * @param moaSession MOASession object, which is used to generate the protocol specific + * authentication information + * @throws Exception In case of an error + */ + protected void internalFinalizeAuthenticationProcess(final HttpServletRequest req, + final HttpServletResponse resp, final IRequest pendingReq) throws Exception { + + String newSsoSessionId = null; + + // if Single Sign-On functionality is enabled for this request + if (pendingReq.needSingleSignOnFunctionality()) { + if (ssoManager != null) { + newSsoSessionId = ssoManager.createNewSsoSessionCookie(req, resp, pendingReq); + if (StringUtils.isEmpty(pendingReq.getInternalSsoSessionIdentifier())) { + ssoManager.createNewSsoSession(pendingReq, newSsoSessionId); + } + + } else { + log.warn("SSO is requested but there is not SSO Session-Manager available"); + } + + } + + // build authenticationdata from session information and OA configuration + final IAuthData authData = authDataBuilder.buildAuthenticationData(pendingReq); + + // execute the protocol-specific action + final SloInformationInterface sloInformation = + executeProtocolSpecificAction(req, resp, pendingReq, authData); + + // Store OA specific SSO session information if an SSO cookie is set + if (StringUtils.isNotEmpty(newSsoSessionId)) { + try { + ssoManager.updateSsoSession(pendingReq, newSsoSessionId, sloInformation); + + } catch (final EaafSsoException e) { + log.warn("SSO Session information can not be stored -> SSO is not enabled!"); + authmanager.performOnlyIdpLogOut(req, resp, pendingReq); + + } + + } else { + // remove MOASession from database + authmanager.performOnlyIdpLogOut(req, resp, pendingReq); + + } + + // Advanced statistic logging + statisticLogger.logSuccessOperation(pendingReq, authData, + StringUtils.isNotEmpty(newSsoSessionId)); + + } + + /** + * Executes the requested protocol action. + * + * @param httpReq HttpServletRequest + * @param httpResp HttpServletResponse + * @param protocolRequest Authentication request which is actually in process + * @param authData Service-provider specific authentication data + * + * @return Return Single LogOut information or null if protocol supports no SSO + * + * @throws Exception in case of an error + */ + private SloInformationInterface executeProtocolSpecificAction(final HttpServletRequest httpReq, + final HttpServletResponse httpResp, final IRequest pendingReq, final IAuthData authData) + throws Exception { + try { + // request needs no authentication --> start request processing + final Class clazz = Class.forName(pendingReq.requestedAction()); + if (clazz == null || !IAction.class.isAssignableFrom(clazz)) { + log.error( + "Requested protocol-action processing Class is NULL or does not implement the IAction interface."); + throw new Exception( + "Requested protocol-action processing Class is NULL or does not implement the IAction interface."); + + } + + final IAction protocolAction = (IAction) applicationContext.getBean(clazz); + return protocolAction.processRequest(pendingReq, httpReq, httpResp, authData); + + } catch (final ClassNotFoundException e) { + log.error( + "Requested Auth. protocol processing Class is NULL or does not implement the IAction interface."); + throw new Exception( + "Requested Auth. protocol processing Class is NULL or does not implement the IAction interface."); + } + + } + + /** + * Write a Exception to the MOA-ID-Auth internal technical log. + * + * @param loggedException Exception to log + */ + protected void logExceptionToTechnicalLog(final Throwable loggedException) { + if (!(loggedException instanceof EaafException + || loggedException instanceof ProcessExecutionException)) { + log.error("Receive an internal error: Message=" + loggedException.getMessage(), + loggedException); + + } else { + if (loggedException instanceof EaafAuthenticationException && ERROR_LOGGER_ON_INFO_LEVEL + .contains(((EaafAuthenticationException) loggedException).getErrorId())) { + if (log.isDebugEnabled() || log.isTraceEnabled()) { + log.info(loggedException.getMessage(), loggedException); + + } else { + log.info(loggedException.getMessage()); + + } + + } else { + if (log.isDebugEnabled() || log.isTraceEnabled()) { + log.warn(loggedException.getMessage(), loggedException); + + } else { + log.warn(loggedException.getMessage()); + + } + } + } + } + + private void writeHtmlErrorResponse(@NonNull final HttpServletRequest httpReq, + @NonNull final HttpServletResponse httpResp, @NonNull final String msg, + @NonNull final String errorCode, @Nullable final Object[] params, + @NonNull final Exception error) throws IOException, EaafException { + + try { + final IGuiBuilderConfiguration config = + guiConfigFactory.getDefaultErrorGui(HttpUtils.extractAuthUrlFromRequest(httpReq)); + + + String[] errorCodeParams = null; + if (params == null) { + errorCodeParams = new String[] {}; + } else { + errorCodeParams = new String[params.length]; + for (int i = 0; i < params.length; i++) { + if (params[i] != null) { + errorCodeParams[i] = params[i].toString(); + } else { + errorCodeParams[i] = "null"; + } + + } + } + + + + // add errorcode and errormessage + if (config instanceof ModifyableGuiBuilderConfiguration) { + ((ModifyableGuiBuilderConfiguration) config).putCustomParameter( + AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERROMSG, msg); + ((ModifyableGuiBuilderConfiguration) config).putCustomParameter( + AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERRORCODE, errorCode); + ((ModifyableGuiBuilderConfiguration) config).putCustomParameterWithOutEscaption( + AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERRORCODEPARAMS, + ArrayUtils.toString(errorCodeParams)); + + // add stacktrace if debug is enabled + if (log.isTraceEnabled()) { + ((ModifyableGuiBuilderConfiguration) config).putCustomParameter( + AbstractGuiFormBuilderConfiguration.PARAM_GROUP_MSG, PARAM_GUI_ERRORSTACKTRACE, + getStacktraceFromException(error)); + + } + + } else { + log.info( + "Can not ADD error message, because 'GUIBuilderConfiguration' is not modifieable "); + } + + + + guiBuilder.build(httpReq, httpResp, config, "Error-Message"); + + } catch (final GuiBuildException e) { + log.warn("Can not build error-message GUI.", e); + throw new EaafException("9199", null, e); + + + } + + } + + private String getStacktraceFromException(final Exception ex) { + final StringWriter errors = new StringWriter(); + ex.printStackTrace(new PrintWriter(errors)); + return errors.toString(); + + } + + private void internalMoaidExceptionHandler(final HttpServletRequest req, + final HttpServletResponse resp, final Exception e, final boolean writeExceptionToStatisicLog) + throws IOException, EaafException { + if (e instanceof ProtocolNotActiveException) { + resp.getWriter().write(e.getMessage()); + resp.setContentType(EAAFConstants.CONTENTTYPE_HTML_UTF8); + resp.sendError(HttpServletResponse.SC_FORBIDDEN, + StringEscapeUtils.escapeHtml4(StringEscapeUtils.escapeEcmaScript(e.getMessage()))); + + } else if (e instanceof AuthnRequestValidatorException) { + final AuthnRequestValidatorException ex = (AuthnRequestValidatorException) e; + // log Error Message + if (writeExceptionToStatisicLog) { + statisticLogger.logErrorOperation(ex, ex.getErrorRequest()); + } + + // write error message + // writeBadRequestErrorResponse(req, resp, (EAAFException) e); + writeHtmlErrorResponse(req, resp, e.getMessage(), statusMessager.getResponseErrorCode(e), + null, e); + + } else if (e instanceof InvalidProtocolRequestException) { + // send error response + // writeBadRequestErrorResponse(req, resp, (EAAFException) e); + writeHtmlErrorResponse(req, resp, e.getMessage(), statusMessager.getResponseErrorCode(e), + null, e); + + } else if (e instanceof ConfigurationException) { + // send HTML formated error message + writeHtmlErrorResponse(req, resp, e.getMessage(), statusMessager.getResponseErrorCode(e), + null, e); + + } else if (e instanceof EaafException) { + // send HTML formated error message + writeHtmlErrorResponse(req, resp, e.getMessage(), statusMessager.getResponseErrorCode(e), + ((EaafException) e).getParams(), e); + + } else if (e instanceof ProcessExecutionException) { + // send HTML formated error message + writeHtmlErrorResponse(req, resp, e.getMessage(), statusMessager.getResponseErrorCode(e), + null, e); + + } + + } + + } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/SimpleStringAttributeGenerator.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/SimpleStringAttributeGenerator.java index 77bd9b8a..fc36f492 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/SimpleStringAttributeGenerator.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/SimpleStringAttributeGenerator.java @@ -1,68 +1,82 @@ /* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * Copyright 2014 Federal Chancellery Austria MOA-ID has been developed in a cooperation between + * BRZ, the Federal Chancellery Austria - ICT staff unit, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: http://www.osor.eu/eupl/ * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. */ + package at.gv.egiz.eaaf.core.impl.idp.builder; import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; /** + * Simple String attribute generator that only generates attribute values as String. + * * @author tlenz * */ public class SimpleStringAttributeGenerator implements IAttributeGenerator { - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeGenerator#buildStringAttribute(java.lang.String, java.lang.String, java.lang.String) - */ - @Override - public String buildStringAttribute(String friendlyName, String name, String value) { - return value; - - } + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeGenerator#buildStringAttribute( + * java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public String buildStringAttribute(final String friendlyName, final String name, final String value) { + return value; + + } + + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeGenerator#buildIntegerAttribute + * (java.lang.String, java.lang.String, int) + */ + @Override + public String buildIntegerAttribute(final String friendlyName, final String name, final int value) { + return String.valueOf(value); + + } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeGenerator#buildIntegerAttribute(java.lang.String, java.lang.String, int) - */ - @Override - public String buildIntegerAttribute(String friendlyName, String name, int value) { - return String.valueOf(value); - - } + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeGenerator#buildLongAttribute( + * java.lang.String, java.lang.String, long) + */ + @Override + public String buildLongAttribute(final String friendlyName, final String name, final long value) { + return String.valueOf(value); - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeGenerator#buildLongAttribute(java.lang.String, java.lang.String, long) - */ - @Override - public String buildLongAttribute(String friendlyName, String name, long value) { - return String.valueOf(value); - - } + } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeGenerator#buildEmptyAttribute(java.lang.String, java.lang.String) - */ - @Override - public String buildEmptyAttribute(String friendlyName, String name) { - return null; - } + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeGenerator#buildEmptyAttribute( + * java.lang.String, java.lang.String) + */ + @Override + public String buildEmptyAttribute(final String friendlyName, final String name) { + return null; + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/BPKAttributeBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/BPKAttributeBuilder.java deleted file mode 100644 index 714ffc9d..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/BPKAttributeBuilder.java +++ /dev/null @@ -1,123 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; - -import javax.annotation.Nonnull; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.util.Assert; - -import at.gv.egiz.eaaf.core.api.data.EAAFConstants; -import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; -import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; - -@PVPMETADATA -public class BPKAttributeBuilder implements IPVPAttributeBuilder { - - private static final Logger log = LoggerFactory.getLogger(BPKAttributeBuilder.class); - public static final String DELIMITER_BPKTYPE_BPK = ":"; - - @Override - public String getName() { - return BPK_NAME; - } - - @Override - public ATT build(ISPConfiguration oaParam, IAuthData authData, - IAttributeGenerator g) throws AttributeBuilderException { - final String result = getBpkForSP(authData); - log.trace("Authenticate user with bPK/wbPK: " + result); - return g.buildStringAttribute(BPK_FRIENDLY_NAME, BPK_NAME, result); - - } - - @Override - public ATT buildEmpty(IAttributeGenerator g) { - return g.buildEmptyAttribute(BPK_FRIENDLY_NAME, BPK_NAME); - } - - /** - * Generate the bPK String for this specific SP - * - * @param authData - * @return - * @throws UnavailableAttributeException - */ - protected String getBpkForSP(IAuthData authData) throws UnavailableAttributeException { - final String bpk = attrMaxSize(authData.getBPK()); - final String type = removeBpkTypePrefix(authData.getBPKType()); - - if (StringUtils.isEmpty(bpk)) - throw new UnavailableAttributeException(BPK_NAME); - - return type + DELIMITER_BPKTYPE_BPK + bpk; - - } - - /** - * Limit the attribute value to maximum size - * - * @param attr - * @return - */ - protected String attrMaxSize(String attr) { - if (attr != null && attr.length() > BPK_MAX_LENGTH) { - attr = attr.substring(0, BPK_MAX_LENGTH); - } - return attr; - - } - - /** - * Remove bPKType prefix if available - * - * @param type - * @return - */ - @Nonnull - protected String removeBpkTypePrefix(@Nonnull String type) { - Assert.isTrue(type != null, "bPKType is 'NULL'"); - if (type.startsWith(EAAFConstants.URN_PREFIX_WBPK)) - return type.substring((EAAFConstants.URN_PREFIX_WBPK).length()); - - else if (type.startsWith(EAAFConstants.URN_PREFIX_CDID)) - return type.substring((EAAFConstants.URN_PREFIX_CDID).length()); - - else if (type.startsWith(EAAFConstants.URN_PREFIX_EIDAS)) - return type.substring((EAAFConstants.URN_PREFIX_EIDAS).length()); - - else - return type; - - } -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/BirthdateAttributeBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/BirthdateAttributeBuilder.java index c52a5d82..505ba137 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/BirthdateAttributeBuilder.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/BirthdateAttributeBuilder.java @@ -1,67 +1,60 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; import java.text.DateFormat; import java.text.SimpleDateFormat; - import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.api.idp.IPvpAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; -@PVPMETADATA -public class BirthdateAttributeBuilder implements IPVPAttributeBuilder { - - @Override - public String getName() { - return BIRTHDATE_NAME; - } - - @Override - public ATT build(ISPConfiguration oaParam, IAuthData authData, - IAttributeGenerator g) throws AttributeBuilderException { - - if (authData.getDateOfBirth() != null) { - final DateFormat pvpDateFormat = new SimpleDateFormat(BIRTHDATE_FORMAT_PATTERN); - final String dateString = pvpDateFormat.format(authData.getDateOfBirth()); - - return g.buildStringAttribute(BIRTHDATE_FRIENDLY_NAME, BIRTHDATE_NAME, dateString); - - } else - throw new UnavailableAttributeException(BIRTHDATE_NAME); - - } - - @Override - public ATT buildEmpty(IAttributeGenerator g) { - return g.buildEmptyAttribute(BIRTHDATE_FRIENDLY_NAME, BIRTHDATE_NAME); - } - +@PvpMetadata +public class BirthdateAttributeBuilder implements IPvpAttributeBuilder { + + @Override + public String getName() { + return BIRTHDATE_NAME; + } + + @Override + public ATT build(final IspConfiguration oaParam, final IAuthData authData, + final IAttributeGenerator g) throws AttributeBuilderException { + + if (authData.getDateOfBirth() != null) { + final DateFormat pvpDateFormat = new SimpleDateFormat(BIRTHDATE_FORMAT_PATTERN); + final String dateString = pvpDateFormat.format(authData.getDateOfBirth()); + + return g.buildStringAttribute(BIRTHDATE_FRIENDLY_NAME, BIRTHDATE_NAME, dateString); + + } else { + throw new UnavailableAttributeException(BIRTHDATE_NAME); + } + + } + + @Override + public ATT buildEmpty(final IAttributeGenerator g) { + return g.buildEmptyAttribute(BIRTHDATE_FRIENDLY_NAME, BIRTHDATE_NAME); + } + } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/BpkAttributeBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/BpkAttributeBuilder.java new file mode 100644 index 00000000..2908ebdf --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/BpkAttributeBuilder.java @@ -0,0 +1,94 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; + +import javax.annotation.Nonnull; +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPvpAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.util.Assert; + +@PvpMetadata +public class BpkAttributeBuilder implements IPvpAttributeBuilder { + + private static final Logger log = LoggerFactory.getLogger(BpkAttributeBuilder.class); + public static final String DELIMITER_BPKTYPE_BPK = ":"; + + @Override + public String getName() { + return BPK_NAME; + } + + @Override + public ATT build(final IspConfiguration oaParam, final IAuthData authData, + final IAttributeGenerator g) throws AttributeBuilderException { + final String result = getBpkForSP(authData); + log.trace("Authenticate user with bPK/wbPK: " + result); + return g.buildStringAttribute(BPK_FRIENDLY_NAME, BPK_NAME, result); + + } + + @Override + public ATT buildEmpty(final IAttributeGenerator g) { + return g.buildEmptyAttribute(BPK_FRIENDLY_NAME, BPK_NAME); + } + + protected String getBpkForSP(final IAuthData authData) throws UnavailableAttributeException { + final String bpk = attrMaxSize(authData.getBpk()); + final String type = removeBpkTypePrefix(authData.getBpkType()); + + if (StringUtils.isEmpty(bpk)) { + throw new UnavailableAttributeException(BPK_NAME); + } + + return type + DELIMITER_BPKTYPE_BPK + bpk; + + } + + protected String attrMaxSize(String attr) { + if (attr != null && attr.length() > BPK_MAX_LENGTH) { + attr = attr.substring(0, BPK_MAX_LENGTH); + } + return attr; + + } + + @Nonnull + protected String removeBpkTypePrefix(@Nonnull final String type) { + Assert.isTrue(type != null, "bPKType is 'NULL'"); + if (type.startsWith(EAAFConstants.URN_PREFIX_WBPK)) { + return type.substring((EAAFConstants.URN_PREFIX_WBPK).length()); + } else if (type.startsWith(EAAFConstants.URN_PREFIX_CDID)) { + return type.substring((EAAFConstants.URN_PREFIX_CDID).length()); + } else if (type.startsWith(EAAFConstants.URN_PREFIX_EIDAS)) { + return type.substring((EAAFConstants.URN_PREFIX_EIDAS).length()); + } else { + return type; + } + + } +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDCcsURL.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDCcsURL.java deleted file mode 100644 index ec0f5d0c..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDCcsURL.java +++ /dev/null @@ -1,44 +0,0 @@ -package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.IEidAuthData; -import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; -import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; - -@PVPMETADATA -public class EIDCcsURL implements IPVPAttributeBuilder { - private static final Logger log = LoggerFactory.getLogger(EID_CCS_URL_NAME); - - @Override - public String getName() { - return EID_CCS_URL_NAME; - } - - @Override - public ATT build(ISPConfiguration oaParam, IAuthData authData, - IAttributeGenerator g) throws AttributeBuilderException { - if (authData instanceof IEidAuthData) { - final String bkuurl = ((IEidAuthData)authData).getVdaEndPointUrl(); - if (StringUtils.isNotEmpty(bkuurl)) - return g.buildStringAttribute(EID_CCS_URL_FRIENDLY_NAME, EID_CCS_URL_NAME, bkuurl); - - - } else - log.info(EID_CCS_URL_FRIENDLY_NAME + " is only available in MOA-ID context"); - - throw new UnavailableAttributeException(EID_CCS_URL_NAME); - } - - @Override - public ATT buildEmpty(IAttributeGenerator g) { - return g.buildEmptyAttribute(EID_CCS_URL_FRIENDLY_NAME, EID_CCS_URL_NAME); - } - -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDEIDTokenBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDEIDTokenBuilder.java deleted file mode 100644 index 698393ea..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDEIDTokenBuilder.java +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.util.Base64Utils; - -import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.IEidAuthData; -import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; -import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; - -@PVPMETADATA -public class EIDEIDTokenBuilder implements IPVPAttributeBuilder { - private static final Logger log = LoggerFactory.getLogger(EIDEIDTokenBuilder.class); - - - @Override - public String getName() { - return EID_E_ID_TOKEN_NAME; - } - - @Override - public ATT build(final ISPConfiguration oaParam, final IAuthData authData, - final IAttributeGenerator g) throws AttributeBuilderException { - - if (authData instanceof IEidAuthData) { - if (((IEidAuthData)authData).getEIDToken() == null) - throw new UnavailableAttributeException(EID_E_ID_TOKEN_NAME); - - return g.buildStringAttribute(EID_E_ID_TOKEN_FRIENDLY_NAME, - EID_E_ID_TOKEN_NAME, Base64Utils.encodeToString(((IEidAuthData)authData).getEIDToken())); - } else - log.info(EID_E_ID_TOKEN_FRIENDLY_NAME + " is only available in AuthHandler context"); - - throw new UnavailableAttributeException(EID_E_ID_TOKEN_NAME); - } - - @Override - public ATT buildEmpty(final IAttributeGenerator g) { - return g.buildEmptyAttribute(EID_E_ID_TOKEN_FRIENDLY_NAME, - EID_E_ID_TOKEN_NAME); - } - -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDEncryptedSourceIdAttributeBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDEncryptedSourceIdAttributeBuilder.java deleted file mode 100644 index 3fbdaf66..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDEncryptedSourceIdAttributeBuilder.java +++ /dev/null @@ -1,58 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; - -import at.gv.egiz.eaaf.core.api.data.ExtendedPVPAttributeDefinitions; -import at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder; -import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; - -public class EIDEncryptedSourceIdAttributeBuilder implements IAttributeBuilder, ExtendedPVPAttributeDefinitions { - - @Override - public ATT build(ISPConfiguration oaParam, IAuthData authData, IAttributeGenerator g) - throws AttributeBuilderException { - return g.buildStringAttribute(getFriendlyName(), getName(), authData.getEncryptedSourceId()); - - } - - @Override - public ATT buildEmpty(IAttributeGenerator g) { - return g.buildEmptyAttribute(getFriendlyName(), getName()); - - } - - @Override - public String getName() { - return EID_ENCRYPTED_SOURCEID_NAME; - } - - private String getFriendlyName() { - return EID_ENCRYPTED_SOURCEID_FRIENDLY_NAME; - } - -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDEncryptedSourceIdTypeAttributeBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDEncryptedSourceIdTypeAttributeBuilder.java deleted file mode 100644 index 440ccf59..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDEncryptedSourceIdTypeAttributeBuilder.java +++ /dev/null @@ -1,58 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; - -import at.gv.egiz.eaaf.core.api.data.ExtendedPVPAttributeDefinitions; -import at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder; -import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; - -public class EIDEncryptedSourceIdTypeAttributeBuilder implements IAttributeBuilder, ExtendedPVPAttributeDefinitions { - - @Override - public ATT build(ISPConfiguration oaParam, IAuthData authData, IAttributeGenerator g) - throws AttributeBuilderException { - return g.buildStringAttribute(getFriendlyName(), getName(), authData.getEncryptedSourceIdType()); - - } - - @Override - public ATT buildEmpty(IAttributeGenerator g) { - return g.buildEmptyAttribute(getFriendlyName(), getName()); - - } - - @Override - public String getName() { - return EID_ENCRYPTED_SOURCEID_TYPE_NAME; - } - - private String getFriendlyName() { - return EID_ENCRYPTED_SOURCEID_TYPE_FRIENDLY_NAME; - } - -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDIdentityLinkBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDIdentityLinkBuilder.java deleted file mode 100644 index 8a2cabbc..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDIdentityLinkBuilder.java +++ /dev/null @@ -1,78 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; - -import java.io.IOException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.util.Base64Utils; - -import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; -import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; - -@Deprecated -@PVPMETADATA -public class EIDIdentityLinkBuilder implements IPVPAttributeBuilder { - private static final Logger log = LoggerFactory.getLogger(EIDIdentityLinkBuilder.class); - - - public String getName() { - return EID_IDENTITY_LINK_NAME; - } - - public ATT build(ISPConfiguration oaParam, IAuthData authData, - IAttributeGenerator g) throws AttributeBuilderException { - try { - String ilAssertion = null; - if (authData.getIdentityLink() == null) - throw new UnavailableAttributeException(EID_IDENTITY_LINK_NAME); - - ilAssertion = authData.getIdentityLink().getSerializedSamlAssertion(); - - return g.buildStringAttribute(EID_IDENTITY_LINK_FRIENDLY_NAME, - EID_IDENTITY_LINK_NAME, Base64Utils.encodeToString(ilAssertion.getBytes("UTF-8"))); - - - } catch (IOException e) { - log.warn("IdentityLink serialization error.", e); - return g.buildEmptyAttribute(EID_IDENTITY_LINK_FRIENDLY_NAME, - EID_IDENTITY_LINK_NAME); - } - - } - - public ATT buildEmpty(IAttributeGenerator g) { - return g.buildEmptyAttribute(EID_IDENTITY_LINK_FRIENDLY_NAME, - EID_IDENTITY_LINK_NAME); - } - -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDIssuingNationAttributeBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDIssuingNationAttributeBuilder.java deleted file mode 100644 index a52197cb..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDIssuingNationAttributeBuilder.java +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; - -import org.apache.commons.lang3.StringUtils; - -import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; - -@PVPMETADATA -public class EIDIssuingNationAttributeBuilder implements IPVPAttributeBuilder { - - public String getName() { - return EID_ISSUING_NATION_NAME; - } - - public ATT build(ISPConfiguration oaParam, IAuthData authData, - IAttributeGenerator g) throws AttributeBuilderException { - String countryCode = authData.getCiticenCountryCode(); - if (StringUtils.isNotEmpty(countryCode)) - return g.buildStringAttribute(EID_ISSUING_NATION_FRIENDLY_NAME, - EID_ISSUING_NATION_NAME, countryCode); - - else - return null; - } - - public ATT buildEmpty(IAttributeGenerator g) { - return g.buildEmptyAttribute(EID_ISSUING_NATION_FRIENDLY_NAME, - EID_ISSUING_NATION_NAME); - } - -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDSectorForIDAttributeBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDSectorForIDAttributeBuilder.java deleted file mode 100644 index 39c9db8f..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDSectorForIDAttributeBuilder.java +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; - -import org.apache.commons.lang3.StringUtils; - -import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; -import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; - -@PVPMETADATA -public class EIDSectorForIDAttributeBuilder implements IPVPAttributeBuilder { - - public String getName() { - return EID_SECTOR_FOR_IDENTIFIER_NAME; - } - - public ATT build(ISPConfiguration oaParam, IAuthData authData, - IAttributeGenerator g) throws AttributeBuilderException { - String bpktype = authData.getBPKType(); - - if (StringUtils.isEmpty(authData.getBPKType())) - throw new UnavailableAttributeException(EID_SECTOR_FOR_IDENTIFIER_NAME); - - return g.buildStringAttribute(EID_SECTOR_FOR_IDENTIFIER_FRIENDLY_NAME, - EID_SECTOR_FOR_IDENTIFIER_NAME, bpktype); - } - - public ATT buildEmpty(IAttributeGenerator g) { - return g.buildEmptyAttribute(EID_SECTOR_FOR_IDENTIFIER_FRIENDLY_NAME, - EID_SECTOR_FOR_IDENTIFIER_NAME); - } - -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDSignerCertificate.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDSignerCertificate.java deleted file mode 100644 index bab521b4..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDSignerCertificate.java +++ /dev/null @@ -1,80 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; - - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.util.Base64Utils; - -import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.IEidAuthData; -import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; -import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; - -@PVPMETADATA -public class EIDSignerCertificate implements IPVPAttributeBuilder { - private static final Logger log = LoggerFactory.getLogger(EIDSignerCertificate.class); - - @Override - public String getName() { - return EID_SIGNER_CERTIFICATE_NAME; - } - - @Override - public ATT build(final ISPConfiguration oaParam, final IAuthData authData, - final IAttributeGenerator g) throws AttributeBuilderException { - - if (authData instanceof IEidAuthData) { - try { - - final byte[] signerCertificate = ((IEidAuthData)authData).getSignerCertificate(); - if (signerCertificate != null) { - return g.buildStringAttribute(EID_SIGNER_CERTIFICATE_FRIENDLY_NAME, EID_SIGNER_CERTIFICATE_NAME, - Base64Utils.encodeToString(signerCertificate)); - - } else - log.info(EID_SIGNER_CERTIFICATE_FRIENDLY_NAME + " is only available in MOA-ID context"); - - } catch (final Exception e) { - log.info("Signer certificate BASE64 encoding error"); - - } - - } else - log.info(EID_SIGNER_CERTIFICATE_FRIENDLY_NAME + " is only available in AuthHandler context"); - - - throw new UnavailableAttributeException(EID_SIGNER_CERTIFICATE_NAME); - - } - - @Override - public ATT buildEmpty(final IAttributeGenerator g) { - return g.buildEmptyAttribute(EID_SIGNER_CERTIFICATE_FRIENDLY_NAME, EID_SIGNER_CERTIFICATE_NAME); - } - -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDSourcePIN.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDSourcePIN.java deleted file mode 100644 index 4db2d87d..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDSourcePIN.java +++ /dev/null @@ -1,65 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; - -import org.apache.commons.lang3.StringUtils; - -import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; -import at.gv.egiz.eaaf.core.exceptions.AttributePolicyException; -import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; - -@Deprecated -@PVPMETADATA -public class EIDSourcePIN implements IPVPAttributeBuilder { - - public String getName() { - return EID_SOURCE_PIN_NAME; - } - - public ATT build(ISPConfiguration oaParam, IAuthData authData, - IAttributeGenerator g) throws AttributeBuilderException { - - if (authData.isBaseIDTransferRestrication()) - throw new AttributePolicyException(EID_SOURCE_PIN_NAME); - - else { - if (StringUtils.isEmpty(authData.getIdentificationValue())) - throw new UnavailableAttributeException(EID_SOURCE_PIN_NAME); - - return g.buildStringAttribute(EID_SOURCE_PIN_FRIENDLY_NAME, EID_SOURCE_PIN_NAME, authData.getIdentificationValue()); - } - } - - public ATT buildEmpty(IAttributeGenerator g) { - return g.buildEmptyAttribute(EID_SOURCE_PIN_FRIENDLY_NAME, EID_SOURCE_PIN_NAME); - } - -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDSourcePINType.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDSourcePINType.java deleted file mode 100644 index 42e47a42..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDSourcePINType.java +++ /dev/null @@ -1,59 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; - -import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; -import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; - -@Deprecated -@PVPMETADATA -public class EIDSourcePINType implements IPVPAttributeBuilder { - - public String getName() { - return EID_SOURCE_PIN_TYPE_NAME; - } - - public ATT build(ISPConfiguration oaParam, IAuthData authData, - IAttributeGenerator g) throws AttributeBuilderException { - - if (authData.isBaseIDTransferRestrication()) - throw new UnavailableAttributeException(EID_SOURCE_PIN_TYPE_NAME); - - else { - return g.buildStringAttribute(EID_SOURCE_PIN_TYPE_FRIENDLY_NAME, EID_SOURCE_PIN_TYPE_NAME, authData.getIdentificationType()); - } - } - - public ATT buildEmpty(IAttributeGenerator g) { - return g.buildEmptyAttribute(EID_SOURCE_PIN_TYPE_FRIENDLY_NAME, EID_SOURCE_PIN_TYPE_NAME); - } - -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDeIDASQAALevelAttributeBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDeIDASQAALevelAttributeBuilder.java deleted file mode 100644 index 1e7b323b..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EIDeIDASQAALevelAttributeBuilder.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; - - -import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; - -@PVPMETADATA -public class EIDeIDASQAALevelAttributeBuilder implements IPVPAttributeBuilder { - - public String getName() { - return EID_CITIZEN_EIDAS_QAA_LEVEL_NAME; - } - - public ATT build(ISPConfiguration oaParam, IAuthData authData, - IAttributeGenerator g) throws AttributeBuilderException { - - return g.buildStringAttribute(EID_CITIZEN_EIDAS_QAA_LEVEL_FRIENDLY_NAME, - EID_CITIZEN_EIDAS_QAA_LEVEL_NAME, authData.getEIDASQAALevel()); - } - - - public ATT buildEmpty(IAttributeGenerator g) { - return g.buildEmptyAttribute(EID_CITIZEN_EIDAS_QAA_LEVEL_FRIENDLY_NAME, - EID_CITIZEN_EIDAS_QAA_LEVEL_NAME); - } - -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidCcsUrl.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidCcsUrl.java new file mode 100644 index 00000000..8029d769 --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidCcsUrl.java @@ -0,0 +1,46 @@ +package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IEidAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPvpAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; + +@PvpMetadata +public class EidCcsUrl implements IPvpAttributeBuilder { + private static final Logger log = LoggerFactory.getLogger(EID_CCS_URL_NAME); + + @Override + public String getName() { + return EID_CCS_URL_NAME; + } + + @Override + public ATT build(final IspConfiguration oaParam, final IAuthData authData, + final IAttributeGenerator g) throws AttributeBuilderException { + if (authData instanceof IEidAuthData) { + final String bkuurl = ((IEidAuthData) authData).getVdaEndPointUrl(); + if (StringUtils.isNotEmpty(bkuurl)) { + return g.buildStringAttribute(EID_CCS_URL_FRIENDLY_NAME, EID_CCS_URL_NAME, bkuurl); + } + + + } else { + log.info(EID_CCS_URL_FRIENDLY_NAME + " is only available in MOA-ID context"); + } + + throw new UnavailableAttributeException(EID_CCS_URL_NAME); + } + + @Override + public ATT buildEmpty(final IAttributeGenerator g) { + return g.buildEmptyAttribute(EID_CCS_URL_FRIENDLY_NAME, EID_CCS_URL_NAME); + } + +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidEidTokenBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidEidTokenBuilder.java new file mode 100644 index 00000000..ccc2b4e8 --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidEidTokenBuilder.java @@ -0,0 +1,66 @@ +/* + * Copyright 2019 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; + +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IEidAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPvpAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.util.Base64Utils; + +@PvpMetadata +public class EidEidTokenBuilder implements IPvpAttributeBuilder { + private static final Logger log = LoggerFactory.getLogger(EidEidTokenBuilder.class); + + + @Override + public String getName() { + return EID_E_ID_TOKEN_NAME; + } + + @Override + public ATT build(final IspConfiguration oaParam, final IAuthData authData, + final IAttributeGenerator g) throws AttributeBuilderException { + + if (authData instanceof IEidAuthData) { + if (((IEidAuthData) authData).getEidToken() == null) { + throw new UnavailableAttributeException(EID_E_ID_TOKEN_NAME); + } + + return g.buildStringAttribute(EID_E_ID_TOKEN_FRIENDLY_NAME, EID_E_ID_TOKEN_NAME, + Base64Utils.encodeToString(((IEidAuthData) authData).getEidToken())); + } else { + log.info(EID_E_ID_TOKEN_FRIENDLY_NAME + " is only available in AuthHandler context"); + } + + throw new UnavailableAttributeException(EID_E_ID_TOKEN_NAME); + } + + @Override + public ATT buildEmpty(final IAttributeGenerator g) { + return g.buildEmptyAttribute(EID_E_ID_TOKEN_FRIENDLY_NAME, EID_E_ID_TOKEN_NAME); + } + +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidEidasQaaLevelAttributeBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidEidasQaaLevelAttributeBuilder.java new file mode 100644 index 00000000..858baf40 --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidEidasQaaLevelAttributeBuilder.java @@ -0,0 +1,52 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. + */ + +package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; + + +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPvpAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; + +@PvpMetadata +public class EidEidasQaaLevelAttributeBuilder implements IPvpAttributeBuilder { + + @Override + public String getName() { + return EID_CITIZEN_EIDAS_QAA_LEVEL_NAME; + } + + @Override + public ATT build(final IspConfiguration oaParam, final IAuthData authData, + final IAttributeGenerator g) throws AttributeBuilderException { + + return g.buildStringAttribute(EID_CITIZEN_EIDAS_QAA_LEVEL_FRIENDLY_NAME, + EID_CITIZEN_EIDAS_QAA_LEVEL_NAME, authData.getEidasQaaLevel()); + } + + + @Override + public ATT buildEmpty(final IAttributeGenerator g) { + return g.buildEmptyAttribute(EID_CITIZEN_EIDAS_QAA_LEVEL_FRIENDLY_NAME, + EID_CITIZEN_EIDAS_QAA_LEVEL_NAME); + } + +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidEncryptedSourceIdAttributeBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidEncryptedSourceIdAttributeBuilder.java new file mode 100644 index 00000000..e828d11c --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidEncryptedSourceIdAttributeBuilder.java @@ -0,0 +1,54 @@ +/* + * Copyright 2019 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; + +import at.gv.egiz.eaaf.core.api.data.ExtendedPVPAttributeDefinitions; +import at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; + +public class EidEncryptedSourceIdAttributeBuilder + implements IAttributeBuilder, ExtendedPVPAttributeDefinitions { + + @Override + public ATT build(final IspConfiguration oaParam, final IAuthData authData, final IAttributeGenerator g) + throws AttributeBuilderException { + return g.buildStringAttribute(getFriendlyName(), getName(), authData.getEncryptedSourceId()); + + } + + @Override + public ATT buildEmpty(final IAttributeGenerator g) { + return g.buildEmptyAttribute(getFriendlyName(), getName()); + + } + + @Override + public String getName() { + return EID_ENCRYPTED_SOURCEID_NAME; + } + + private String getFriendlyName() { + return EID_ENCRYPTED_SOURCEID_FRIENDLY_NAME; + } + +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidEncryptedSourceIdTypeAttributeBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidEncryptedSourceIdTypeAttributeBuilder.java new file mode 100644 index 00000000..a1a245d1 --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidEncryptedSourceIdTypeAttributeBuilder.java @@ -0,0 +1,55 @@ +/* + * Copyright 2019 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; + +import at.gv.egiz.eaaf.core.api.data.ExtendedPVPAttributeDefinitions; +import at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; + +public class EidEncryptedSourceIdTypeAttributeBuilder + implements IAttributeBuilder, ExtendedPVPAttributeDefinitions { + + @Override + public ATT build(final IspConfiguration oaParam, final IAuthData authData, final IAttributeGenerator g) + throws AttributeBuilderException { + return g.buildStringAttribute(getFriendlyName(), getName(), + authData.getEncryptedSourceIdType()); + + } + + @Override + public ATT buildEmpty(final IAttributeGenerator g) { + return g.buildEmptyAttribute(getFriendlyName(), getName()); + + } + + @Override + public String getName() { + return EID_ENCRYPTED_SOURCEID_TYPE_NAME; + } + + private String getFriendlyName() { + return EID_ENCRYPTED_SOURCEID_TYPE_FRIENDLY_NAME; + } + +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidIdentityLinkBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidIdentityLinkBuilder.java new file mode 100644 index 00000000..8f629795 --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidIdentityLinkBuilder.java @@ -0,0 +1,71 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; + +import java.io.IOException; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPvpAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.util.Base64Utils; + +@Deprecated +@PvpMetadata +public class EidIdentityLinkBuilder implements IPvpAttributeBuilder { + private static final Logger log = LoggerFactory.getLogger(EidIdentityLinkBuilder.class); + + + @Override + public String getName() { + return EID_IDENTITY_LINK_NAME; + } + + @Override + public ATT build(final IspConfiguration oaParam, final IAuthData authData, + final IAttributeGenerator g) throws AttributeBuilderException { + try { + String ilAssertion = null; + if (authData.getIdentityLink() == null) { + throw new UnavailableAttributeException(EID_IDENTITY_LINK_NAME); + } + + ilAssertion = authData.getIdentityLink().getSerializedSamlAssertion(); + + return g.buildStringAttribute(EID_IDENTITY_LINK_FRIENDLY_NAME, EID_IDENTITY_LINK_NAME, + Base64Utils.encodeToString(ilAssertion.getBytes("UTF-8"))); + + + } catch (final IOException e) { + log.warn("IdentityLink serialization error.", e); + return g.buildEmptyAttribute(EID_IDENTITY_LINK_FRIENDLY_NAME, EID_IDENTITY_LINK_NAME); + } + + } + + @Override + public ATT buildEmpty(final IAttributeGenerator g) { + return g.buildEmptyAttribute(EID_IDENTITY_LINK_FRIENDLY_NAME, EID_IDENTITY_LINK_NAME); + } + +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidIdentityStatusLevelAttributeBuiler.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidIdentityStatusLevelAttributeBuiler.java index 6a8de559..2f70e3e0 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidIdentityStatusLevelAttributeBuiler.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidIdentityStatusLevelAttributeBuiler.java @@ -6,42 +6,45 @@ import org.slf4j.LoggerFactory; import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; import at.gv.egiz.eaaf.core.api.idp.IAuthData; import at.gv.egiz.eaaf.core.api.idp.IEidAuthData; -import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.api.idp.IPvpAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; -@PVPMETADATA -public class EidIdentityStatusLevelAttributeBuiler implements IPVPAttributeBuilder { - private static final Logger log = LoggerFactory.getLogger(EidIdentityStatusLevelAttributeBuiler.class); - - @Override - public String getName() { - return EID_IDENTITY_STATUS_LEVEL_NAME; - } - - @Override - public ATT build(ISPConfiguration oaParam, IAuthData authData, IAttributeGenerator g) - throws AttributeBuilderException { - - if (authData instanceof IEidAuthData) { - if (((IEidAuthData)authData).getEIDStatus() == null) - throw new UnavailableAttributeException(getName()); - - return g.buildStringAttribute(getFriendlyName(), - getName(), ((IEidAuthData)authData).getEIDStatus().getURI()); - } else - log.info(getFriendlyName() + " is only available in EAAF context"); - - throw new UnavailableAttributeException(getName()); - } - - @Override - public ATT buildEmpty(IAttributeGenerator g) { - return g.buildEmptyAttribute(getFriendlyName(), getName()); - } - - private String getFriendlyName() { - return EID_IDENTITY_STATUS_LEVEL_FRIENDLY_NAME; - } +@PvpMetadata +public class EidIdentityStatusLevelAttributeBuiler implements IPvpAttributeBuilder { + private static final Logger log = + LoggerFactory.getLogger(EidIdentityStatusLevelAttributeBuiler.class); + + @Override + public String getName() { + return EID_IDENTITY_STATUS_LEVEL_NAME; + } + + @Override + public ATT build(final IspConfiguration oaParam, final IAuthData authData, + final IAttributeGenerator g) throws AttributeBuilderException { + + if (authData instanceof IEidAuthData) { + if (((IEidAuthData) authData).getEidStatus() == null) { + throw new UnavailableAttributeException(getName()); + } + + return g.buildStringAttribute(getFriendlyName(), getName(), + ((IEidAuthData) authData).getEidStatus().getURI()); + } else { + log.info(getFriendlyName() + " is only available in EAAF context"); + } + + throw new UnavailableAttributeException(getName()); + } + + @Override + public ATT buildEmpty(final IAttributeGenerator g) { + return g.buildEmptyAttribute(getFriendlyName(), getName()); + } + + private String getFriendlyName() { + return EID_IDENTITY_STATUS_LEVEL_FRIENDLY_NAME; + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidIssuingNationAttributeBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidIssuingNationAttributeBuilder.java new file mode 100644 index 00000000..04c2b379 --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidIssuingNationAttributeBuilder.java @@ -0,0 +1,54 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; + +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPvpAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import org.apache.commons.lang3.StringUtils; + +@PvpMetadata +public class EidIssuingNationAttributeBuilder implements IPvpAttributeBuilder { + + @Override + public String getName() { + return EID_ISSUING_NATION_NAME; + } + + @Override + public ATT build(final IspConfiguration oaParam, final IAuthData authData, + final IAttributeGenerator g) throws AttributeBuilderException { + final String countryCode = authData.getCiticenCountryCode(); + if (StringUtils.isNotEmpty(countryCode)) { + return g.buildStringAttribute(EID_ISSUING_NATION_FRIENDLY_NAME, EID_ISSUING_NATION_NAME, + countryCode); + } else { + return null; + } + } + + @Override + public ATT buildEmpty(final IAttributeGenerator g) { + return g.buildEmptyAttribute(EID_ISSUING_NATION_FRIENDLY_NAME, EID_ISSUING_NATION_NAME); + } + +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidSectorForIdAttributeBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidSectorForIdAttributeBuilder.java new file mode 100644 index 00000000..f5e37792 --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidSectorForIdAttributeBuilder.java @@ -0,0 +1,57 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; + +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPvpAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; +import org.apache.commons.lang3.StringUtils; + +@PvpMetadata +public class EidSectorForIdAttributeBuilder implements IPvpAttributeBuilder { + + @Override + public String getName() { + return EID_SECTOR_FOR_IDENTIFIER_NAME; + } + + @Override + public ATT build(final IspConfiguration oaParam, final IAuthData authData, + final IAttributeGenerator g) throws AttributeBuilderException { + final String bpktype = authData.getBpkType(); + + if (StringUtils.isEmpty(authData.getBpkType())) { + throw new UnavailableAttributeException(EID_SECTOR_FOR_IDENTIFIER_NAME); + } + + return g.buildStringAttribute(EID_SECTOR_FOR_IDENTIFIER_FRIENDLY_NAME, + EID_SECTOR_FOR_IDENTIFIER_NAME, bpktype); + } + + @Override + public ATT buildEmpty(final IAttributeGenerator g) { + return g.buildEmptyAttribute(EID_SECTOR_FOR_IDENTIFIER_FRIENDLY_NAME, + EID_SECTOR_FOR_IDENTIFIER_NAME); + } + +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidSignerCertificate.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidSignerCertificate.java new file mode 100644 index 00000000..8ba7f255 --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidSignerCertificate.java @@ -0,0 +1,78 @@ +/* + * Copyright 2019 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. + */ + +package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; + + +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IEidAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPvpAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.util.Base64Utils; + +@PvpMetadata +public class EidSignerCertificate implements IPvpAttributeBuilder { + private static final Logger log = LoggerFactory.getLogger(EidSignerCertificate.class); + + @Override + public String getName() { + return EID_SIGNER_CERTIFICATE_NAME; + } + + @Override + public ATT build(final IspConfiguration oaParam, final IAuthData authData, + final IAttributeGenerator g) throws AttributeBuilderException { + + if (authData instanceof IEidAuthData) { + try { + + final byte[] signerCertificate = ((IEidAuthData) authData).getSignerCertificate(); + if (signerCertificate != null) { + return g.buildStringAttribute(EID_SIGNER_CERTIFICATE_FRIENDLY_NAME, + EID_SIGNER_CERTIFICATE_NAME, Base64Utils.encodeToString(signerCertificate)); + + } else { + log.info(EID_SIGNER_CERTIFICATE_FRIENDLY_NAME + " is only available in MOA-ID context"); + } + + } catch (final Exception e) { + log.info("Signer certificate BASE64 encoding error"); + + } + + } else { + log.info(EID_SIGNER_CERTIFICATE_FRIENDLY_NAME + " is only available in AuthHandler context"); + } + + + throw new UnavailableAttributeException(EID_SIGNER_CERTIFICATE_NAME); + + } + + @Override + public ATT buildEmpty(final IAttributeGenerator g) { + return g.buildEmptyAttribute(EID_SIGNER_CERTIFICATE_FRIENDLY_NAME, EID_SIGNER_CERTIFICATE_NAME); + } + +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidSourcePin.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidSourcePin.java new file mode 100644 index 00000000..fd2d51bb --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidSourcePin.java @@ -0,0 +1,61 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. + */ + +package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; + +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPvpAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.exceptions.AttributePolicyException; +import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; +import org.apache.commons.lang3.StringUtils; + +@Deprecated +@PvpMetadata +public class EidSourcePin implements IPvpAttributeBuilder { + + @Override + public String getName() { + return EID_SOURCE_PIN_NAME; + } + + @Override + public ATT build(final IspConfiguration oaParam, final IAuthData authData, + final IAttributeGenerator g) throws AttributeBuilderException { + + if (authData.isBaseIdTransferRestrication()) { + throw new AttributePolicyException(EID_SOURCE_PIN_NAME); + } else { + if (StringUtils.isEmpty(authData.getIdentificationValue())) { + throw new UnavailableAttributeException(EID_SOURCE_PIN_NAME); + } + + return g.buildStringAttribute(EID_SOURCE_PIN_FRIENDLY_NAME, EID_SOURCE_PIN_NAME, + authData.getIdentificationValue()); + } + } + + @Override + public ATT buildEmpty(final IAttributeGenerator g) { + return g.buildEmptyAttribute(EID_SOURCE_PIN_FRIENDLY_NAME, EID_SOURCE_PIN_NAME); + } + +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidSourcePinType.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidSourcePinType.java new file mode 100644 index 00000000..2a02fb05 --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/EidSourcePinType.java @@ -0,0 +1,55 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. + */ + +package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; + +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPvpAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; + +@Deprecated +@PvpMetadata +public class EidSourcePinType implements IPvpAttributeBuilder { + + @Override + public String getName() { + return EID_SOURCE_PIN_TYPE_NAME; + } + + @Override + public ATT build(final IspConfiguration oaParam, final IAuthData authData, + final IAttributeGenerator g) throws AttributeBuilderException { + + if (authData.isBaseIdTransferRestrication()) { + throw new UnavailableAttributeException(EID_SOURCE_PIN_TYPE_NAME); + } else { + return g.buildStringAttribute(EID_SOURCE_PIN_TYPE_FRIENDLY_NAME, EID_SOURCE_PIN_TYPE_NAME, + authData.getIdentificationType()); + } + } + + @Override + public ATT buildEmpty(final IAttributeGenerator g) { + return g.buildEmptyAttribute(EID_SOURCE_PIN_TYPE_FRIENDLY_NAME, EID_SOURCE_PIN_TYPE_NAME); + } + +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/GivenNameAttributeBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/GivenNameAttributeBuilder.java index 87512b03..bbd7a06c 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/GivenNameAttributeBuilder.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/GivenNameAttributeBuilder.java @@ -1,60 +1,54 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. + */ -import org.apache.commons.lang3.StringUtils; +package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.api.idp.IPvpAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; +import org.apache.commons.lang3.StringUtils; + +@PvpMetadata +public class GivenNameAttributeBuilder implements IPvpAttributeBuilder { -@PVPMETADATA -public class GivenNameAttributeBuilder implements IPVPAttributeBuilder { + @Override + public String getName() { + return GIVEN_NAME_NAME; + } - @Override - public String getName() { - return GIVEN_NAME_NAME; - } + @Override + public ATT build(final IspConfiguration oaParam, final IAuthData authData, + final IAttributeGenerator g) throws AttributeBuilderException { + if (StringUtils.isNotEmpty(authData.getGivenName())) { + return g.buildStringAttribute(GIVEN_NAME_FRIENDLY_NAME, GIVEN_NAME_NAME, + authData.getGivenName()); + } else { + throw new UnavailableAttributeException(GIVEN_NAME_NAME); + } + } - @Override - public ATT build(ISPConfiguration oaParam, IAuthData authData, - IAttributeGenerator g) throws AttributeBuilderException { - if (StringUtils.isNotEmpty(authData.getGivenName())) - return g.buildStringAttribute(GIVEN_NAME_FRIENDLY_NAME, GIVEN_NAME_NAME, authData.getGivenName()); - else - throw new UnavailableAttributeException(GIVEN_NAME_NAME); - } - - @Override - public ATT buildEmpty(IAttributeGenerator g) { - return g.buildEmptyAttribute(GIVEN_NAME_FRIENDLY_NAME, GIVEN_NAME_NAME); - } + @Override + public ATT buildEmpty(final IAttributeGenerator g) { + return g.buildEmptyAttribute(GIVEN_NAME_FRIENDLY_NAME, GIVEN_NAME_NAME); + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/PVPMETADATA.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/PVPMETADATA.java deleted file mode 100644 index 81ad2126..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/PVPMETADATA.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; - -import java.lang.annotation.Retention; - -@Retention(java.lang.annotation.RetentionPolicy.RUNTIME) -public @interface PVPMETADATA { - -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/PVPVersionAttributeBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/PVPVersionAttributeBuilder.java deleted file mode 100644 index 38377641..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/PVPVersionAttributeBuilder.java +++ /dev/null @@ -1,51 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; - -import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; - -@PVPMETADATA -public class PVPVersionAttributeBuilder implements IPVPAttributeBuilder { - - public String getName() { - return PVP_VERSION_NAME; - } - - public ATT build(ISPConfiguration oaParam, IAuthData authData, - IAttributeGenerator g) throws AttributeBuilderException { - return g.buildStringAttribute(PVP_VERSION_FRIENDLY_NAME, PVP_VERSION_NAME, PVP_VERSION_2_1); - } - - public ATT buildEmpty(IAttributeGenerator g) { - return g.buildEmptyAttribute(PVP_VERSION_FRIENDLY_NAME, PVP_VERSION_NAME); - } - -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/PrincipalNameAttributeBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/PrincipalNameAttributeBuilder.java index d753550e..bbe9b741 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/PrincipalNameAttributeBuilder.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/PrincipalNameAttributeBuilder.java @@ -1,60 +1,54 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ -import org.apache.commons.lang3.StringUtils; +package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.api.idp.IPvpAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; +import org.apache.commons.lang3.StringUtils; + +@PvpMetadata +public class PrincipalNameAttributeBuilder implements IPvpAttributeBuilder { + + @Override + public String getName() { + return PRINCIPAL_NAME_NAME; + } + + @Override + public ATT build(final IspConfiguration oaParam, final IAuthData authData, + final IAttributeGenerator g) throws AttributeBuilderException { + if (StringUtils.isNotEmpty(authData.getFamilyName())) { + return g.buildStringAttribute(PRINCIPAL_NAME_FRIENDLY_NAME, PRINCIPAL_NAME_NAME, + authData.getFamilyName()); + } else { + throw new UnavailableAttributeException(PRINCIPAL_NAME_NAME); + } + } + + @Override + public ATT buildEmpty(final IAttributeGenerator g) { + return g.buildEmptyAttribute(PRINCIPAL_NAME_FRIENDLY_NAME, PRINCIPAL_NAME_NAME); + } -@PVPMETADATA -public class PrincipalNameAttributeBuilder implements IPVPAttributeBuilder { - - @Override - public String getName() { - return PRINCIPAL_NAME_NAME; - } - - @Override - public ATT build(ISPConfiguration oaParam, IAuthData authData, - IAttributeGenerator g) throws AttributeBuilderException { - if (StringUtils.isNotEmpty(authData.getFamilyName())) - return g.buildStringAttribute(PRINCIPAL_NAME_FRIENDLY_NAME, PRINCIPAL_NAME_NAME, authData.getFamilyName()); - else - throw new UnavailableAttributeException(PRINCIPAL_NAME_NAME); - } - - @Override - public ATT buildEmpty(IAttributeGenerator g) { - return g.buildEmptyAttribute(PRINCIPAL_NAME_FRIENDLY_NAME, PRINCIPAL_NAME_NAME); - } - } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/PvpMetadata.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/PvpMetadata.java new file mode 100644 index 00000000..6d1c40f9 --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/PvpMetadata.java @@ -0,0 +1,27 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; + +import java.lang.annotation.Retention; + +@Retention(java.lang.annotation.RetentionPolicy.RUNTIME) +public @interface PvpMetadata { + +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/PvpVersionAttributeBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/PvpVersionAttributeBuilder.java new file mode 100644 index 00000000..5ff68721 --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/PvpVersionAttributeBuilder.java @@ -0,0 +1,47 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; + +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPvpAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; + +@PvpMetadata +public class PvpVersionAttributeBuilder implements IPvpAttributeBuilder { + + @Override + public String getName() { + return PVP_VERSION_NAME; + } + + @Override + public ATT build(final IspConfiguration oaParam, final IAuthData authData, + final IAttributeGenerator g) throws AttributeBuilderException { + return g.buildStringAttribute(PVP_VERSION_FRIENDLY_NAME, PVP_VERSION_NAME, PVP_VERSION_2_1); + } + + @Override + public ATT buildEmpty(final IAttributeGenerator g) { + return g.buildEmptyAttribute(PVP_VERSION_FRIENDLY_NAME, PVP_VERSION_NAME); + } + +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SPCountryCodeAttributeBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SPCountryCodeAttributeBuilder.java deleted file mode 100644 index 9a365eb3..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SPCountryCodeAttributeBuilder.java +++ /dev/null @@ -1,59 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; - -import at.gv.egiz.eaaf.core.api.data.ExtendedPVPAttributeDefinitions; -import at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder; -import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; - -public class SPCountryCodeAttributeBuilder implements IAttributeBuilder, ExtendedPVPAttributeDefinitions { - - @Override - public String getName() { - return SP_COUNTRYCODE_NAME; - } - - @Override - public ATT build(ISPConfiguration oaParam, IAuthData authData, IAttributeGenerator g) - throws AttributeBuilderException { - //this attribute can not generated yet - return null; -// return g.buildStringAttribute( -// SP_COUNTRYCODE_FRIENDLY_NAME, -// SP_COUNTRYCODE_NAME, -// oaParam.getFriendlyName()); - - } - - @Override - public ATT buildEmpty(IAttributeGenerator g) { - return g.buildEmptyAttribute(SP_COUNTRYCODE_FRIENDLY_NAME, SP_COUNTRYCODE_NAME); - - } - -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SPFriendlyNameAttributeBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SPFriendlyNameAttributeBuilder.java deleted file mode 100644 index 2062f35b..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SPFriendlyNameAttributeBuilder.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; - -import at.gv.egiz.eaaf.core.api.data.ExtendedPVPAttributeDefinitions; -import at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder; -import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; - -public class SPFriendlyNameAttributeBuilder implements IAttributeBuilder, ExtendedPVPAttributeDefinitions { - - @Override - public String getName() { - return SP_FRIENDLYNAME_NAME; - } - - @Override - public ATT build(ISPConfiguration oaParam, IAuthData authData, IAttributeGenerator g) - throws AttributeBuilderException { - return g.buildStringAttribute( - SP_FRIENDLYNAME_FRIENDLY_NAME, - SP_FRIENDLYNAME_NAME, - oaParam.getFriendlyName()); - - } - - @Override - public ATT buildEmpty(IAttributeGenerator g) { - return g.buildEmptyAttribute(SP_FRIENDLYNAME_FRIENDLY_NAME, SP_FRIENDLYNAME_NAME); - - } - -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SPUniqueIdAttributeBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SPUniqueIdAttributeBuilder.java deleted file mode 100644 index bac2ec24..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SPUniqueIdAttributeBuilder.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; - -import at.gv.egiz.eaaf.core.api.data.ExtendedPVPAttributeDefinitions; -import at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder; -import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; - -public class SPUniqueIdAttributeBuilder implements IAttributeBuilder, ExtendedPVPAttributeDefinitions { - - @Override - public String getName() { - return SP_UNIQUEID_NAME; - } - - @Override - public ATT build(ISPConfiguration oaParam, IAuthData authData, IAttributeGenerator g) - throws AttributeBuilderException { - return g.buildStringAttribute( - SP_UNIQUEID_FRIENDLY_NAME, - SP_UNIQUEID_NAME, - oaParam.getUniqueIdentifier()); - - } - - @Override - public ATT buildEmpty(IAttributeGenerator g) { - return g.buildEmptyAttribute(SP_UNIQUEID_FRIENDLY_NAME, SP_UNIQUEID_NAME); - - } - -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SPUsesMandates.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SPUsesMandates.java deleted file mode 100644 index 7ad6cb09..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SPUsesMandates.java +++ /dev/null @@ -1,55 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; - -import at.gv.egiz.eaaf.core.api.data.ExtendedPVPAttributeDefinitions; -import at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder; -import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; - -public class SPUsesMandates implements IAttributeBuilder, ExtendedPVPAttributeDefinitions { - - @Override - public String getName() { - return SP_USESMANDATES_NAME; - } - - @Override - public ATT build(ISPConfiguration oaParam, IAuthData authData, IAttributeGenerator g) - throws AttributeBuilderException { - //this attribute can not generated yet - return null; - - } - - @Override - public ATT buildEmpty(IAttributeGenerator g) { - return g.buildEmptyAttribute(SP_USESMANDATES_FRIENDLY_NAME, SP_USESMANDATES_NAME); - - } - -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SpCountryCodeAttributeBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SpCountryCodeAttributeBuilder.java new file mode 100644 index 00000000..86cb1dcc --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SpCountryCodeAttributeBuilder.java @@ -0,0 +1,55 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; + +import at.gv.egiz.eaaf.core.api.data.ExtendedPVPAttributeDefinitions; +import at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; + +public class SpCountryCodeAttributeBuilder + implements IAttributeBuilder, ExtendedPVPAttributeDefinitions { + + @Override + public String getName() { + return SP_COUNTRYCODE_NAME; + } + + @Override + public ATT build(final IspConfiguration oaParam, final IAuthData authData, final IAttributeGenerator g) + throws AttributeBuilderException { + // this attribute can not generated yet + return null; + // return g.buildStringAttribute( + // SP_COUNTRYCODE_FRIENDLY_NAME, + // SP_COUNTRYCODE_NAME, + // oaParam.getFriendlyName()); + + } + + @Override + public ATT buildEmpty(final IAttributeGenerator g) { + return g.buildEmptyAttribute(SP_COUNTRYCODE_FRIENDLY_NAME, SP_COUNTRYCODE_NAME); + + } + +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SpFriendlyNameAttributeBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SpFriendlyNameAttributeBuilder.java new file mode 100644 index 00000000..4b905690 --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SpFriendlyNameAttributeBuilder.java @@ -0,0 +1,51 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; + +import at.gv.egiz.eaaf.core.api.data.ExtendedPVPAttributeDefinitions; +import at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; + +public class SpFriendlyNameAttributeBuilder + implements IAttributeBuilder, ExtendedPVPAttributeDefinitions { + + @Override + public String getName() { + return SP_FRIENDLYNAME_NAME; + } + + @Override + public ATT build(final IspConfiguration oaParam, final IAuthData authData, final IAttributeGenerator g) + throws AttributeBuilderException { + return g.buildStringAttribute(SP_FRIENDLYNAME_FRIENDLY_NAME, SP_FRIENDLYNAME_NAME, + oaParam.getFriendlyName()); + + } + + @Override + public ATT buildEmpty(final IAttributeGenerator g) { + return g.buildEmptyAttribute(SP_FRIENDLYNAME_FRIENDLY_NAME, SP_FRIENDLYNAME_NAME); + + } + +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SpUniqueIdAttributeBuilder.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SpUniqueIdAttributeBuilder.java new file mode 100644 index 00000000..47e5e8ce --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SpUniqueIdAttributeBuilder.java @@ -0,0 +1,51 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; + +import at.gv.egiz.eaaf.core.api.data.ExtendedPVPAttributeDefinitions; +import at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; + +public class SpUniqueIdAttributeBuilder + implements IAttributeBuilder, ExtendedPVPAttributeDefinitions { + + @Override + public String getName() { + return SP_UNIQUEID_NAME; + } + + @Override + public ATT build(final IspConfiguration oaParam, final IAuthData authData, final IAttributeGenerator g) + throws AttributeBuilderException { + return g.buildStringAttribute(SP_UNIQUEID_FRIENDLY_NAME, SP_UNIQUEID_NAME, + oaParam.getUniqueIdentifier()); + + } + + @Override + public ATT buildEmpty(final IAttributeGenerator g) { + return g.buildEmptyAttribute(SP_UNIQUEID_FRIENDLY_NAME, SP_UNIQUEID_NAME); + + } + +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SpUsesMandates.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SpUsesMandates.java new file mode 100644 index 00000000..ce717862 --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/builder/attributes/SpUsesMandates.java @@ -0,0 +1,50 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.impl.idp.builder.attributes; + +import at.gv.egiz.eaaf.core.api.data.ExtendedPVPAttributeDefinitions; +import at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; + +public class SpUsesMandates implements IAttributeBuilder, ExtendedPVPAttributeDefinitions { + + @Override + public String getName() { + return SP_USESMANDATES_NAME; + } + + @Override + public ATT build(final IspConfiguration oaParam, final IAuthData authData, final IAttributeGenerator g) + throws AttributeBuilderException { + // this attribute can not generated yet + return null; + + } + + @Override + public ATT buildEmpty(final IAttributeGenerator g) { + return g.buildEmptyAttribute(SP_USESMANDATES_FRIENDLY_NAME, SP_USESMANDATES_NAME); + + } + +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/conf/AbstractConfigurationImpl.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/conf/AbstractConfigurationImpl.java index 55662326..e661a2a8 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/conf/AbstractConfigurationImpl.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/conf/AbstractConfigurationImpl.java @@ -1,29 +1,22 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.conf; import java.io.File; @@ -34,201 +27,215 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.Map; import java.util.Properties; - +import at.gv.egiz.eaaf.core.api.idp.IExtendedConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; +import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import at.gv.egiz.eaaf.core.api.idp.IExtendedConfiguration; -import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; -import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; - public abstract class AbstractConfigurationImpl implements IExtendedConfiguration { - private static final Logger log = LoggerFactory.getLogger(AbstractConfigurationImpl.class); - - private static final String URI_SCHEME_CLASSPATH = "classpath"; - private static final String URI_SCHEME_FILESYSTEM = "file"; - - private final URI internalConfigPath; - private final URI configRootDirectory; - private final Properties properties; - - public AbstractConfigurationImpl(final String configPath) throws EAAFConfigurationException { - InputStream is = null; - try { - log.debug("Starting EAAFCore initialization process .... "); - - if (StringUtils.isEmpty(configPath)) { - log.debug("Primary configuration is empty. Search for backup configuration .... "); - final String backupConfigPath = getBackupConfigPath(); - if (StringUtils.isEmpty(backupConfigPath)) { - log.error("No configuration file found."); - throw new EAAFConfigurationException("config.01", null); - - } - - internalConfigPath = new URI(getBackupConfigPath()); - - } else - internalConfigPath = new URI(configPath); - - log.info("Load EAAFCore configuration from " + internalConfigPath); - - - //extract configuration root directory - //TODO: check if it works with classpath - final File propertiesFile = new File(internalConfigPath); - if (!propertiesFile.exists()) { - log.error("Configuration file: " + internalConfigPath + " is NOT found on filesystem"); - throw new EAAFConfigurationException("config.18", null); - - } - - final String configDir = propertiesFile.getParent(); - configRootDirectory = new File(configDir).toURI(); - log.debug("Set EAAFCore configuration root directory to " + configRootDirectory.toString()); - - - //get input stream from configuration path - if (internalConfigPath.getScheme().equals(URI_SCHEME_FILESYSTEM)) { - log.trace("Load config from filesystem"); - is = new FileInputStream(propertiesFile); - - } else if (internalConfigPath.getScheme().equals(URI_SCHEME_CLASSPATH)) { - log.trace("Load config from classpath"); - is = this.getClass().getResourceAsStream(internalConfigPath.toString()); - - } else { - log.error("Can not load EAAFCore configuration. Unsupported prefix! (Only 'file:' and 'classpath:') "); - throw new EAAFConfigurationException("config.24", new Object[] {internalConfigPath, "'file:'"}); - - } - - if (is == null) { - log.error("Can NOT load EAAFCore configuration from file " + internalConfigPath.toString()); - throw new EAAFConfigurationException("config.03", - new Object[] {internalConfigPath.toString()}); - - } - - - //load EAAF core configuration into properties object - properties = new Properties(); - properties.load(is); - - log.info("EAAFCore configuration loaded"); - - } catch (URISyntaxException | IOException e) { - log.error("Can not parse configuration path " + configPath + " or " + getBackupConfigPath()); - throw new EAAFConfigurationException("config.03", new Object[]{configPath + " or " + getBackupConfigPath()}, e); - - } finally { - if (is != null) { - try { - is.close(); - - } catch (final IOException e) { - log.warn("Can not close inputstream from configuration loader!"); - - } - } - } - - } - - @Override - public String getBasicConfiguration(String key) { - if (StringUtils.isNotEmpty(key)) { - final String value = properties.getProperty(addPrefixToKey(key)); - if (value != null) - return value.trim(); - } - - return null; - } - - @Override - public String getBasicConfiguration(String key, String defaultValue) { - if (StringUtils.isNotEmpty(key)) { - final String value = properties.getProperty(addPrefixToKey(key), defaultValue); - if (value != null) - return value.trim(); - } - - return defaultValue; - } - - - @Override - public Boolean getBasicConfigurationBoolean(String key) { - final String value = getBasicConfiguration(key); - if (value != null) - return Boolean.parseBoolean(value); - else - return null; - - } - - - @Override - public boolean getBasicConfigurationBoolean(String key, boolean defaultValue) { - final Boolean result = getBasicConfigurationBoolean(key); - if (result != null) - return result; - else - return defaultValue; - - } - - @Override - public Map getBasicConfigurationWithPrefix(String prefix) { - return KeyValueUtils.getSubSetWithPrefix(KeyValueUtils.convertPropertiesToMap(properties), addPrefixToKey(prefix)); - - } - - @Override - public Properties getFullConfigurationProperties() { - return properties; - - } - - @Override - public URI getConfigurationRootDirectory() { - return configRootDirectory; - - } - - @Override - public URI getConfigurationFilePath() { - return internalConfigPath; - - } - - /** - * Get the path to backup configuration - * - * @return A filepath file: or a classpath classpath: - */ - abstract protected String getBackupConfigPath(); - - /** - * Get a specific configuration-key prefix for this software implementation - * - * @return - */ - abstract public String getApplicationSpecificKeyPrefix(); - - - private String addPrefixToKey(String key) { - if (StringUtils.isNotEmpty(getApplicationSpecificKeyPrefix())) { - if (getApplicationSpecificKeyPrefix().endsWith(KeyValueUtils.KEY_DELIMITER)) - return getApplicationSpecificKeyPrefix() + key; - else - return getApplicationSpecificKeyPrefix() + KeyValueUtils.KEY_DELIMITER + key; - - } - - return key; - - } + private static final Logger log = LoggerFactory.getLogger(AbstractConfigurationImpl.class); + + private static final String URI_SCHEME_CLASSPATH = "classpath"; + private static final String URI_SCHEME_FILESYSTEM = "file"; + + private final URI internalConfigPath; + private final URI configRootDirectory; + private final Properties properties; + + /** + * Basic configuration loader implementation. + * + * @param configPath Path to configuration + * @throws EaafConfigurationException In case of a configuration error + */ + public AbstractConfigurationImpl(final String configPath) throws EaafConfigurationException { + InputStream is = null; + try { + log.debug("Starting EAAFCore initialization process .... "); + + if (StringUtils.isEmpty(configPath)) { + log.debug("Primary configuration is empty. Search for backup configuration .... "); + final String backupConfigPath = getBackupConfigPath(); + if (StringUtils.isEmpty(backupConfigPath)) { + log.error("No configuration file found."); + throw new EaafConfigurationException("config.01", null); + + } + + internalConfigPath = new URI(getBackupConfigPath()); + + } else { + internalConfigPath = new URI(configPath); + } + + log.info("Load EAAFCore configuration from " + internalConfigPath); + + + // extract configuration root directory + // TODO: check if it works with classpath + final File propertiesFile = new File(internalConfigPath); + if (!propertiesFile.exists()) { + log.error("Configuration file: " + internalConfigPath + " is NOT found on filesystem"); + throw new EaafConfigurationException("config.18", null); + + } + + final String configDir = propertiesFile.getParent(); + configRootDirectory = new File(configDir).toURI(); + log.debug("Set EAAFCore configuration root directory to " + configRootDirectory.toString()); + + + // get input stream from configuration path + if (internalConfigPath.getScheme().equals(URI_SCHEME_FILESYSTEM)) { + log.trace("Load config from filesystem"); + is = new FileInputStream(propertiesFile); + + } else if (internalConfigPath.getScheme().equals(URI_SCHEME_CLASSPATH)) { + log.trace("Load config from classpath"); + is = this.getClass().getResourceAsStream(internalConfigPath.toString()); + + } else { + log.error( + "Can not load EAAFCore configuration. Unsupported prefix! (Only 'file:' and 'classpath:') "); + throw new EaafConfigurationException("config.24", + new Object[] {internalConfigPath, "'file:'"}); + + } + + if (is == null) { + log.error("Can NOT load EAAFCore configuration from file " + internalConfigPath.toString()); + throw new EaafConfigurationException("config.03", + new Object[] {internalConfigPath.toString()}); + + } + + + // load EAAF core configuration into properties object + properties = new Properties(); + properties.load(is); + + log.info("EAAFCore configuration loaded"); + + } catch (URISyntaxException | IOException e) { + log.error("Can not parse configuration path " + configPath + " or " + getBackupConfigPath()); + throw new EaafConfigurationException("config.03", + new Object[] {configPath + " or " + getBackupConfigPath()}, e); + + } finally { + if (is != null) { + try { + is.close(); + + } catch (final IOException e) { + log.warn("Can not close inputstream from configuration loader!"); + + } + } + } + + } + + @Override + public String getBasicConfiguration(final String key) { + if (StringUtils.isNotEmpty(key)) { + final String value = properties.getProperty(addPrefixToKey(key)); + if (value != null) { + return value.trim(); + } + } + + return null; + } + + @Override + public String getBasicConfiguration(final String key, final String defaultValue) { + if (StringUtils.isNotEmpty(key)) { + final String value = properties.getProperty(addPrefixToKey(key), defaultValue); + if (value != null) { + return value.trim(); + } + } + + return defaultValue; + } + + + @Override + public boolean getBasicConfigurationBoolean(final String key) { + final String value = getBasicConfiguration(key); + if (value != null) { + return Boolean.parseBoolean(value); + } else { + return false; + } + + } + + + @Override + public boolean getBasicConfigurationBoolean(final String key, final boolean defaultValue) { + final Boolean result = getBasicConfigurationBoolean(key); + if (result != null) { + return result; + } else { + return defaultValue; + } + + } + + @Override + public Map getBasicConfigurationWithPrefix(final String prefix) { + return KeyValueUtils.getSubSetWithPrefix(KeyValueUtils.convertPropertiesToMap(properties), + addPrefixToKey(prefix)); + + } + + @Override + public Properties getFullConfigurationProperties() { + return properties; + + } + + @Override + public URI getConfigurationRootDirectory() { + return configRootDirectory; + + } + + @Override + public URI getConfigurationFilePath() { + return internalConfigPath; + + } + + /** + * Get the path to backup configuration. + * + * @return A filepath file: or a classpath classpath: + */ + protected abstract String getBackupConfigPath(); + + /** + * Get a specific configuration-key prefix for this software implementation. + * + * @return + */ + public abstract String getApplicationSpecificKeyPrefix(); + + + private String addPrefixToKey(final String key) { + if (StringUtils.isNotEmpty(getApplicationSpecificKeyPrefix())) { + if (getApplicationSpecificKeyPrefix().endsWith(KeyValueUtils.KEY_DELIMITER)) { + return getApplicationSpecificKeyPrefix() + key; + } else { + return getApplicationSpecificKeyPrefix() + KeyValueUtils.KEY_DELIMITER + key; + } + + } + + return key; + + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/conf/AbstractSpringBootConfigurationImpl.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/conf/AbstractSpringBootConfigurationImpl.java index dd13b534..3a6cc67d 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/conf/AbstractSpringBootConfigurationImpl.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/conf/AbstractSpringBootConfigurationImpl.java @@ -1,29 +1,22 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.conf; import java.net.URI; @@ -32,9 +25,10 @@ import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; - import javax.annotation.PostConstruct; - +import at.gv.egiz.eaaf.core.api.idp.IConfigurationWithSP; +import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; +import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -45,175 +39,176 @@ import org.springframework.core.env.EnumerablePropertySource; import org.springframework.core.env.Environment; import org.springframework.core.env.PropertySource; -import at.gv.egiz.eaaf.core.api.idp.IConfigurationWithSP; -import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; -import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; - public abstract class AbstractSpringBootConfigurationImpl implements IConfigurationWithSP { - private static final Logger log = LoggerFactory.getLogger(AbstractSpringBootConfigurationImpl.class); - - @Autowired private Environment env; - - public static final String PROP_CONFIG_ROOT_DIR = "core.configRootDir"; - - @PostConstruct - private void initialize() throws EAAFConfigurationException { - if (getConfigurationRootDirectory() == null) { - throw new EAAFConfigurationException("config.08", new Object[] {addPrefixToKey(PROP_CONFIG_ROOT_DIR)}); - - } - - } - - @Override - public String getBasicConfiguration(String key) { - if (StringUtils.isNotEmpty(key)) { - final String value = env.getProperty(addPrefixToKey(key)); - if (value != null) - return value.trim(); - } - - return null; - } - - @Override - public String getBasicConfiguration(String key, String defaultValue) { - if (StringUtils.isNotEmpty(key)) { - final String value = env.getProperty(addPrefixToKey(key), defaultValue); - if (value != null) - return value.trim(); - } - - return defaultValue; - } - - @Override - public Map getBasicConfigurationWithPrefix(String prefix) { - final Map configProps = getPropertiesStartingWith((ConfigurableEnvironment) env, addPrefixToKey(prefix)); - return KeyValueUtils.removePrefixFromKeys(configProps, addPrefixToKey(prefix) + "."); - - - } - - @Override - public Boolean getBasicConfigurationBoolean(String key) { - final String value = getBasicConfiguration(key); - if (StringUtils.isNotEmpty(value)) - return Boolean.valueOf(value.trim()); - else - return null; - } - - @Override - public boolean getBasicConfigurationBoolean(String key, boolean defaultValue) { - final Boolean value = getBasicConfigurationBoolean(key); - if (value != null) - return value; - else - return defaultValue; - } - - @Override - public URI getConfigurationRootDirectory() { - try { - return new URI(env.getRequiredProperty(addPrefixToKey(PROP_CONFIG_ROOT_DIR))); - - } catch (IllegalStateException | URISyntaxException e) { - log.warn("ConfigRootDirectory is NOT set"); - return null; - - } - - } - - - /** - * Get the path to backup configuration - * - * @return A filepath file: or a classpath classpath: - */ - abstract protected String getBackupConfigPath(); - - /** - * Get a specific configuration-key prefix for this software implementation - * - * @return - */ - abstract public String getApplicationSpecificKeyPrefix(); - - - private String addPrefixToKey(String key) { - if (StringUtils.isNotEmpty(getApplicationSpecificKeyPrefix())) { - if (getApplicationSpecificKeyPrefix().endsWith(KeyValueUtils.KEY_DELIMITER)) - return getApplicationSpecificKeyPrefix() + key; - else - return getApplicationSpecificKeyPrefix() + KeyValueUtils.KEY_DELIMITER + key; - - } - - return key; - - } - - private static Map getPropertiesStartingWith( ConfigurableEnvironment aEnv, String aKeyPrefix ) { - final Map result = new HashMap<>(); - final Map map = getAllProperties(aEnv); - - for (final Entry entry : map.entrySet()) { - final String key = entry.getKey(); - - if ( key.startsWith( aKeyPrefix ) ) - { - result.put( key, (String) entry.getValue() ); - } - } - - return result; - } - - private static Map getAllProperties( ConfigurableEnvironment aEnv ) { - final Map result = new HashMap<>(); - aEnv.getPropertySources().forEach( ps -> addAll( result, getAllProperties( ps ) ) ); - return result; - - } - - private static Map getAllProperties( PropertySource aPropSource ) { - final Map result = new HashMap<>(); - - if ( aPropSource instanceof CompositePropertySource) - { - final CompositePropertySource cps = (CompositePropertySource) aPropSource; - cps.getPropertySources().forEach( ps -> addAll( result, getAllProperties( ps ) ) ); - return result; - } - - if ( aPropSource instanceof EnumerablePropertySource ) - { - final EnumerablePropertySource ps = (EnumerablePropertySource) aPropSource; - Arrays.asList( ps.getPropertyNames() ).forEach( key -> result.put( key, ps.getProperty( key ) ) ); - return result; - } - - // note: Most descendants of PropertySource are EnumerablePropertySource. There are some - // few others like JndiPropertySource or StubPropertySource - log.debug( "Given PropertySource is instanceof " + aPropSource.getClass().getName() - + " and cannot be iterated" ); - - return result; - - } - - private static void addAll( Map aBase, Map aToBeAdded ) - { - for (final Entry entry : aToBeAdded.entrySet()) - { - if ( aBase.containsKey( entry.getKey() ) ) - { - continue; - } - - aBase.put( entry.getKey(), entry.getValue() ); - } - } + private static final Logger log = + LoggerFactory.getLogger(AbstractSpringBootConfigurationImpl.class); + + @Autowired + private Environment env; + + public static final String PROP_CONFIG_ROOT_DIR = "core.configRootDir"; + + @PostConstruct + private void initialize() throws EaafConfigurationException { + if (getConfigurationRootDirectory() == null) { + throw new EaafConfigurationException("config.08", + new Object[] {addPrefixToKey(PROP_CONFIG_ROOT_DIR)}); + + } + + } + + @Override + public String getBasicConfiguration(final String key) { + if (StringUtils.isNotEmpty(key)) { + final String value = env.getProperty(addPrefixToKey(key)); + if (value != null) { + return value.trim(); + } + } + + return null; + } + + @Override + public String getBasicConfiguration(final String key, final String defaultValue) { + if (StringUtils.isNotEmpty(key)) { + final String value = env.getProperty(addPrefixToKey(key), defaultValue); + if (value != null) { + return value.trim(); + } + } + + return defaultValue; + } + + @Override + public Map getBasicConfigurationWithPrefix(final String prefix) { + final Map configProps = + getPropertiesStartingWith((ConfigurableEnvironment) env, addPrefixToKey(prefix)); + return KeyValueUtils.removePrefixFromKeys(configProps, addPrefixToKey(prefix) + "."); + + + } + + @Override + public boolean getBasicConfigurationBoolean(final String key) { + final String value = getBasicConfiguration(key); + if (StringUtils.isNotEmpty(value)) { + return Boolean.valueOf(value.trim()); + } else { + return false; + } + } + + @Override + public boolean getBasicConfigurationBoolean(final String key, final boolean defaultValue) { + final Boolean value = getBasicConfigurationBoolean(key); + if (value != null) { + return value; + } else { + return defaultValue; + } + } + + @Override + public URI getConfigurationRootDirectory() { + try { + return new URI(env.getRequiredProperty(addPrefixToKey(PROP_CONFIG_ROOT_DIR))); + + } catch (IllegalStateException | URISyntaxException e) { + log.warn("ConfigRootDirectory is NOT set"); + return null; + + } + + } + + + /** + * Get the path to backup configuration. + * + * @return A filepath file: or a classpath classpath: + */ + protected abstract String getBackupConfigPath(); + + /** + * Get a specific configuration-key prefix for this software implementation. + * + * @return + */ + public abstract String getApplicationSpecificKeyPrefix(); + + + private String addPrefixToKey(final String key) { + if (StringUtils.isNotEmpty(getApplicationSpecificKeyPrefix())) { + if (getApplicationSpecificKeyPrefix().endsWith(KeyValueUtils.KEY_DELIMITER)) { + return getApplicationSpecificKeyPrefix() + key; + } else { + return getApplicationSpecificKeyPrefix() + KeyValueUtils.KEY_DELIMITER + key; + } + + } + + return key; + + } + + private static Map getPropertiesStartingWith(final ConfigurableEnvironment aenv, + final String akeyPrefix) { + final Map result = new HashMap<>(); + final Map map = getAllProperties(aenv); + + for (final Entry entry : map.entrySet()) { + final String key = entry.getKey(); + + if (key.startsWith(akeyPrefix)) { + result.put(key, (String) entry.getValue()); + } + } + + return result; + } + + private static Map getAllProperties(final ConfigurableEnvironment aenv) { + final Map result = new HashMap<>(); + aenv.getPropertySources().forEach(ps -> addAll(result, getAllProperties(ps))); + return result; + + } + + private static Map getAllProperties(final PropertySource apropSource) { + final Map result = new HashMap<>(); + + if (apropSource instanceof CompositePropertySource) { + final CompositePropertySource cps = (CompositePropertySource) apropSource; + cps.getPropertySources().forEach(ps -> addAll(result, getAllProperties(ps))); + return result; + } + + if (apropSource instanceof EnumerablePropertySource) { + final EnumerablePropertySource ps = (EnumerablePropertySource) apropSource; + Arrays.asList(ps.getPropertyNames()).forEach(key -> result.put(key, ps.getProperty(key))); + return result; + } + + // note: Most descendants of PropertySource are EnumerablePropertySource. There are some + // few others like JndiPropertySource or StubPropertySource + log.debug("Given PropertySource is instanceof " + apropSource.getClass().getName() + + " and cannot be iterated"); + + return result; + + } + + private static void addAll(final Map abase, + final Map atoBeAdded) { + for (final Entry entry : atoBeAdded.entrySet()) { + if (abase.containsKey(entry.getKey())) { + continue; + } + + abase.put(entry.getKey(), entry.getValue()); + } + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/conf/SPConfigurationImpl.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/conf/SPConfigurationImpl.java deleted file mode 100644 index 1b99ce50..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/conf/SPConfigurationImpl.java +++ /dev/null @@ -1,191 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.conf; - -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import at.gv.egiz.eaaf.core.api.data.EAAFConfigConstants; -import at.gv.egiz.eaaf.core.api.data.EAAFConstants; -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; - -public class SPConfigurationImpl implements ISPConfiguration { - private static final long serialVersionUID = 688541755446463453L; - - private static final Logger log = LoggerFactory.getLogger(SPConfigurationImpl.class); - - private final Map spConfiguration; - private final List targetAreasWithNoInteralBaseIdRestriction; - private final List targetAreasWithNoBaseIdTransmissionRestriction; - - public SPConfigurationImpl(final Map spConfig, IConfiguration authConfig) { - this.spConfiguration = spConfig; - - //set oa specific restrictions - targetAreasWithNoInteralBaseIdRestriction = Collections.unmodifiableList( - KeyValueUtils.getListOfCSVValues( - authConfig.getBasicConfiguration( - CONFIG_KEY_RESTRICTIONS_BASEID_INTERNAL, - EAAFConstants.URN_PREFIX_CDID))); - - targetAreasWithNoBaseIdTransmissionRestriction = Collections.unmodifiableList( - KeyValueUtils.getListOfCSVValues( - authConfig.getBasicConfiguration( - CONFIG_KEY_RESTRICTIONS_BASEID_TRANSMISSION, - EAAFConstants.URN_PREFIX_CDID))); - - if (log.isTraceEnabled()) { - log.trace("Internal policy for OA: " + getUniqueIdentifier()); - for (String el : targetAreasWithNoInteralBaseIdRestriction) - log.trace(" Allow baseID processing for prefix " + el); - for (String el : targetAreasWithNoBaseIdTransmissionRestriction) - log.trace(" Allow baseID transfer for prefix " + el); - - } - } - - - @Override - public final Map getFullConfiguration() { - return this.spConfiguration; - - } - - @Override - public final String getConfigurationValue(String key) { - if (key == null) - return null; - else - return this.spConfiguration.get(key); - - } - - @Override - public final String getConfigurationValue(String key, String defaultValue) { - String value = getConfigurationValue(key); - if (value == null) - return defaultValue; - else - return value; - } - - - @Override - public final Boolean isConfigurationValue(String key) { - String value = getConfigurationValue(key); - if (value != null) { - return Boolean.parseBoolean(value); - - } - - return null; - } - - - @Override - public final boolean isConfigurationValue(String key, boolean defaultValue) { - String value = getConfigurationValue(key); - if (value != null) { - return Boolean.parseBoolean(value); - - } - - return defaultValue; - } - - @Override - public final boolean containsConfigurationKey(String key) { - if (key == null) - return false; - else - return this.spConfiguration.containsKey(key); - - } - - @Override - public String getUniqueIdentifier() { - return getConfigurationValue(EAAFConfigConstants.SERVICE_UNIQUEIDENTIFIER); - - } - - @Override - public boolean hasBaseIdInternalProcessingRestriction() { - return false; - - } - - @Override - public boolean hasBaseIdTransferRestriction() { - return true; - - } - - - @Override - public final List getTargetsWithNoBaseIdInternalProcessingRestriction() { - return this.targetAreasWithNoInteralBaseIdRestriction; - } - - - @Override - public final List getTargetsWithNoBaseIdTransferRestriction() { - return this.targetAreasWithNoBaseIdTransmissionRestriction; - } - - - @Override - public List getRequiredLoA() { - log.warn("Method not implemented: " + SPConfigurationImpl.class.getName() + " 'getRequiredLoA()'"); - return null; - } - - @Override - public String getLoAMatchingMode() { - log.warn("Method not implemented: " + SPConfigurationImpl.class.getName() + " 'getLoAMatchingMode()'"); - return null; - } - - @Override - public String getAreaSpecificTargetIdentifier() { - log.warn("Method not implemented: " + SPConfigurationImpl.class.getName() + " 'getAreaSpecificTargetIdentifier()'"); - return null; - } - - - @Override - public String getFriendlyName() { - log.warn("Method not implemented: " + SPConfigurationImpl.class.getName() + " 'getFriendlyName()'"); - return null; - } - -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/conf/SpConfigurationImpl.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/conf/SpConfigurationImpl.java new file mode 100644 index 00000000..07284cd3 --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/conf/SpConfigurationImpl.java @@ -0,0 +1,193 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.impl.idp.conf; + +import java.util.Collections; +import java.util.List; +import java.util.Map; +import at.gv.egiz.eaaf.core.api.data.EAAFConfigConstants; +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; +import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SpConfigurationImpl implements IspConfiguration { + private static final long serialVersionUID = 688541755446463453L; + + private static final Logger log = LoggerFactory.getLogger(SpConfigurationImpl.class); + + private final Map spConfiguration; + private final List targetAreasWithNoInteralBaseIdRestriction; + private final List targetAreasWithNoBaseIdTransmissionRestriction; + + /** + * Service-provider configuration holder. + * + * @param spConfig Key/value based configuration + * @param authConfig Basic application configuration + */ + public SpConfigurationImpl(final Map spConfig, final IConfiguration authConfig) { + this.spConfiguration = spConfig; + + // set oa specific restrictions + targetAreasWithNoInteralBaseIdRestriction = Collections + .unmodifiableList(KeyValueUtils.getListOfCsvValues(authConfig.getBasicConfiguration( + CONFIG_KEY_RESTRICTIONS_BASEID_INTERNAL, EAAFConstants.URN_PREFIX_CDID))); + + targetAreasWithNoBaseIdTransmissionRestriction = Collections + .unmodifiableList(KeyValueUtils.getListOfCsvValues(authConfig.getBasicConfiguration( + CONFIG_KEY_RESTRICTIONS_BASEID_TRANSMISSION, EAAFConstants.URN_PREFIX_CDID))); + + if (log.isTraceEnabled()) { + log.trace("Internal policy for OA: " + getUniqueIdentifier()); + for (final String el : targetAreasWithNoInteralBaseIdRestriction) { + log.trace(" Allow baseID processing for prefix " + el); + } + for (final String el : targetAreasWithNoBaseIdTransmissionRestriction) { + log.trace(" Allow baseID transfer for prefix " + el); + } + + } + } + + + @Override + public final Map getFullConfiguration() { + return this.spConfiguration; + + } + + @Override + public final String getConfigurationValue(final String key) { + if (key == null) { + return null; + } else { + return this.spConfiguration.get(key); + } + + } + + @Override + public final String getConfigurationValue(final String key, final String defaultValue) { + final String value = getConfigurationValue(key); + if (value == null) { + return defaultValue; + } else { + return value; + } + } + + + @Override + public final boolean isConfigurationValue(final String key) { + final String value = getConfigurationValue(key); + if (value != null) { + return Boolean.parseBoolean(value); + + } + + return false; + } + + + @Override + public final boolean isConfigurationValue(final String key, final boolean defaultValue) { + final String value = getConfigurationValue(key); + if (value != null) { + return Boolean.parseBoolean(value); + + } + + return defaultValue; + } + + @Override + public final boolean containsConfigurationKey(final String key) { + if (key == null) { + return false; + } else { + return this.spConfiguration.containsKey(key); + } + + } + + @Override + public String getUniqueIdentifier() { + return getConfigurationValue(EAAFConfigConstants.SERVICE_UNIQUEIDENTIFIER); + + } + + @Override + public boolean hasBaseIdInternalProcessingRestriction() { + return false; + + } + + @Override + public boolean hasBaseIdTransferRestriction() { + return true; + + } + + + @Override + public final List getTargetsWithNoBaseIdInternalProcessingRestriction() { + return this.targetAreasWithNoInteralBaseIdRestriction; + } + + + @Override + public final List getTargetsWithNoBaseIdTransferRestriction() { + return this.targetAreasWithNoBaseIdTransmissionRestriction; + } + + + @Override + public List getRequiredLoA() { + log.warn( + "Method not implemented: " + SpConfigurationImpl.class.getName() + " 'getRequiredLoA()'"); + return null; + } + + @Override + public String getLoAMatchingMode() { + log.warn("Method not implemented: " + SpConfigurationImpl.class.getName() + + " 'getLoAMatchingMode()'"); + return null; + } + + @Override + public String getAreaSpecificTargetIdentifier() { + log.warn("Method not implemented: " + SpConfigurationImpl.class.getName() + + " 'getAreaSpecificTargetIdentifier()'"); + return null; + } + + + @Override + public String getFriendlyName() { + log.warn( + "Method not implemented: " + SpConfigurationImpl.class.getName() + " 'getFriendlyName()'"); + return null; + } + +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/AbstractController.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/AbstractController.java index 4505163d..7c42f506 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/AbstractController.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/AbstractController.java @@ -1,43 +1,27 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.controller; import java.io.IOException; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.text.StringEscapeUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.web.bind.annotation.ExceptionHandler; - import at.gv.egiz.components.eventlog.api.EventConstants; import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.IStatusMessenger; @@ -47,165 +31,215 @@ import at.gv.egiz.eaaf.core.api.idp.IConfigurationWithSP; import at.gv.egiz.eaaf.core.api.idp.auth.services.IProtocolAuthenticationService; import at.gv.egiz.eaaf.core.api.logging.IRevisionLogger; import at.gv.egiz.eaaf.core.api.storage.ITransactionStorage; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.exceptions.PendingReqIdValidationException; import at.gv.egiz.eaaf.core.exceptions.ProcessExecutionException; import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; import at.gv.egiz.eaaf.core.impl.utils.Random; import at.gv.egiz.eaaf.core.impl.utils.ServletUtils; +import org.apache.commons.text.StringEscapeUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.web.bind.annotation.ExceptionHandler; /** + * Basic application controller that implements core error-handling. + * * @author tlenz * */ public abstract class AbstractController { - private static final Logger log = LoggerFactory.getLogger(AbstractController.class); - - @Autowired(required=true) protected IProtocolAuthenticationService protAuthService; - @Autowired(required=true) protected ApplicationContext applicationContext; - @Autowired(required=true) protected IConfigurationWithSP authConfig; - @Autowired(required=true) protected ITransactionStorage transactionStorage; - @Autowired(required=true) protected IStatusMessenger statusMessager; - - @Autowired protected IRevisionLogger revisionsLogger; - - @ExceptionHandler({EAAFException.class}) - public void EAAFExceptionHandler(final HttpServletRequest req, final HttpServletResponse resp, final Exception e) throws IOException { - try { - protAuthService.handleErrorNoRedirect(e, req, resp, true); - - } catch (final EAAFException e1) { - log.warn("Can NOT handle an 'EAAFException'. Forwarding to generic error ... ", e); - IOExceptionHandler(resp, e); - - } - - } - - @ExceptionHandler({Exception.class}) - public void GenericExceptionHandler(final HttpServletResponse resp, final Exception exception) throws IOException { - log.error("Internel Server Error." , exception); - resp.setContentType(EAAFConstants.CONTENTTYPE_HTML_UTF8); - resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error!" + - "(Errorcode=9199" - +" | Description=" - + StringEscapeUtils.escapeHtml4(StringEscapeUtils.escapeEcmaScript(exception.getMessage())) - + ")"); - return; - - } - - @ExceptionHandler({IOException.class}) - public void IOExceptionHandler(final HttpServletResponse resp, final Throwable exception) { - log.error("Internel Server Error." , exception); - resp.setContentType(EAAFConstants.CONTENTTYPE_HTML_UTF8); - resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - return; - - } - - protected void handleError(final String errorMessage, final Throwable exceptionThrown, - final HttpServletRequest req, final HttpServletResponse resp, IRequest pendingReq) throws IOException, EAAFException { - - Throwable loggedException = null; - final Throwable extractedException = extractOriginalExceptionFromProcessException(exceptionThrown); - - //extract pendingRequestID and originalException if it was a TaskExecutionException - if (extractedException instanceof TaskExecutionException) { - //set original exception - loggedException = ((TaskExecutionException) extractedException).getOriginalException(); - - } else if (exceptionThrown instanceof PendingReqIdValidationException) { - log.trace("Find pendingRequestId validation exception. Looking for invalid pending-request ... "); - if (((PendingReqIdValidationException) exceptionThrown).getInvalidPendingReq() != null) - pendingReq = ((PendingReqIdValidationException) exceptionThrown).getInvalidPendingReq(); - - } - - //use TaskExecutionException directly, if no Original Exeception is included - if (loggedException == null) - loggedException = exceptionThrown; - - try { - //switch to protocol-finalize method to generate a protocol-specific error message - - //log error directly in debug mode - if (log.isDebugEnabled()) - log.warn(loggedException.getMessage(), loggedException); - - - //put exception into transaction store for redirect - final String key = Random.nextLongRandom(); - if (pendingReq != null) { - revisionsLogger.logEvent(pendingReq, EventConstants.TRANSACTION_ERROR); - transactionStorage.put(key, - new ExceptionContainer(pendingReq, loggedException), -1); - - } else { - transactionStorage.put(key, - new ExceptionContainer(null, loggedException), -1); - - } - - //build up redirect URL - String redirectURL = null; - redirectURL = ServletUtils.getBaseUrl(req); - redirectURL += "/"+ProtocolFinalizationController.ENDPOINT_ERRORHANDLING - + "?" + EAAFConstants.PARAM_HTTP_ERROR_CODE + "=" + key; - - resp.setContentType("text/html"); - resp.setStatus(302); - - resp.addHeader("Location", redirectURL); - log.debug("REDIRECT TO: " + redirectURL); - - return; - - } catch (final Exception e) { - log.warn("Default error-handling FAILED. Exception can not be stored ....", e); - log.info("Switch to generic generic backup error-handling ... "); - protAuthService.handleErrorNoRedirect(loggedException, req, resp, true); - - } - - } - - - - - - /** - * Extracts a TaskExecutionException of a ProcessExecutionExeception Stacktrace. - * - * @param exception - * @return Return the latest TaskExecutionExecption if exists, otherwise the latest ProcessExecutionException - */ - private Throwable extractOriginalExceptionFromProcessException(final Throwable exception) { - Throwable exholder = exception; - TaskExecutionException taskExc = null; - - while(exholder != null - && exholder instanceof ProcessExecutionException) { - final ProcessExecutionException procExc = (ProcessExecutionException) exholder; - if (procExc.getCause() != null && - procExc.getCause() instanceof TaskExecutionException) { - taskExc = (TaskExecutionException) procExc.getCause(); - exholder = taskExc.getOriginalException(); - - } else - break; - - } - - if (taskExc == null) - return exholder; - - else - return taskExc; - } - - - + private static final Logger log = LoggerFactory.getLogger(AbstractController.class); + + @Autowired(required = true) + protected IProtocolAuthenticationService protAuthService; + @Autowired(required = true) + protected ApplicationContext applicationContext; + @Autowired(required = true) + protected IConfigurationWithSP authConfig; + @Autowired(required = true) + protected ITransactionStorage transactionStorage; + @Autowired(required = true) + protected IStatusMessenger statusMessager; + + @Autowired + protected IRevisionLogger revisionsLogger; + + /** + * EAAF framework exception handler. + * + *

+ *This handler start a protocol-specific error handling. + *

+ * + * @param req http request + * @param resp http response + * @param e exception + * @throws IOException in case of an exception handling error + */ + @ExceptionHandler({EaafException.class}) + public void eaafExceptionHandler(final HttpServletRequest req, final HttpServletResponse resp, + final Exception e) throws IOException { + try { + protAuthService.handleErrorNoRedirect(e, req, resp, true); + + } catch (final EaafException e1) { + log.warn("Can NOT handle an 'EAAFException'. Forwarding to generic error ... ", e); + ioExceptionHandler(resp, e); + + } + + } + + /** + * Generic exception handler. + * + *

+ * This handler wrote an internal server error into http response + *

+ * + * @param resp http response + * @param exception exception + * @throws IOException In case of an internal error. + */ + @ExceptionHandler({Exception.class}) + public void genericExceptionHandler(final HttpServletResponse resp, final Exception exception) + throws IOException { + log.error("Internel Server Error.", exception); + resp.setContentType(EAAFConstants.CONTENTTYPE_HTML_UTF8); + resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error!" + + "(Errorcode=9199" + " | Description=" + + StringEscapeUtils.escapeHtml4(StringEscapeUtils.escapeEcmaScript(exception.getMessage())) + + ")"); + return; + + } + + /** + * Generic exception handler. + * + *

+ * This handler wrote an internal server error into http response + *

+ * + * @param resp http response + * @param exception exception + */ + @ExceptionHandler({IOException.class}) + public void ioExceptionHandler(final HttpServletResponse resp, final Throwable exception) { + log.error("Internel Server Error.", exception); + resp.setContentType(EAAFConstants.CONTENTTYPE_HTML_UTF8); + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return; + + } + + protected void handleError(final String errorMessage, final Throwable exceptionThrown, + final HttpServletRequest req, final HttpServletResponse resp, IRequest pendingReq) + throws IOException, EaafException { + + Throwable loggedException = null; + final Throwable extractedException = + extractOriginalExceptionFromProcessException(exceptionThrown); + + // extract pendingRequestID and originalException if it was a TaskExecutionException + if (extractedException instanceof TaskExecutionException) { + // set original exception + loggedException = ((TaskExecutionException) extractedException).getOriginalException(); + + } else if (exceptionThrown instanceof PendingReqIdValidationException) { + log.trace( + "Find pendingRequestId validation exception. Looking for invalid pending-request ... "); + if (((PendingReqIdValidationException) exceptionThrown).getInvalidPendingReq() != null) { + pendingReq = ((PendingReqIdValidationException) exceptionThrown).getInvalidPendingReq(); + } + + } + + // use TaskExecutionException directly, if no Original Exeception is included + if (loggedException == null) { + loggedException = exceptionThrown; + } + + try { + // switch to protocol-finalize method to generate a protocol-specific error message + + // log error directly in debug mode + if (log.isDebugEnabled()) { + log.warn(loggedException.getMessage(), loggedException); + } + + + // put exception into transaction store for redirect + final String key = Random.nextLongRandom(); + if (pendingReq != null) { + revisionsLogger.logEvent(pendingReq, EventConstants.TRANSACTION_ERROR); + transactionStorage.put(key, new ExceptionContainer(pendingReq, loggedException), -1); + + } else { + transactionStorage.put(key, new ExceptionContainer(null, loggedException), -1); + + } + + // build up redirect URL + String redirectUrl = null; + redirectUrl = ServletUtils.getBaseUrl(req); + redirectUrl += "/" + ProtocolFinalizationController.ENDPOINT_ERRORHANDLING + "?" + + EAAFConstants.PARAM_HTTP_ERROR_CODE + "=" + key; + + resp.setContentType("text/html"); + resp.setStatus(302); + + resp.addHeader("Location", redirectUrl); + log.debug("REDIRECT TO: " + redirectUrl); + + return; + + } catch (final Exception e) { + log.warn("Default error-handling FAILED. Exception can not be stored ....", e); + log.info("Switch to generic generic backup error-handling ... "); + protAuthService.handleErrorNoRedirect(loggedException, req, resp, true); + + } + + } + + + + /** + * Extracts a TaskExecutionException of a ProcessExecutionExeception Stacktrace. + * + * @param exception error + * @return Return the latest TaskExecutionExecption if exists, otherwise the latest + * ProcessExecutionException + */ + private Throwable extractOriginalExceptionFromProcessException(final Throwable exception) { + Throwable exholder = exception; + TaskExecutionException taskExc = null; + + while (exholder != null && exholder instanceof ProcessExecutionException) { + final ProcessExecutionException procExc = (ProcessExecutionException) exholder; + if (procExc.getCause() != null && procExc.getCause() instanceof TaskExecutionException) { + taskExc = (TaskExecutionException) procExc.getCause(); + exholder = taskExc.getOriginalException(); + + } else { + break; + } + + } + + if (taskExc == null) { + return exholder; + } else { + return taskExc; + } + } + + + } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/AbstractProcessEngineSignalController.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/AbstractProcessEngineSignalController.java index b87c9b78..9ff468d3 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/AbstractProcessEngineSignalController.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/AbstractProcessEngineSignalController.java @@ -1,119 +1,113 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.controller; import java.io.IOException; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.text.StringEscapeUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.IRequestStorage; import at.gv.egiz.eaaf.core.api.IStatusMessenger; import at.gv.egiz.eaaf.core.api.data.EAAFConstants; import at.gv.egiz.eaaf.core.api.idp.process.ProcessEngine; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.core.exceptions.EAAFIllegalStateException; -import at.gv.egiz.eaaf.core.impl.utils.TransactionIDUtils; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.exceptions.EaafIllegalStateException; +import at.gv.egiz.eaaf.core.impl.utils.TransactionIdUtils; +import org.apache.commons.text.StringEscapeUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; /** * Servlet that resumes a suspended process (in case of asynchronous tasks). - * + * * @author tknall - * + * */ public abstract class AbstractProcessEngineSignalController extends AbstractController { - private static final Logger log = LoggerFactory.getLogger(AbstractProcessEngineSignalController.class); - - @Autowired(required=true) protected ProcessEngine processEngine; - @Autowired(required=true) protected IRequestStorage requestStorage; - - protected void signalProcessManagement(HttpServletRequest req, HttpServletResponse resp) throws IOException, EAAFException { - String pendingRequestID = StringEscapeUtils.escapeHtml4(getPendingRequestId(req)); - IRequest pendingReq = null; - try { - if (pendingRequestID == null) { - new EAAFException( - IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_NOPENDIGREQID, - null); - - } - - pendingReq = requestStorage.getPendingRequest(pendingRequestID); - if (pendingReq == null) { - log.info("No PendingRequest with Id: " + pendingRequestID + " Maybe, a transaction timeout occure."); - throw new EAAFException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_TIMEOUT, new Object[]{pendingRequestID}); - - } - - //change pending-request ID - requestStorage.changePendingRequestID(pendingReq); - pendingRequestID = pendingReq.getPendingRequestId(); - - // process instance is mandatory - if (pendingReq.getProcessInstanceId() == null) { - throw new EAAFIllegalStateException(new Object[]{"MOA session does not provide process instance id."}); - - } - - // wake up next task - processEngine.signal(pendingReq); - - } catch (Exception ex) { - handleError(null, ex, req, resp, pendingReq); - - } finally { - //MOASessionDBUtils.closeSession(); - TransactionIDUtils.removeAllLoggingVariables(); - - } - - - } - - /** - * Retrieves the current pending-request id from the HttpServletRequest parameter - * - *

- * Note that this class/method can be overwritten by modules providing their own strategy of retrieving the - * respective pending-request id. - * - * @param request - * The unterlying HttpServletRequest. - * @return The current pending-request id. - */ - public String getPendingRequestId(HttpServletRequest request) { - return StringEscapeUtils.escapeHtml4(request.getParameter(EAAFConstants.PARAM_HTTP_TARGET_PENDINGREQUESTID)); - - } + private static final Logger log = + LoggerFactory.getLogger(AbstractProcessEngineSignalController.class); + + @Autowired(required = true) + protected ProcessEngine processEngine; + @Autowired(required = true) + protected IRequestStorage requestStorage; + + protected void signalProcessManagement(final HttpServletRequest req, + final HttpServletResponse resp) throws IOException, EaafException { + final String pendingRequestID = StringEscapeUtils.escapeHtml4(getPendingRequestId(req)); + IRequest pendingReq = null; + try { + if (pendingRequestID == null) { + throw new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_NOPENDIGREQID, null); + + } + + pendingReq = requestStorage.getPendingRequest(pendingRequestID); + if (pendingReq == null) { + log.info("No PendingRequest with Id: " + pendingRequestID + + " Maybe, a transaction timeout occure."); + throw new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_TIMEOUT, + new Object[] {pendingRequestID}); + + } + + // change pending-request ID + requestStorage.changePendingRequestID(pendingReq); + + // process instance is mandatory + if (pendingReq.getProcessInstanceId() == null) { + throw new EaafIllegalStateException( + new Object[] {"MOA session does not provide process instance id."}); + + } + + // wake up next task + processEngine.signal(pendingReq); + + } catch (final Exception ex) { + handleError(null, ex, req, resp, pendingReq); + + } finally { + // MOASessionDBUtils.closeSession(); + TransactionIdUtils.removeAllLoggingVariables(); + + } + + + } + + /** + * Retrieves the current pending-request id from the HttpServletRequest parameter + * + *

+ * Note that this class/method can be overwritten by modules providing their own strategy of + * retrieving the respective pending-request id. + * + * @param request The unterlying HttpServletRequest. + * @return The current pending-request id. + */ + public String getPendingRequestId(final HttpServletRequest request) { + return StringEscapeUtils + .escapeHtml4(request.getParameter(EAAFConstants.PARAM_HTTP_TARGET_PENDINGREQUESTID)); + + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java index b830e240..7b350c3b 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/ProtocolFinalizationController.java @@ -1,32 +1,34 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.controller; import java.io.IOException; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - +import at.gv.egiz.components.eventlog.api.EventConstants; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.IRequestStorage; +import at.gv.egiz.eaaf.core.api.IStatusMessenger; +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; +import at.gv.egiz.eaaf.core.api.data.ExceptionContainer; +import at.gv.egiz.eaaf.core.exceptions.EaafException; import org.apache.commons.text.StringEscapeUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -35,114 +37,121 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; -import at.gv.egiz.components.eventlog.api.EventConstants; -import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.core.api.IRequestStorage; -import at.gv.egiz.eaaf.core.api.IStatusMessenger; -import at.gv.egiz.eaaf.core.api.data.EAAFConstants; -import at.gv.egiz.eaaf.core.api.data.ExceptionContainer; -import at.gv.egiz.eaaf.core.api.idp.auth.services.IProtocolAuthenticationService; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; - /** + * Protocol finialization end-point. + * * @author tlenz * */ @Controller public class ProtocolFinalizationController extends AbstractController { - private static final Logger log = LoggerFactory.getLogger(ProtocolFinalizationController.class); - public static final String ENDPOINT_FINALIZEPROTOCOL = "finalizeAuthProtocol"; - public static final String ENDPOINT_ERRORHANDLING = "errorHandling"; - - @Autowired(required=true) IRequestStorage requestStorage; - - @RequestMapping(value = ENDPOINT_ERRORHANDLING, method = {RequestMethod.GET}) - public void errorHandling(HttpServletRequest req, HttpServletResponse resp) throws EAAFException, IOException { - //receive an authentication error - String errorid = StringEscapeUtils.escapeHtml4(req.getParameter(EAAFConstants.PARAM_HTTP_ERROR_CODE)); - if (errorid != null) { - IRequest pendingReq = null; - try { - //load stored exception from database - ExceptionContainer container = transactionStorage.get(errorid, ExceptionContainer.class); - if (container != null) { - //remove exception if it was found - transactionStorage.remove(errorid); - - Throwable throwable = container.getExceptionThrown(); - pendingReq = container.getPendingRequest(); - - if (pendingReq != null) { - //build protocol-specific error message if possible - protAuthService.buildProtocolSpecificErrorResponse(throwable, req, resp, pendingReq); - - //remove active user-session - transactionStorage.remove(pendingReq.getPendingRequestId()); - - return; - - } else { - protAuthService.handleErrorNoRedirect(throwable, req, resp, true); - - } - } else { - protAuthService.handleErrorNoRedirect( - new EAAFException( - IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_NOPENDIGREQID, - null), req, resp, false); - - } - - } catch (Throwable e) { - log.error(e.getMessage(), e); - protAuthService.handleErrorNoRedirect(e, req, resp, false); - - } finally { - //remove pending-request - if (pendingReq != null) { - requestStorage.removePendingRequest(pendingReq.getPendingRequestId()); - revisionsLogger.logEvent(EventConstants.TRANSACTION_DESTROYED, pendingReq.getUniqueTransactionIdentifier()); - - } - - } - - } else { - log.debug("Request contains NO ErrorId"); - protAuthService.handleErrorNoRedirect( - new EAAFException( - IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_NOPENDIGREQID, - null), req, resp, false); - - } - - } - - - @RequestMapping(value = ENDPOINT_FINALIZEPROTOCOL, method = {RequestMethod.GET}) - public void finalizeAuthProtocol(HttpServletRequest req, HttpServletResponse resp) throws EAAFException, IOException { - - //read pendingRequest from http request - Object idObject = StringEscapeUtils.escapeHtml4(req.getParameter(EAAFConstants.PARAM_HTTP_TARGET_PENDINGREQUESTID)); - IRequest pendingReq = null; - String pendingRequestID = null; - if (idObject != null && (idObject instanceof String)) { - pendingRequestID = (String) idObject; - pendingReq = requestStorage.getPendingRequest(pendingRequestID); - - } - - if (pendingReq == null) { - log.error("No PendingRequest with ID " + pendingRequestID + " found.!"); - protAuthService.handleErrorNoRedirect( - new EAAFException( - IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_TIMEOUT, - new Object[]{pendingRequestID, - }), req, resp, false); - - } else - protAuthService.finalizeAuthentication(req, resp, pendingReq); - - } - + private static final Logger log = LoggerFactory.getLogger(ProtocolFinalizationController.class); + public static final String ENDPOINT_FINALIZEPROTOCOL = "finalizeAuthProtocol"; + public static final String ENDPOINT_ERRORHANDLING = "errorHandling"; + + @Autowired(required = true) + IRequestStorage requestStorage; + + /** + * End-Point to handle errors. + * + * @param req http request + * @param resp http response + * @throws EaafException In case of an internal error + * @throws IOException In case of a servlet error + */ + @RequestMapping(value = ENDPOINT_ERRORHANDLING, method = {RequestMethod.GET}) + public void errorHandling(final HttpServletRequest req, final HttpServletResponse resp) + throws EaafException, IOException { + // receive an authentication error + final String errorid = + StringEscapeUtils.escapeHtml4(req.getParameter(EAAFConstants.PARAM_HTTP_ERROR_CODE)); + if (errorid != null) { + IRequest pendingReq = null; + try { + // load stored exception from database + final ExceptionContainer container = + transactionStorage.get(errorid, ExceptionContainer.class); + if (container != null) { + // remove exception if it was found + transactionStorage.remove(errorid); + + final Throwable throwable = container.getExceptionThrown(); + pendingReq = container.getPendingRequest(); + + if (pendingReq != null) { + // build protocol-specific error message if possible + protAuthService.buildProtocolSpecificErrorResponse(throwable, req, resp, pendingReq); + + // remove active user-session + transactionStorage.remove(pendingReq.getPendingRequestId()); + + return; + + } else { + protAuthService.handleErrorNoRedirect(throwable, req, resp, true); + + } + } else { + protAuthService.handleErrorNoRedirect( + new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_NOPENDIGREQID, null), + req, resp, false); + + } + + } catch (final Throwable e) { + log.error(e.getMessage(), e); + protAuthService.handleErrorNoRedirect(e, req, resp, false); + + } finally { + // remove pending-request + if (pendingReq != null) { + requestStorage.removePendingRequest(pendingReq.getPendingRequestId()); + revisionsLogger.logEvent(EventConstants.TRANSACTION_DESTROYED, + pendingReq.getUniqueTransactionIdentifier()); + + } + + } + + } else { + log.debug("Request contains NO ErrorId"); + protAuthService.handleErrorNoRedirect( + new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_NOPENDIGREQID, null), req, + resp, false); + + } + + } + + /** + * End-Point to finalize authentication protocol. + * + * @param req http request + * @param resp http response + * @throws EaafException In case of an internal error + * @throws IOException In case of a servlet error + */ + @RequestMapping(value = ENDPOINT_FINALIZEPROTOCOL, method = {RequestMethod.GET}) + public void finalizeAuthProtocol(final HttpServletRequest req, final HttpServletResponse resp) + throws EaafException, IOException { + + // read pendingRequest from http request + final String pendingRequestID = StringEscapeUtils + .escapeHtml4(req.getParameter(EAAFConstants.PARAM_HTTP_TARGET_PENDINGREQUESTID)); + final IRequest pendingReq = requestStorage.getPendingRequest(pendingRequestID); + + if (pendingReq == null) { + log.error("No PendingRequest with ID " + pendingRequestID + " found.!"); + protAuthService.handleErrorNoRedirect( + new EaafException(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_TIMEOUT, + new Object[] {pendingRequestID,}), + req, resp, false); + + } else { + protAuthService.finalizeAuthentication(req, resp, pendingReq); + } + + } + } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/protocols/RequestImpl.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/protocols/RequestImpl.java index 722a9304..ac0876c4 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/protocols/RequestImpl.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/protocols/RequestImpl.java @@ -1,29 +1,22 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.controller.protocols; import java.io.Serializable; @@ -35,444 +28,459 @@ import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; - +import javax.annotation.Nonnull; import javax.servlet.http.HttpServletRequest; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.lang.NonNull; -import org.springframework.lang.Nullable; - import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.data.EAAFConstants; import at.gv.egiz.eaaf.core.api.idp.IConfiguration; import at.gv.egiz.eaaf.core.api.idp.IConfigurationWithSP; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.exceptions.EAAFAuthenticationException; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.core.exceptions.EAAFStorageException; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EaafAuthenticationException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; -import at.gv.egiz.eaaf.core.impl.utils.HTTPUtils; +import at.gv.egiz.eaaf.core.impl.utils.HttpUtils; import at.gv.egiz.eaaf.core.impl.utils.Random; -import at.gv.egiz.eaaf.core.impl.utils.TransactionIDUtils; - -public abstract class RequestImpl implements IRequest, Serializable{ - - private static final Logger log = LoggerFactory.getLogger(RequestImpl.class); - - public static final String DATAID_REQUESTER_IP_ADDRESS = "reqestImpl_requesterIPAddr"; - - private static final long serialVersionUID = 1L; - - private String module = null; - private String action = null; - - private String pendingRequestId = null; - private String processInstanceId; - private String internalSSOSessionId; - - private String uniqueTransactionIdentifer; - private String uniqueSessionIdentifer; - - private String requestedServiceProviderIdentifer; - private String idpAuthURL = null; - - private ISPConfiguration spConfiguration = null; - - private boolean passiv = false; - private boolean force = false; - private boolean isAbortedByUser = false; - - //every request needs authentication by default - private boolean needAuthentication = true; - - //every request is not authenticated by default - private boolean isAuthenticated = false; - - //every request needs no SSO by default - private boolean needSSO = false; - - private boolean needUserConsent = false; - - private final Map genericDataStorage = new HashMap(); - - - /** - * Initialize this pendingRequest object - * - * @param req {@link HttpServletRequest} - * @param authConfig {@link IConfiguration} - * @throws EAAFException - * - */ - public final void initialize(HttpServletRequest req, IConfigurationWithSP authConfig) throws EAAFException { - initialize(req, authConfig, null); - - } - - /** - * Initialize this pendingRequest object - * - * @param req {@link HttpServletRequest} - * @param authConfig {@link IConfiguration} - * @param transactionId transactionId that should be used in this pendingRequest for logging. If 'null' a new one will be generated - * - * @throws EAAFException - * - */ - public final void initialize(@NonNull HttpServletRequest req, @NonNull IConfigurationWithSP authConfig, @Nullable String transactionId) throws EAAFException { - //use external transactionId or create new one if empty or null - if (StringUtils.isNotEmpty(transactionId)) - uniqueTransactionIdentifer = transactionId; - else - uniqueTransactionIdentifer = Random.nextLongRandom(); - - //set unique transaction identifier for logging - TransactionIDUtils.setTransactionId(uniqueTransactionIdentifer); - - //initialize session object - genericDataStorage.put(EAAFConstants.AUTH_DATA_CREATED, new Date()); - //genericDataStorage.put(EAAFConstants.VALUE_SESSIONID, Random.nextLongRandom()); - - //check if End-Point is valid - final String authURLString = HTTPUtils.extractAuthURLFromRequest(req); - URL authReqURL; - try { - authReqURL = new URL(authURLString); - - } catch (final MalformedURLException e) { - log.error("IDP AuthenticationServiceURL Prefix is not a valid URL." + authURLString, e); - throw new EAAFAuthenticationException("errorId", new Object[]{authURLString}, e); - - } - this.idpAuthURL = authConfig.validateIDPURL(authReqURL); - if (this.idpAuthURL == null) { - log.warn("Extract AuthenticationServiceURL: " + authReqURL + " is NOT found in configuration."); - throw new EAAFAuthenticationException("errorId", new Object[]{authURLString}); - - } - - //set unique session identifier - final String uniqueID = (String) req.getAttribute(EAAFConstants.UNIQUESESSIONIDENTIFIER); - if (StringUtils.isNotEmpty(uniqueID)) - this.uniqueSessionIdentifer = uniqueID; - - else { - log.debug("Create new sessionIdentifier for this pendingRequest ... "); - this.uniqueSessionIdentifer = UUID.randomUUID().toString(); - - } - - //set requester's IP address - try { - setRawDataToTransaction(DATAID_REQUESTER_IP_ADDRESS, req.getRemoteAddr()); - - } catch (final EAAFStorageException e) { - log.info("Can NOT store remote IP address into 'pendingRequest'." , e); - - } - - } - - public final void setSPEntityId(String spIdentifier) { - this.requestedServiceProviderIdentifer = spIdentifier; - } - - @Override - public final String getSPEntityId() { - return this.requestedServiceProviderIdentifer; - } - - @Override - public final boolean isPassiv() { - return passiv; - } - - @Override - public final boolean forceAuth() { - return force; - } - - public final void setPassiv(boolean passiv) { - this.passiv = passiv; - } - - public final void setForce(boolean force) { - this.force = force; - } - - @Override - public final String requestedAction() { - return action; - } - - public final void setAction(String action) { - this.action = action; - } - - @Override - public final String requestedModule() { - return module; - } - - public final void setModule(String module) { - this.module = module; - } - - public final void setPendingRequestId(String pendingReqId) { - this.pendingRequestId = pendingReqId; - - } - - @Override - @NonNull - public final String getPendingRequestId() { - if (pendingRequestId == null) - throw new IllegalStateException("No PendingRequestId set!!!"); - - return pendingRequestId; - } - - @Override - public final String getInternalSSOSessionIdentifier() { - return this.internalSSOSessionId; - } - - @Override - public final void setInternalSSOSessionIdentifier(String internalSSOSessionId) { - this.internalSSOSessionId = internalSSOSessionId; - - } - - @Override - public final T getSessionData(final Class wrapper) { - if (wrapper != null) { - if (AuthProcessDataWrapper.class.isAssignableFrom(wrapper)) { - try { - return wrapper.getConstructor(Map.class).newInstance(this.genericDataStorage); - - } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException - | IllegalArgumentException | InvocationTargetException e) { - log.error("Can NOT instance wrapper: " + wrapper.getName(), e); - - } - - } - - log.error("Can NOT wrap generic data into session data. " - + "Reason: Wrapper " + wrapper.getName() + " is NOT a valid wrapper"); - throw new RuntimeException("Can NOT wrap generic data into session data. " - + "Reason: Wrapper " + wrapper.getName() + " is NOT a valid wrapper"); - - } - - return null; - - } - - @Override - public final ISPConfiguration getServiceProviderConfiguration() { - return this.spConfiguration; - - - } - - @Override - public T getServiceProviderConfiguration(final Class decorator) { - if (this.spConfiguration != null) { - if (decorator.isAssignableFrom(this.spConfiguration.getClass())) { - return (T) this.spConfiguration; - - } else - log.error("Can not decorate SP configuration by '" + decorator.getName() + "'."); - throw new RuntimeException("Can not decorate SP configuration by '" + decorator.getName() + "'."); - - } - - return null; - - } - - public void setOnlineApplicationConfiguration(ISPConfiguration spConfig) { - this.spConfiguration = spConfig; - - } - - @Override - public final String getUniqueTransactionIdentifier() { - return this.uniqueTransactionIdentifer; - - } - - @Override - public final String getUniqueSessionIdentifier() { - return this.uniqueSessionIdentifer; - - } - - @Override - public final String getProcessInstanceId() { - return this.processInstanceId; - - } - - public final void setUniqueTransactionIdentifier(String id) { - this.uniqueTransactionIdentifer = id; - - } - - public final void setUniqueSessionIdentifier(String id) { - this.uniqueSessionIdentifer = id; - - } - - public void setProcessInstanceId(String id) { - this.processInstanceId = id; - - } - - @Override - public final String getAuthURL() { - return this.idpAuthURL; - } - - @Override - public final String getAuthURLWithOutSlash() { - if (this.idpAuthURL.endsWith("/")) - return this.idpAuthURL.substring(0, this.idpAuthURL.length()-1); - else - return this.idpAuthURL; - - } - - @Override - public final boolean isNeedAuthentication() { - return needAuthentication; - } - - public final void setNeedAuthentication(boolean needAuthentication) { - this.needAuthentication = needAuthentication; - } - - @Override - public final boolean isAuthenticated() { - return isAuthenticated; - } - - @Override - public final void setAuthenticated(boolean isAuthenticated) { - this.isAuthenticated = isAuthenticated; - } - - @Override - public final boolean needSingleSignOnFunctionality() { - return needSSO; - } - @Override - public final void setNeedSingleSignOnFunctionality(boolean needSSO) { - this.needSSO = needSSO; - - } - - @Override - public final boolean isNeedUserConsent() { - return this.needUserConsent; - - } - - @Override - public final void setNeedUserConsent(boolean needConsent) { - this.needUserConsent = needConsent; - - } - - @Override - public final boolean isAbortedByUser() { - return this.isAbortedByUser; - } - - @Override - public final void setAbortedByUser(boolean isAborted) { - this.isAbortedByUser = isAborted; - - } - - @Override - public final Object getRawData(String key) { - if (StringUtils.isNotEmpty(key)) { - return genericDataStorage.get(key); - - } - - log.info("Can not load generic request-data with key='null'"); - return null; - } - - @Override - public final T getRawData(String key, final Class clazz) { - if (StringUtils.isNotEmpty(key)) { - final Object data = genericDataStorage.get(key); - - if (data == null) - return null; - - try { - @SuppressWarnings("unchecked") - final - T test = (T) data; - return test; - - } catch (final Exception e) { - log.warn("Generic request-data object can not be casted to requested type", e); - return null; - - } - - } - - log.info("Can not load generic request-data with key='null'"); - return null; - - } - - @Override - public final void setRawDataToTransaction(String key, Object object) throws EAAFStorageException { - if (StringUtils.isEmpty(key)) { - log.info("Generic request-data can not be stored with a 'null' key"); - throw new EAAFStorageException("Generic request-data can not be stored with a 'null' key", null); - - } - - if (object != null) { - if (!Serializable.class.isInstance(object)) { - log.warn("Generic request-data can only store objects which implements the 'Seralizable' interface"); - throw new EAAFStorageException("Generic request-data can only store objects which implements the 'Seralizable' interface", null); - - } - } - - if (genericDataStorage.containsKey(key)) - log.trace("Overwrite generic request-data with key:" + key); - else - log.trace("Add generic request-data with key:" + key + " to session."); - - genericDataStorage.put(key, object); - - } - - @Override - public final void setRawDataToTransaction(Map map) throws EAAFStorageException { - if (map == null) { - log.info("Generic request-data can not be stored with a 'null' map"); - throw new EAAFStorageException("Generic request-data can not be stored with a 'null' map", null); - - } - - //validate and store values - for (final Entry el : map.entrySet()) - setRawDataToTransaction(el.getKey(), el.getValue()); - - } - +import at.gv.egiz.eaaf.core.impl.utils.TransactionIdUtils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.lang.NonNull; +import org.springframework.lang.Nullable; +import org.springframework.util.Assert; + +public abstract class RequestImpl implements IRequest, Serializable { + + private static final Logger log = LoggerFactory.getLogger(RequestImpl.class); + + public static final String DATAID_REQUESTER_IP_ADDRESS = "reqestImpl_requesterIPAddr"; + + private static final long serialVersionUID = 1L; + + private String module = null; + private String action = null; + + private String pendingRequestId = null; + private String processInstanceId; + private String internalSsoSessionId; + + private String uniqueTransactionIdentifer; + private String uniqueSessionIdentifer; + + private String requestedServiceProviderIdentifer; + private String idpAuthUrl = null; + + private IspConfiguration spConfiguration = null; + + private boolean passiv = false; + private boolean force = false; + private boolean isAbortedByUser = false; + + // every request needs authentication by default + private boolean needAuthentication = true; + + // every request is not authenticated by default + private boolean isAuthenticated = false; + + // every request needs no SSO by default + private boolean needSso = false; + + private boolean needUserConsent = false; + + private final Map genericDataStorage = new HashMap<>(); + + + /** + * Initialize this pendingRequest object. + * + * @param req {@link HttpServletRequest} + * @param authConfig {@link IConfiguration} + * @throws EaafException + * + */ + public final void initialize(final HttpServletRequest req, final IConfigurationWithSP authConfig) + throws EaafException { + initialize(req, authConfig, null); + + } + + /** + * Initialize this pendingRequest object. + * + * @param req {@link HttpServletRequest} + * @param authConfig {@link IConfiguration} + * @param transactionId transactionId that should be used in this pendingRequest for logging. If + * 'null' a new one will be generated + * + * @throws EaafException + * + */ + public final void initialize(@NonNull final HttpServletRequest req, + @NonNull final IConfigurationWithSP authConfig, @Nullable final String transactionId) + throws EaafException { + // use external transactionId or create new one if empty or null + if (StringUtils.isNotEmpty(transactionId)) { + uniqueTransactionIdentifer = transactionId; + } else { + uniqueTransactionIdentifer = Random.nextLongRandom(); + } + + // set unique transaction identifier for logging + TransactionIdUtils.setTransactionId(uniqueTransactionIdentifer); + + // initialize session object + genericDataStorage.put(EAAFConstants.AUTH_DATA_CREATED, new Date()); + // genericDataStorage.put(EAAFConstants.VALUE_SESSIONID, Random.nextLongRandom()); + + // check if End-Point is valid + final String authUrlString = HttpUtils.extractAuthUrlFromRequest(req); + URL authReqUrl; + try { + authReqUrl = new URL(authUrlString); + + } catch (final MalformedURLException e) { + log.error("IDP AuthenticationServiceURL Prefix is not a valid URL." + authUrlString, e); + throw new EaafAuthenticationException("errorId", new Object[] {authUrlString}, e); + + } + this.idpAuthUrl = authConfig.validateIdpUrl(authReqUrl); + if (this.idpAuthUrl == null) { + log.warn( + "Extract AuthenticationServiceURL: " + authReqUrl + " is NOT found in configuration."); + throw new EaafAuthenticationException("errorId", new Object[] {authUrlString}); + + } + + // set unique session identifier + final String uniqueID = (String) req.getAttribute(EAAFConstants.UNIQUESESSIONIDENTIFIER); + if (StringUtils.isNotEmpty(uniqueID)) { + this.uniqueSessionIdentifer = uniqueID; + } else { + log.debug("Create new sessionIdentifier for this pendingRequest ... "); + this.uniqueSessionIdentifer = UUID.randomUUID().toString(); + + } + + // set requester's IP address + try { + setRawDataToTransaction(DATAID_REQUESTER_IP_ADDRESS, req.getRemoteAddr()); + + } catch (final EaafStorageException e) { + log.info("Can NOT store remote IP address into 'pendingRequest'.", e); + + } + + } + + public final void setSpEntityId(final String spIdentifier) { + this.requestedServiceProviderIdentifer = spIdentifier; + } + + @Override + public final String getSpEntityId() { + return this.requestedServiceProviderIdentifer; + } + + @Override + public final boolean isPassiv() { + return passiv; + } + + @Override + public final boolean forceAuth() { + return force; + } + + public final void setPassiv(final boolean passiv) { + this.passiv = passiv; + } + + public final void setForce(final boolean force) { + this.force = force; + } + + @Override + public final String requestedAction() { + return action; + } + + public final void setAction(final String action) { + this.action = action; + } + + @Override + public final String requestedModule() { + return module; + } + + public final void setModule(final String module) { + this.module = module; + } + + public final void setPendingRequestId(final String pendingReqId) { + this.pendingRequestId = pendingReqId; + + } + + @Override + @NonNull + public final String getPendingRequestId() { + if (pendingRequestId == null) { + throw new IllegalStateException("No PendingRequestId set!!!"); + } + + return pendingRequestId; + } + + @Override + public final String getInternalSsoSessionIdentifier() { + return this.internalSsoSessionId; + } + + @Override + public final void setInternalSsoSessionIdentifier(final String internalSsoSessionId) { + this.internalSsoSessionId = internalSsoSessionId; + + } + + @Override + @Nonnull + public final T getSessionData(@Nonnull final Class wrapper) { + Assert.notNull(wrapper, "Wrapper must NOT null"); + if (AuthProcessDataWrapper.class.isAssignableFrom(wrapper)) { + try { + return wrapper.getConstructor(Map.class).newInstance(this.genericDataStorage); + + } catch (NoSuchMethodException | SecurityException | InstantiationException + | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + log.error("Can NOT instance wrapper: " + wrapper.getName(), e); + + } + + } + + log.error("Can NOT wrap generic data into session data. " + "Reason: Wrapper " + + wrapper.getName() + " is NOT a valid wrapper"); + throw new RuntimeException("Can NOT wrap generic data into session data. " + "Reason: Wrapper " + + wrapper.getName() + " is NOT a valid wrapper"); + + } + + @Override + public final IspConfiguration getServiceProviderConfiguration() { + return this.spConfiguration; + + + } + + @Override + public T getServiceProviderConfiguration(final Class decorator) { + if (this.spConfiguration != null) { + if (decorator.isAssignableFrom(this.spConfiguration.getClass())) { + return (T) this.spConfiguration; + + } else { + log.error("Can not decorate SP configuration by '" + decorator.getName() + "'."); + } + throw new RuntimeException( + "Can not decorate SP configuration by '" + decorator.getName() + "'."); + + } + + return null; + + } + + public void setOnlineApplicationConfiguration(final IspConfiguration spConfig) { + this.spConfiguration = spConfig; + + } + + @Override + public final String getUniqueTransactionIdentifier() { + return this.uniqueTransactionIdentifer; + + } + + @Override + public final String getUniqueSessionIdentifier() { + return this.uniqueSessionIdentifer; + + } + + @Override + public final String getProcessInstanceId() { + return this.processInstanceId; + + } + + public final void setUniqueTransactionIdentifier(final String id) { + this.uniqueTransactionIdentifer = id; + + } + + public final void setUniqueSessionIdentifier(final String id) { + this.uniqueSessionIdentifer = id; + + } + + public void setProcessInstanceId(final String id) { + this.processInstanceId = id; + + } + + @Override + public final String getAuthUrl() { + return this.idpAuthUrl; + } + + @Override + public final String getAuthUrlWithOutSlash() { + if (this.idpAuthUrl.endsWith("/")) { + return this.idpAuthUrl.substring(0, this.idpAuthUrl.length() - 1); + } else { + return this.idpAuthUrl; + } + + } + + @Override + public final boolean isNeedAuthentication() { + return needAuthentication; + } + + public final void setNeedAuthentication(final boolean needAuthentication) { + this.needAuthentication = needAuthentication; + } + + @Override + public final boolean isAuthenticated() { + return isAuthenticated; + } + + @Override + public final void setAuthenticated(final boolean isAuthenticated) { + this.isAuthenticated = isAuthenticated; + } + + @Override + public final boolean needSingleSignOnFunctionality() { + return needSso; + } + + @Override + public final void setNeedSingleSignOnFunctionality(final boolean needSso) { + this.needSso = needSso; + + } + + @Override + public final boolean isNeedUserConsent() { + return this.needUserConsent; + + } + + @Override + public final void setNeedUserConsent(final boolean needConsent) { + this.needUserConsent = needConsent; + + } + + @Override + public final boolean isAbortedByUser() { + return this.isAbortedByUser; + } + + @Override + public final void setAbortedByUser(final boolean isAborted) { + this.isAbortedByUser = isAborted; + + } + + @Override + public final Object getRawData(final String key) { + if (StringUtils.isNotEmpty(key)) { + return genericDataStorage.get(key); + + } + + log.info("Can not load generic request-data with key='null'"); + return null; + } + + @Override + public final T getRawData(final String key, final Class clazz) { + if (StringUtils.isNotEmpty(key)) { + final Object data = genericDataStorage.get(key); + + if (data == null) { + return null; + } + + try { + @SuppressWarnings("unchecked") + final T test = (T) data; + return test; + + } catch (final Exception e) { + log.warn("Generic request-data object can not be casted to requested type", e); + return null; + + } + + } + + log.info("Can not load generic request-data with key='null'"); + return null; + + } + + @Override + public final void setRawDataToTransaction(final String key, final Object object) + throws EaafStorageException { + if (StringUtils.isEmpty(key)) { + log.info("Generic request-data can not be stored with a 'null' key"); + throw new EaafStorageException("Generic request-data can not be stored with a 'null' key", + null); + + } + + if (object != null) { + if (!Serializable.class.isInstance(object)) { + log.warn( + "Generic request-data can only store objects which implements the 'Seralizable' interface"); + throw new EaafStorageException( + "Generic request-data can only store objects which implements the 'Seralizable' interface", + null); + + } + } + + if (genericDataStorage.containsKey(key)) { + log.trace("Overwrite generic request-data with key:" + key); + } else { + log.trace("Add generic request-data with key:" + key + " to session."); + } + + genericDataStorage.put(key, object); + + } + + @Override + public final void setRawDataToTransaction(final Map map) + throws EaafStorageException { + if (map == null) { + log.info("Generic request-data can not be stored with a 'null' map"); + throw new EaafStorageException("Generic request-data can not be stored with a 'null' map", + null); + + } + + // validate and store values + for (final Entry el : map.entrySet()) { + setRawDataToTransaction(el.getKey(), el.getValue()); + } + + } + } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/AbstractLocaleAuthServletTask.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/AbstractLocaleAuthServletTask.java index 6b5f1a4c..3c8fd604 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/AbstractLocaleAuthServletTask.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/AbstractLocaleAuthServletTask.java @@ -13,77 +13,85 @@ import org.slf4j.LoggerFactory; import at.gv.egiz.eaaf.core.api.data.EAAFConstants; import at.gv.egiz.eaaf.core.api.data.EAAFEventCodes; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; public abstract class AbstractLocaleAuthServletTask extends AbstractAuthServletTask { - private static final Logger log = LoggerFactory.getLogger(AbstractLocaleAuthServletTask.class); - - public static final String PROP_REQ_PARAM_LOCALE = "lang"; - - @Override - public final void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) - throws TaskExecutionException { - - final Serializable changeLangFlag = executionContext.get(EAAFConstants.PROCESSCONTEXT_SWITCH_LANGUAGE); - final String localeParam = StringEscapeUtils.escapeHtml4(request.getParameter(PROP_REQ_PARAM_LOCALE)); - if (StringUtils.isNotEmpty(localeParam) && - (changeLangFlag == null || !((Boolean)changeLangFlag)) ) { - log.debug("Find {} parameter. Reload last task with new locale: {}", PROP_REQ_PARAM_LOCALE, localeParam); - executionContext.put(EAAFConstants.PROCESSCONTEXT_SWITCH_LANGUAGE, true); - - - - } else { - log.trace("Find {} parameter. Processing this task ... ",PROP_REQ_PARAM_LOCALE); - executionContext.put(EAAFConstants.PROCESSCONTEXT_SWITCH_LANGUAGE, false); - - if (parseFlagFromHttpRequest(request, EAAFConstants.PARAM_HTTP_STOP_PROCESS, false)) { - log.info("Authentication process WAS stopped by entity. Stopping auth. process ... "); - stopProcessFromUserDecision(executionContext, request, response); - - } else - executeWithLocale(executionContext, request, response); - - } - - } - - protected void stopProcessFromUserDecision(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) throws TaskExecutionException { - try { - revisionsLogger.logEvent(pendingReq, EAAFEventCodes.PROCESS_STOPPED_BY_USER); - pendingReq.setAbortedByUser(true); - pendingReq.setAuthenticated(false); - performRedirectToProtocolFinialization(executionContext, pendingReq, request, response); - - log.trace("Set process-cancelation flag"); - executionContext.setCanceleProcessFlag(); - - } catch (final EAAFException e) { - throw new TaskExecutionException(pendingReq, e.getMessage(), e); - - } catch (final Exception e) { - log.warn("Stopping auth.process FAILED", e); - throw new TaskExecutionException(pendingReq, e.getMessage(), e); - - } - - } - - protected boolean parseFlagFromHttpRequest(HttpServletRequest httpReq, String httpParamName, boolean defaultValue) { - final String flag = httpReq.getParameter(httpParamName); - log.trace("Get httpParam: {} with value: {}", httpParamName, flag); - if (StringUtils.isNotEmpty(httpParamName)) { - return Boolean.parseBoolean(flag); - - } else { - return defaultValue; - } - - } - - protected abstract void executeWithLocale(ExecutionContext executionContext, HttpServletRequest request, - HttpServletResponse response) throws TaskExecutionException; + private static final Logger log = LoggerFactory.getLogger(AbstractLocaleAuthServletTask.class); + + public static final String PROP_REQ_PARAM_LOCALE = "lang"; + + @Override + public final void execute(final ExecutionContext executionContext, + final HttpServletRequest request, final HttpServletResponse response) + throws TaskExecutionException { + + final Serializable changeLangFlag = + executionContext.get(EAAFConstants.PROCESSCONTEXT_SWITCH_LANGUAGE); + final String localeParam = + StringEscapeUtils.escapeHtml4(request.getParameter(PROP_REQ_PARAM_LOCALE)); + if (StringUtils.isNotEmpty(localeParam) + && (changeLangFlag == null || !((Boolean) changeLangFlag))) { + log.debug("Find {} parameter. Reload last task with new locale: {}", PROP_REQ_PARAM_LOCALE, + localeParam); + executionContext.put(EAAFConstants.PROCESSCONTEXT_SWITCH_LANGUAGE, true); + + + + } else { + log.trace("Find {} parameter. Processing this task ... ", PROP_REQ_PARAM_LOCALE); + executionContext.put(EAAFConstants.PROCESSCONTEXT_SWITCH_LANGUAGE, false); + + if (parseFlagFromHttpRequest(request, EAAFConstants.PARAM_HTTP_STOP_PROCESS, false)) { + log.info("Authentication process WAS stopped by entity. Stopping auth. process ... "); + stopProcessFromUserDecision(executionContext, request, response); + + } else { + executeWithLocale(executionContext, request, response); + } + + } + + } + + protected void stopProcessFromUserDecision(final ExecutionContext executionContext, + final HttpServletRequest request, final HttpServletResponse response) + throws TaskExecutionException { + try { + revisionsLogger.logEvent(pendingReq, EAAFEventCodes.PROCESS_STOPPED_BY_USER); + pendingReq.setAbortedByUser(true); + pendingReq.setAuthenticated(false); + performRedirectToProtocolFinialization(executionContext, pendingReq, request, response); + + log.trace("Set process-cancelation flag"); + executionContext.setCanceleProcessFlag(); + + } catch (final EaafException e) { + throw new TaskExecutionException(pendingReq, e.getMessage(), e); + + } catch (final Exception e) { + log.warn("Stopping auth.process FAILED", e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); + + } + + } + + protected boolean parseFlagFromHttpRequest(final HttpServletRequest httpReq, + final String httpParamName, final boolean defaultValue) { + final String flag = httpReq.getParameter(httpParamName); + log.trace("Get httpParam: {} with value: {}", httpParamName, flag); + if (StringUtils.isNotEmpty(httpParamName)) { + return Boolean.parseBoolean(flag); + + } else { + return defaultValue; + } + + } + + protected abstract void executeWithLocale(ExecutionContext executionContext, + HttpServletRequest request, HttpServletResponse response) throws TaskExecutionException; } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/FinalizeAuthenticationTask.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/FinalizeAuthenticationTask.java index b12a69b2..7991c093 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/FinalizeAuthenticationTask.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/FinalizeAuthenticationTask.java @@ -1,81 +1,79 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.controller.tasks; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - import at.gv.egiz.eaaf.core.api.data.EAAFConstants; import at.gv.egiz.eaaf.core.api.idp.auth.IAuthenticationManager; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; /** + * Finalize the authentication process-flow. + * * @author tlenz * */ @Component("FinalizeAuthenticationTask") public class FinalizeAuthenticationTask extends AbstractAuthServletTask { - private static final Logger log = LoggerFactory.getLogger(FinalizeAuthenticationTask.class); - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.process.springweb.MoaIdTask#execute(at.gv.egovernment.moa.id.process.api.ExecutionContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - public void execute(ExecutionContext executionContext, - HttpServletRequest request, HttpServletResponse response) - throws TaskExecutionException { - - try { - //set pending request to authenticated - pendingReq.setAuthenticated(true); - revisionsLogger.logEvent(pendingReq, IAuthenticationManager.EVENT_AUTHENTICATION_PROCESS_FINISHED); - performRedirectToProtocolFinialization(executionContext, pendingReq, request, response); - - - } catch (final EAAFException e) { - throw new TaskExecutionException(pendingReq, e.getMessage(), e); - - } catch (final Exception e) { - log.warn("FinalizeAuthenticationTask has an internal error", e); - throw new TaskExecutionException(pendingReq, e.getMessage(), e); - - } finally { - executionContext.remove(EAAFConstants.PROCESS_ENGINE_PENDINGREQUESTID); - - } - - } + private static final Logger log = LoggerFactory.getLogger(FinalizeAuthenticationTask.class); + + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.process.springweb.MoaIdTask#execute(at.gv.egovernment.moa.id.process. + * api.ExecutionContext, javax.servlet.http.HttpServletRequest, + * javax.servlet.http.HttpServletResponse) + */ + @Override + public void execute(final ExecutionContext executionContext, final HttpServletRequest request, + final HttpServletResponse response) throws TaskExecutionException { + + try { + // set pending request to authenticated + pendingReq.setAuthenticated(true); + revisionsLogger.logEvent(pendingReq, + IAuthenticationManager.EVENT_AUTHENTICATION_PROCESS_FINISHED); + performRedirectToProtocolFinialization(executionContext, pendingReq, request, response); + + + } catch (final EaafException e) { + throw new TaskExecutionException(pendingReq, e.getMessage(), e); + + } catch (final Exception e) { + log.warn("FinalizeAuthenticationTask has an internal error", e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); + + } finally { + executionContext.remove(EAAFConstants.PROCESS_ENGINE_PENDINGREQUESTID); + + } + + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/RestartAuthProzessManagement.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/RestartAuthProzessManagement.java index 5ea5baa1..7a2c5f08 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/RestartAuthProzessManagement.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/controller/tasks/RestartAuthProzessManagement.java @@ -1,121 +1,122 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.controller.tasks; import java.util.Set; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; import at.gv.egiz.eaaf.core.api.idp.process.ProcessEngine; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; import at.gv.egiz.eaaf.core.impl.idp.auth.modules.ModuleRegistration; import at.gv.egiz.eaaf.core.impl.idp.controller.protocols.RequestImpl; import at.gv.egiz.eaaf.core.impl.idp.process.ExecutionContextImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; /** + * Restart the authentication process-flow. + * * @author tlenz * */ @Component("RestartAuthProzessManagement") -public class RestartAuthProzessManagement extends AbstractAuthServletTask { - private static final Logger log = LoggerFactory.getLogger(RestartAuthProzessManagement.class); - - @Autowired ProcessEngine processEngine; - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.process.springweb.MoaIdTask#execute(at.gv.egovernment.moa.id.process.api.ExecutionContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) - throws TaskExecutionException { - try { - - if (this.pendingReq.isAbortedByUser()) { - log.debug("AuthProcess was stopped. Forward to finalization ... "); - performRedirectToProtocolFinialization(executionContext, pendingReq, request, response); - - } else { - //create a new execution context and copy all elements to new context - final ExecutionContext newec = new ExecutionContextImpl(); - final Set entries = executionContext.keySet(); - for (final String key : entries) { - newec.put(key, executionContext.get(key)); - - } - - log.debug("Select new auth.-process and restart restart process-engine ... "); - - // select and create new process instance - final String processDefinitionId = ModuleRegistration.getInstance().selectProcess(newec, pendingReq); - if (processDefinitionId == null) { - log.warn("No suitable authentication process found for SessionID " + pendingReq.getPendingRequestId()); - throw new EAAFException("process.02", new Object[] { pendingReq.getPendingRequestId()}); - } - - final String processInstanceId = processEngine.createProcessInstance(processDefinitionId, newec); - - // keep process instance id in moa session - ((RequestImpl)pendingReq).setProcessInstanceId(processInstanceId); - - // make sure pending request has been persisted before running the process - try { - requestStoreage.storePendingRequest(pendingReq); - - } catch (final EAAFException e) { - log.error("Database Error! MOASession is not stored!"); - throw new EAAFException("internal.02", null); - - } - - log.info("Restart process-engine with auth.process:" + processDefinitionId); - - // start process - processEngine.start(pendingReq); - - } - - } catch (final EAAFException e) { - throw new TaskExecutionException(pendingReq, e.getMessage(), e); - - } catch (final Exception e) { - log.warn("RestartAuthProzessManagement has an internal error", e); - throw new TaskExecutionException(pendingReq, e.getMessage(), e); - - } - - } +public class RestartAuthProzessManagement extends AbstractAuthServletTask { + private static final Logger log = LoggerFactory.getLogger(RestartAuthProzessManagement.class); + + @Autowired ProcessEngine processEngine; + @Autowired ModuleRegistration moduleRegistration; + + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.process.springweb.MoaIdTask#execute(at.gv.egovernment.moa.id.process. + * api.ExecutionContext, javax.servlet.http.HttpServletRequest, + * javax.servlet.http.HttpServletResponse) + */ + @Override + public void execute(final ExecutionContext executionContext, final HttpServletRequest request, + final HttpServletResponse response) throws TaskExecutionException { + try { + + if (this.pendingReq.isAbortedByUser()) { + log.debug("AuthProcess was stopped. Forward to finalization ... "); + performRedirectToProtocolFinialization(executionContext, pendingReq, request, response); + + } else { + // create a new execution context and copy all elements to new context + final ExecutionContext newec = new ExecutionContextImpl(); + final Set entries = executionContext.keySet(); + for (final String key : entries) { + newec.put(key, executionContext.get(key)); + + } + + log.debug("Select new auth.-process and restart restart process-engine ... "); + + // select and create new process instance + final String processDefinitionId = + moduleRegistration.selectProcess(newec, pendingReq); + if (processDefinitionId == null) { + log.warn("No suitable authentication process found for SessionID " + + pendingReq.getPendingRequestId()); + throw new EaafException("process.02", new Object[] {pendingReq.getPendingRequestId()}); + } + + final String processInstanceId = + processEngine.createProcessInstance(processDefinitionId, newec); + + // keep process instance id in moa session + ((RequestImpl) pendingReq).setProcessInstanceId(processInstanceId); + + // make sure pending request has been persisted before running the process + try { + requestStoreage.storePendingRequest(pendingReq); + + } catch (final EaafException e) { + log.error("Database Error! MOASession is not stored!"); + throw new EaafException("internal.02", null); + + } + + log.info("Restart process-engine with auth.process:" + processDefinitionId); + + // start process + processEngine.start(pendingReq); + + } + + } catch (final EaafException e) { + throw new TaskExecutionException(pendingReq, e.getMessage(), e); + + } catch (final Exception e) { + log.warn("RestartAuthProzessManagement has an internal error", e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); + + } + + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ExecutionContextImpl.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ExecutionContextImpl.java index 3cd696df..619911c1 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ExecutionContextImpl.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ExecutionContextImpl.java @@ -1,29 +1,22 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process; import java.io.Serializable; @@ -31,87 +24,88 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; - import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; /** * ExecutionContext implementation, related to a certain process instance. - * + * * @author tknall - * + * */ public class ExecutionContextImpl implements ExecutionContext { - private static final long serialVersionUID = 1L; - - private final Map ctxData = Collections.synchronizedMap(new HashMap()); - - private String processInstanceId; - private boolean markedAsCancelled = false; - - /** - * Creates a new instance. - */ - public ExecutionContextImpl() { - } - - /** - * Creates a new instance and associated it with a certain process instance. - */ - public ExecutionContextImpl(String processInstanceId) { - this.processInstanceId = processInstanceId; - } - - @Override - public void setProcessInstanceId(String processInstanceId) { - this.processInstanceId = processInstanceId; - } - - @Override - public String getProcessInstanceId() { - return processInstanceId; - } - - @Override - public Serializable get(String key) { - return ctxData.get(key); - } - - @Override - public Serializable remove(String key) { - return ctxData.remove(key); - } - - @Override - public void put(String key, Serializable object) { - ctxData.put(key, object); - } - - @Override - public Set keySet() { - return Collections.unmodifiableSet(ctxData.keySet()); - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("ExecutionContextImpl ["); - builder.append("id=").append(processInstanceId); - builder.append(", variables="); - builder.append(ctxData.keySet()); - builder.append("]"); - return builder.toString(); - } - - @Override - public boolean isProcessCancelled() { - return markedAsCancelled; - } - - @Override - public void setCanceleProcessFlag() { - markedAsCancelled = true; - - } + private static final long serialVersionUID = 1L; + + private final Map ctxData = + Collections.synchronizedMap(new HashMap()); + + private String processInstanceId; + private boolean markedAsCancelled = false; + + /** + * Creates a new instance. + */ + public ExecutionContextImpl() { + + } + + /** + * Creates a new instance and associated it with a certain process instance. + */ + public ExecutionContextImpl(final String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + @Override + public void setProcessInstanceId(final String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + @Override + public String getProcessInstanceId() { + return processInstanceId; + } + + @Override + public Serializable get(final String key) { + return ctxData.get(key); + } + + @Override + public Serializable remove(final String key) { + return ctxData.remove(key); + } + + @Override + public void put(final String key, final Serializable object) { + ctxData.put(key, object); + } + + @Override + public Set keySet() { + return Collections.unmodifiableSet(ctxData.keySet()); + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("ExecutionContextImpl ["); + builder.append("id=").append(processInstanceId); + builder.append(", variables="); + builder.append(ctxData.keySet()); + builder.append("]"); + return builder.toString(); + } + + @Override + public boolean isProcessCancelled() { + return markedAsCancelled; + } + + @Override + public void setCanceleProcessFlag() { + markedAsCancelled = true; + + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ExpressionEvaluationContextImpl.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ExpressionEvaluationContextImpl.java index 694b8d0d..72ad456f 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ExpressionEvaluationContextImpl.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ExpressionEvaluationContextImpl.java @@ -1,29 +1,22 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process; import java.io.Serializable; @@ -31,40 +24,38 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; - import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; import at.gv.egiz.eaaf.core.api.idp.process.ExpressionEvaluationContext; /** * Context implementation used for expression evaluation only. - * + * * @author tknall - * + * */ public class ExpressionEvaluationContextImpl implements ExpressionEvaluationContext { - private static final long serialVersionUID = 1L; - - private Map ctxData; - - /** - * Creates a new instance and initializes it with data from a given process instance. - * - * @param processInstance - * The process instance. - */ - ExpressionEvaluationContextImpl(ProcessInstance processInstance) { - ExecutionContext executionContext = processInstance.getExecutionContext(); - Set keys = executionContext.keySet(); - ctxData = Collections.synchronizedMap(new HashMap(keys.size())); - for (String key : keys) { - ctxData.put(key, executionContext.get(key)); - } - } - - @Override - public Map getCtx() { - return Collections.unmodifiableMap(ctxData); - } + private static final long serialVersionUID = 1L; + + private final Map ctxData; + + /** + * Creates a new instance and initializes it with data from a given process instance. + * + * @param processInstance The process instance. + */ + ExpressionEvaluationContextImpl(final ProcessInstance processInstance) { + final ExecutionContext executionContext = processInstance.getExecutionContext(); + final Set keys = executionContext.keySet(); + ctxData = Collections.synchronizedMap(new HashMap(keys.size())); + for (final String key : keys) { + ctxData.put(key, executionContext.get(key)); + } + } + + @Override + public Map getCtx() { + return Collections.unmodifiableMap(ctxData); + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ProcessDefinitionParser.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ProcessDefinitionParser.java index f817f9fb..63ae66d5 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ProcessDefinitionParser.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ProcessDefinitionParser.java @@ -1,29 +1,22 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process; import java.io.IOException; @@ -32,7 +25,6 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Objects; - import javax.xml.XMLConstants; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventReader; @@ -48,203 +40,225 @@ import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.xml.sax.SAXException; - import at.gv.egiz.eaaf.core.impl.idp.process.model.EndEvent; import at.gv.egiz.eaaf.core.impl.idp.process.model.ProcessDefinition; import at.gv.egiz.eaaf.core.impl.idp.process.model.ProcessNode; import at.gv.egiz.eaaf.core.impl.idp.process.model.StartEvent; import at.gv.egiz.eaaf.core.impl.idp.process.model.TaskInfo; import at.gv.egiz.eaaf.core.impl.idp.process.model.Transition; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.xml.sax.SAXException; /** * Parses an XML representation of a process definition as defined by the respective XML schema. - *

transitionElements = new ArrayList<>(); - final List startEvents = new ArrayList<>(); - - reader = new EventReaderDelegate(reader) { - - @Override - public XMLEvent nextEvent() throws XMLStreamException { - XMLEvent event = super.nextEvent(); - - switch (event.getEventType()) { - case XMLStreamConstants.START_ELEMENT: - StartElement element = event.asStartElement(); - QName qname = element.getName(); - - if (NS.equals(qname.getNamespaceURI())) { - log.trace("Found process description element '{}'.", qname.getLocalPart()); - Attribute id = element.getAttributeByName(new QName("id")); - - switch (qname.getLocalPart()) { - case "ProcessDefinition": - if (id != null) { - pd.setId(id.getValue()); - } - break; - case "StartEvent": - StartEvent startEvent = new StartEvent(); - if (id != null) { - startEvent.setId(id.getValue()); - } - startEvents.add(startEvent); - break; - case "EndEvent": - EndEvent endEvent = new EndEvent(); - if (id != null) { - endEvent.setId(id.getValue()); - pd.getEndEvents().put(id.getValue(), endEvent); - } - break; - case "Transition": - transitionElements.add(element); - break; - case "Task": - TaskInfo taskInfo = new TaskInfo(); - if (id != null) { - taskInfo.setId(id.getValue()); - pd.getTaskInfos().put(id.getValue(), taskInfo); - } - Attribute async = element.getAttributeByName(new QName("async")); - if (async != null) { - taskInfo.setAsync(Boolean.valueOf(async.getValue())); - } - Attribute implementingClass = element.getAttributeByName(new QName("class")); - if (implementingClass != null) { - taskInfo.setTaskImplementingClass(implementingClass.getValue()); - } - break; - } - - } - - break; - } - - return event; - } - - }; - - // validator is not thread-safe - Validator validator = LazyProcessDefinitionSchemaHolder.PD_SCHEMA_INSTANCE.newValidator(); - validator.validate(new StAXSource(reader)); - log.trace("Process definition successfully schema validated."); - - // perform some basic checks - log.trace("Building model and performing some plausibility checks."); - if (startEvents.size() != 1) { - throw new ProcessDefinitionParserException("A ProcessDefinition must contain exactly one single StartEvent."); - } - pd.setStartEvent(startEvents.get(0)); - - // link transitions - Iterator transitions = transitionElements.iterator(); - while (transitions.hasNext()) { - StartElement element = transitions.next(); - Transition transition = new Transition(); - Attribute id = element.getAttributeByName(new QName("id")); - if (id != null) { - transition.setId(id.getValue()); - } - Attribute conditionExpression = element.getAttributeByName(new QName("conditionExpression")); - if (conditionExpression != null) { - transition.setConditionExpression(conditionExpression.getValue()); - } - Attribute from = element.getAttributeByName(new QName("from")); - if (from != null) { - ProcessNode fromNode = pd.getProcessNode(from.getValue()); - if (fromNode == null) { - throw new ProcessDefinitionParserException("Transition's 'from'-attribute refers to a non-existing event or task '" + from.getValue() + '.'); - } - if (fromNode instanceof EndEvent) { - throw new ProcessDefinitionParserException("Transition cannot start from end event."); - } - transition.setFrom(fromNode); - fromNode.getOutgoingTransitions().add(transition); - } - Attribute to = element.getAttributeByName(new QName("to")); - if (to != null) { - ProcessNode toNode = pd.getProcessNode(to.getValue()); - if (toNode == null) { - throw new ProcessDefinitionParserException("Transition's 'to'-attribute refers to a non-existing event or task '" + to.getValue() + '.'); - } - transition.setTo(toNode); - toNode.getIncomingTransitions().add(transition); - } - if (transition.getConditionExpression() == null && Objects.equals(transition.getFrom(), transition.getTo())) { - throw new ProcessDefinitionParserException("Transition's 'from' equals its 'to'. Since no 'conditionExpression' has been set this will cause a loop."); - } - } - log.debug("Process definition '{}' successfully parsed.", pd.getId()); - return pd; - - } catch (ProcessDefinitionParserException e) { - throw e; - } catch (XMLStreamException|IOException e) { - throw new ProcessDefinitionParserException("Unable to read process definition from inputstream.", e); - } catch (SAXException e) { - throw new ProcessDefinitionParserException("Schema validation of process description failed.", e); - } catch (Exception e) { - throw new ProcessDefinitionParserException("Internal error creating process definition from inputstream.", e); - } finally { - if (reader != null) { - try { - reader.close(); - } catch (XMLStreamException e) { - // error freeing resources - } - } - } - } + + private static final String NS = + "http://reference.e-government.gv.at/namespace/moa/process/definition/v1"; + + private static Logger log = LoggerFactory.getLogger(ProcessDefinitionParser.class); + + private static class LazyProcessDefinitionSchemaHolder { + private static final Schema PD_SCHEMA_INSTANCE; + + static { + try (InputStream in = + ProcessDefinitionParser.class.getResourceAsStream("/process/ProcessDefinition.xsd")) { + log.trace("Compiling process definition schema."); + final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); + // schema is thread-safe + PD_SCHEMA_INSTANCE = factory.newSchema(new StreamSource(in)); + } catch (final Exception e) { + throw new RuntimeException("Unable to compile process definition schema.", e); + } + } + } + + /** + * Parses an XML representation of a process definition. The representation is being validated in + * order to suffice the related XML schema. + * + * @param processDefinitionInputStream The process definition. + * @return A new process definition. + * @throws ProcessDefinitionParserException Thrown in case of error parsing the process + * definition. + */ + public ProcessDefinition parse(final InputStream processDefinitionInputStream) + throws ProcessDefinitionParserException { + XMLEventReader reader = null; + final ProcessDefinition pd = new ProcessDefinition(); + log.debug("Parsing and validating process definition."); + try { + + // Standard implementation of XMLInputFactory seems not to be thread-safe + final XMLInputFactory inputFactory = XMLInputFactory.newInstance(); + reader = inputFactory.createXMLEventReader(processDefinitionInputStream); + + final List transitionElements = new ArrayList<>(); + final List startEvents = new ArrayList<>(); + + reader = new EventReaderDelegate(reader) { + + @Override + public XMLEvent nextEvent() throws XMLStreamException { + final XMLEvent event = super.nextEvent(); + + switch (event.getEventType()) { + case XMLStreamConstants.START_ELEMENT: + final StartElement element = event.asStartElement(); + final QName qname = element.getName(); + + if (NS.equals(qname.getNamespaceURI())) { + log.trace("Found process description element '{}'.", qname.getLocalPart()); + final Attribute id = element.getAttributeByName(new QName("id")); + + switch (qname.getLocalPart()) { + case "ProcessDefinition": + if (id != null) { + pd.setId(id.getValue()); + } + break; + case "StartEvent": + final StartEvent startEvent = new StartEvent(); + if (id != null) { + startEvent.setId(id.getValue()); + } + startEvents.add(startEvent); + break; + case "EndEvent": + final EndEvent endEvent = new EndEvent(); + if (id != null) { + endEvent.setId(id.getValue()); + pd.getEndEvents().put(id.getValue(), endEvent); + } + break; + case "Transition": + transitionElements.add(element); + break; + case "Task": + final TaskInfo taskInfo = new TaskInfo(); + if (id != null) { + taskInfo.setId(id.getValue()); + pd.getTaskInfos().put(id.getValue(), taskInfo); + } + final Attribute async = element.getAttributeByName(new QName("async")); + if (async != null) { + taskInfo.setAsync(Boolean.valueOf(async.getValue())); + } + final Attribute implementingClass = + element.getAttributeByName(new QName("class")); + if (implementingClass != null) { + taskInfo.setTaskImplementingClass(implementingClass.getValue()); + } + break; + default: + log.warn("Ignore unknown event: {}", qname); + break; + } + + } + + break; + default: + log.warn("Ignore unknown event: {}", event); + break; + } + + return event; + } + + }; + + // validator is not thread-safe + final Validator validator = + LazyProcessDefinitionSchemaHolder.PD_SCHEMA_INSTANCE.newValidator(); + validator.validate(new StAXSource(reader)); + log.trace("Process definition successfully schema validated."); + + // perform some basic checks + log.trace("Building model and performing some plausibility checks."); + if (startEvents.size() != 1) { + throw new ProcessDefinitionParserException( + "A ProcessDefinition must contain exactly one single StartEvent."); + } + pd.setStartEvent(startEvents.get(0)); + + // link transitions + final Iterator transitions = transitionElements.iterator(); + while (transitions.hasNext()) { + final StartElement element = transitions.next(); + final Transition transition = new Transition(); + final Attribute id = element.getAttributeByName(new QName("id")); + if (id != null) { + transition.setId(id.getValue()); + } + final Attribute conditionExpression = + element.getAttributeByName(new QName("conditionExpression")); + if (conditionExpression != null) { + transition.setConditionExpression(conditionExpression.getValue()); + } + final Attribute from = element.getAttributeByName(new QName("from")); + if (from != null) { + final ProcessNode fromNode = pd.getProcessNode(from.getValue()); + if (fromNode == null) { + throw new ProcessDefinitionParserException( + "Transition's 'from'-attribute refers to a non-existing event or task '" + + from.getValue() + '.'); + } + if (fromNode instanceof EndEvent) { + throw new ProcessDefinitionParserException("Transition cannot start from end event."); + } + transition.setFrom(fromNode); + fromNode.getOutgoingTransitions().add(transition); + } + final Attribute to = element.getAttributeByName(new QName("to")); + if (to != null) { + final ProcessNode toNode = pd.getProcessNode(to.getValue()); + if (toNode == null) { + throw new ProcessDefinitionParserException( + "Transition's 'to'-attribute refers to a non-existing event or task '" + + to.getValue() + '.'); + } + transition.setTo(toNode); + toNode.getIncomingTransitions().add(transition); + } + if (transition.getConditionExpression() == null + && Objects.equals(transition.getFrom(), transition.getTo())) { + throw new ProcessDefinitionParserException( + "Transition's 'from' equals its 'to'. Since no 'conditionExpression' " + + "has been set this will cause a loop."); + } + } + log.debug("Process definition '{}' successfully parsed.", pd.getId()); + return pd; + + } catch (final ProcessDefinitionParserException e) { + throw e; + } catch (XMLStreamException | IOException e) { + throw new ProcessDefinitionParserException( + "Unable to read process definition from inputstream.", e); + } catch (final SAXException e) { + throw new ProcessDefinitionParserException("Schema validation of process description failed.", + e); + } catch (final Exception e) { + throw new ProcessDefinitionParserException( + "Internal error creating process definition from inputstream.", e); + } finally { + if (reader != null) { + try { + reader.close(); + } catch (final XMLStreamException e) { + e.printStackTrace(); + + } + } + } + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ProcessDefinitionParserException.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ProcessDefinitionParserException.java index 292b3881..472d6469 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ProcessDefinitionParserException.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ProcessDefinitionParserException.java @@ -1,61 +1,52 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process; /** * Exception thrown in case of error parsing a process definition. - * + * * @author tknall - * + * */ public class ProcessDefinitionParserException extends Exception { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - /** - * Creates a new parser exception providing a {@code message} describing the reason and the {@code cause}. - * - * @param message - * The message. - * @param cause - * The cause. - */ - public ProcessDefinitionParserException(String message, Throwable cause) { - super(message, cause); - } + /** + * Creates a new parser exception providing a {@code message} describing the reason and the + * {@code cause}. + * + * @param message The message. + * @param cause The cause. + */ + public ProcessDefinitionParserException(final String message, final Throwable cause) { + super(message, cause); + } - /** - * Creates a new parser exception providing a {@code message} describing the reason. - * - * @param message - * The message. - */ - public ProcessDefinitionParserException(String message) { - super(message); - } + /** + * Creates a new parser exception providing a {@code message} describing the reason. + * + * @param message The message. + */ + public ProcessDefinitionParserException(final String message) { + super(message); + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ProcessEngineImpl.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ProcessEngineImpl.java index 53f50e1f..0c4946af 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ProcessEngineImpl.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ProcessEngineImpl.java @@ -1,55 +1,39 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process; import java.io.InputStream; import java.io.Serializable; import java.util.HashMap; import java.util.Map; +import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; - -import org.apache.commons.collections4.IterableUtils; -import org.apache.commons.collections4.Predicate; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; - import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.data.EAAFConstants; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; import at.gv.egiz.eaaf.core.api.idp.process.ExpressionEvaluationContext; import at.gv.egiz.eaaf.core.api.idp.process.ExpressionEvaluator; import at.gv.egiz.eaaf.core.api.idp.process.ProcessEngine; -import at.gv.egiz.eaaf.core.api.idp.process.ProcessInstanceStoreDAO; +import at.gv.egiz.eaaf.core.api.idp.process.ProcessInstanceStoreDao; import at.gv.egiz.eaaf.core.api.idp.process.Task; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.exceptions.ProcessExecutionException; import at.gv.egiz.eaaf.core.impl.idp.process.dao.ProcessInstanceStore; import at.gv.egiz.eaaf.core.impl.idp.process.model.EndEvent; @@ -58,439 +42,491 @@ import at.gv.egiz.eaaf.core.impl.idp.process.model.ProcessNode; import at.gv.egiz.eaaf.core.impl.idp.process.model.StartEvent; import at.gv.egiz.eaaf.core.impl.idp.process.model.TaskInfo; import at.gv.egiz.eaaf.core.impl.idp.process.model.Transition; +import org.apache.commons.collections4.IterableUtils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; /** - * Process engine implementation allowing starting and continuing processes as well as providing means for cleanup actions. + * Process engine implementation allowing starting and continuing processes as well as providing + * means for cleanup actions. */ public class ProcessEngineImpl implements ProcessEngine { - - private final Logger log = LoggerFactory.getLogger(getClass()); - - @Autowired ProcessInstanceStoreDAO piStoreDao; - @Autowired ApplicationContext context; - - private final ProcessDefinitionParser pdp = new ProcessDefinitionParser(); - - private final Map processDefinitions = new ConcurrentHashMap(); - - private final static String MDC_CTX_PI_NAME = "processInstanceId"; - private final static String MDC_CTX_TASK_NAME = "taskId"; - - private ExpressionEvaluator transitionConditionExpressionEvaluator; - - @Override - public void registerProcessDefinition(ProcessDefinition processDefinition) { - log.info("Registering process definition '{}'.", processDefinition.getId()); - processDefinitions.put(processDefinition.getId(), processDefinition); - } - - @Override - public String registerProcessDefinition(InputStream processDefinitionInputStream) throws ProcessDefinitionParserException{ - final ProcessDefinition pd = pdp.parse(processDefinitionInputStream); - - postValidationOfProcessDefintion(pd); - - registerProcessDefinition(pd); - return pd.getId(); - } - - /** - * Sets the process definitions. - * - * @param processDefinitions - * The process definitions. - * @throws IllegalArgumentException - * In case the process definitions contain definitions with the same identifier. - */ - public void setProcessDefinitions(Iterable processDefinitions) { - this.processDefinitions.clear(); - for (final ProcessDefinition pd : processDefinitions) { - if (this.processDefinitions.containsKey(pd.getId())) { - throw new IllegalArgumentException("Duplicate process definition identifier '" + pd.getId() + "'."); - } - registerProcessDefinition(pd); - } - } - - /** - * Sets an expression evaluator that should be used to process transition condition expressions. - * @param transitionConditionExpressionEvaluator The expression evaluator. - */ - public void setTransitionConditionExpressionEvaluator( - ExpressionEvaluator transitionConditionExpressionEvaluator) { - this.transitionConditionExpressionEvaluator = transitionConditionExpressionEvaluator; - } - - - @Override - public String createProcessInstance(String processDefinitionId, ExecutionContext executionContext) throws ProcessExecutionException { - // look for respective process definition - final ProcessDefinition pd = processDefinitions.get(processDefinitionId); - if (pd == null) { - throw new ProcessExecutionException("Unable to find process definition for process '" + processDefinitionId + "'."); - } - // create and keep process instance - final ProcessInstance pi = new ProcessInstance(pd, executionContext); - log.info("Creating process instance from process definition '{}': {}", processDefinitionId, pi.getId()); - - try { - saveOrUpdateProcessInstance(pi); - - } catch (final EAAFException e) { - throw new ProcessExecutionException("Unable to persist process instance.", e); - } - - return pi.getId(); - } - - @Override - public String createProcessInstance(String processDefinitionId) throws ProcessExecutionException { - return createProcessInstance(processDefinitionId, null); - } - - @Override - public void start(IRequest pendingReq) throws ProcessExecutionException { - try { - if (StringUtils.isEmpty(pendingReq.getProcessInstanceId())) { - log.error("Pending-request with id:" + pendingReq.getPendingRequestId() - + " includes NO 'ProcessInstanceId'"); - throw new ProcessExecutionException("Pending-request with id:" + pendingReq.getPendingRequestId() - + " includes NO 'ProcessInstanceId'"); - } - - final ProcessInstance pi = loadProcessInstance(pendingReq.getProcessInstanceId()); - - if (pi == null ) { - throw new ProcessExecutionException("Process instance '" + pendingReq.getProcessInstanceId() + "' does not exist."); - - } - - MDC.put(MDC_CTX_PI_NAME, pi.getId()); - - if (!ProcessInstanceState.NOT_STARTED.equals(pi.getState())) { - throw new ProcessExecutionException("Process instance '" + pi.getId() + "' has already been started (current state is " + pi.getState() + ")."); - } - log.info("Starting process instance '{}'.", pi.getId()); - // execute process - pi.setState(ProcessInstanceState.STARTED); - execute(pi, pendingReq); - - //store ProcessInstance if it is not already ended - if (!ProcessInstanceState.ENDED.equals(pi.getState())) - saveOrUpdateProcessInstance(pi); - - } catch (final EAAFException e) { - throw new ProcessExecutionException("Unable to load/save process instance.", e); - - } finally { - MDC.remove(MDC_CTX_PI_NAME); - } - } - - @Override - public void signal(IRequest pendingReq) throws ProcessExecutionException { - - try { - if (StringUtils.isEmpty(pendingReq.getProcessInstanceId())) { - log.error("Pending-request with id:" + pendingReq.getPendingRequestId() - + " includes NO 'ProcessInstanceId'"); - throw new ProcessExecutionException("Pending-request with id:" + pendingReq.getPendingRequestId() - + " includes NO 'ProcessInstanceId'"); - } - - final ProcessInstance pi = loadProcessInstance(pendingReq.getProcessInstanceId()); - - if (pi == null ) { - throw new ProcessExecutionException("Process instance '" + pendingReq.getProcessInstanceId() + "' does not exist."); - - } - - MDC.put(MDC_CTX_PI_NAME, pi.getId()); - - if (!ProcessInstanceState.SUSPENDED.equals(pi.getState())) { - throw new ProcessExecutionException("Process instance '" + pi.getId() + "' has not been suspended (current state is " + pi.getState() + ")."); - } - - log.debug("Waking up process instance '{}'.", pi.getId()); - pi.setState(ProcessInstanceState.STARTED); - - //put pending-request ID on execution-context because it could be changed - pi.getExecutionContext().put(EAAFConstants.PARAM_HTTP_TARGET_PENDINGREQUESTID, pendingReq.getPendingRequestId()); - - execute(pi, pendingReq); - - //store ProcessInstance if it is not already ended - if (!ProcessInstanceState.ENDED.equals(pi.getState())) - saveOrUpdateProcessInstance(pi); - - } catch (final EAAFException e) { - throw new ProcessExecutionException("Unable to load/save process instance.", e); - - } finally { - MDC.remove(MDC_CTX_PI_NAME); - } - } - - - /** - * Instantiates a task implementation given by a {@link TaskInfo}. - * @param ti The task info. - * @return A Task implementation or {@code null} if the task info does not reference any task implementing classes. - * @throws ProcessExecutionException Thrown in case of error (when the referenced class does not implement {@link Task} for instance). - */ - private Task createTaskInstance(TaskInfo ti) throws ProcessExecutionException { - final String clazz = StringUtils.trimToNull(ti.getTaskImplementingClass()); - Task task = null; - - if (clazz != null) { - log.debug("Instantiating task implementing class '{}'.", clazz); - Object instanceClass = null; - try { - instanceClass = context.getBean(clazz); - - } catch (final Exception e) { - throw new ProcessExecutionException("Unable to get class '" + clazz + "' associated with task '" + ti.getId() + "' .", e); - - } - if (instanceClass == null || !(instanceClass instanceof Task)) { - throw new ProcessExecutionException("Class '" + clazz + "' associated with task '" + ti.getId() + "' is not assignable to " + Task.class.getName() + "."); - - } - try { - task = (Task) instanceClass; - - } catch (final Exception e) { - throw new ProcessExecutionException("Unable to instantiate class '" + clazz + "' associated with task '" + ti.getId() + "' .", e); - } - } - - return task; - } - - /** - * Starts/executes a given process instance. - * @param pi The process instance. - * @param pendingReq - * @throws ProcessExecutionException Thrown in case of error. - */ - private void execute(final ProcessInstance pi, IRequest pendingReq) throws ProcessExecutionException { - if (ProcessInstanceState.ENDED.equals(pi.getState())) { - throw new ProcessExecutionException("Process for instance '" + pi.getId() + "' has already been ended."); - } - final ProcessDefinition pd = pi.getProcessDefinition(); - final ProcessNode processNode = pd.getProcessNode(pi.getNextId()); - log.debug("Processing node '{}'.", processNode.getId()); - - // distinguish process node types StartEvent, TaskInfo and EndEvent - - if (processNode instanceof TaskInfo) { - // TaskInfo types need to be executed - final TaskInfo ti = (TaskInfo) processNode; - MDC.put(MDC_CTX_TASK_NAME, ti.getId()); - try { - log.debug("Processing task '{}'.", ti.getId()); - final Task task = createTaskInstance(ti); - if (task != null) { - try { - log.debug("Executing task implementation for task '{}'.", ti.getId()); - log.trace("Execution context before task execution: {}", pi.getExecutionContext().keySet()); - pendingReq = task.execute(pendingReq, pi.getExecutionContext()); - log.debug("Returned from execution of task '{}'.", ti.getId()); - log.trace("Execution context after task execution: {}", pi.getExecutionContext().keySet()); - - } catch (final Throwable t) { - throw new ProcessExecutionException("Error executing task '" + ti.getId() + "'.", t); - - } - - //check if process was cancelled dynamically by task - if (pi.getExecutionContext().isProcessCancelled()) { - log.debug("Processing task '{}' was cancelled by Task: '{}'.", pi.getId(), ti.getId()); - processFinishEvent(pi); - return; - - } - - } else { - log.debug("No task implementing class set."); - - } - } finally { - MDC.remove(MDC_CTX_TASK_NAME); - - } - - } else if (processNode instanceof EndEvent) { - processFinishEvent(pi); - return; - - } - - final ExpressionEvaluationContext expressionContext = new ExpressionEvaluationContextImpl(pi); - - // traverse pointer - final Transition t = IterableUtils.find(processNode.getOutgoingTransitions(), new Predicate() { - @Override - public boolean evaluate(Transition transition) { - if (transitionConditionExpressionEvaluator != null && transition.getConditionExpression() != null) { - log.trace("Evaluating transition expression '{}'.", transition.getConditionExpression()); - return transitionConditionExpressionEvaluator.evaluate(expressionContext, transition.getConditionExpression()); - } - return true; - } - }); - if (t == null) { - throw new ProcessExecutionException("No valid transition starting from process node '" + processNode.getId()+ "'."); - } - log.trace("Found suitable transition: {}", t); - // update pointer - log.trace("Shifting process token from '{}' to '{}'.", pi.getNextId(), t.getTo().getId()); - pi.setNextId(t.getTo().getId()); - - // inspect current task - if (t.getTo() instanceof TaskInfo && (((TaskInfo) t.getTo()).isAsync())) { - // immediately return in case of asynchonous task - log.debug("Suspending process instance '{}' for asynchronous task '{}'.", pi.getId(), t.getTo().getId()); - pi.setState(ProcessInstanceState.SUSPENDED); - return; - } - - // continue execution in case of StartEvent or Task - if (processNode instanceof StartEvent || processNode instanceof TaskInfo) { - execute(pi, pendingReq); - } - } - - @Override - public ProcessInstance getProcessInstance(String processInstanceId) { - - ProcessInstance processInstance; - try { - processInstance = loadProcessInstance(processInstanceId); - - } catch (final EAAFException e) { - throw new RuntimeException("The process instance '" + processInstanceId + "' could not be retrieved.", e); - } - - if (processInstance == null) { - throw new IllegalArgumentException("The process instance '" + processInstanceId + "' does not/no longer exist."); - } - - return processInstance; - } - - /** - * Persists a {@link ProcessInstance} to the database. - * @param processInstance The object to persist. - * @throws MOADatabaseException Thrown if an error occurs while accessing the database. - */ - private void saveOrUpdateProcessInstance(ProcessInstance processInstance) throws EAAFException { - final ProcessInstanceStore store = new ProcessInstanceStore(); - - final ExecutionContext ctx = processInstance.getExecutionContext(); - - final Map ctxData = new HashMap(); - for (final String key : ctx.keySet()) { - ctxData.put(key, ctx.get(key)); - } - store.setExecutionContextData(ctxData); - - store.setNextTaskId(processInstance.getNextId()); - store.setProcessDefinitionId(processInstance.getProcessDefinition().getId()); - - store.setProcessInstanceId(processInstance.getId()); - store.setProcessState(processInstance.getState()); - - piStoreDao.saveOrUpdate(store); - } - - /** - * Load a {@link ProcessInstance} with a certain id from the database. - * @param processInstanceId The process instance id - * @return The process instance corresponding to the id or {@code null} if no such object is found. - * @throws MOADatabaseException Thrown if an error occurs while accessing the database. - */ - private ProcessInstance loadProcessInstance(String processInstanceId) throws EAAFException { - - final ProcessInstanceStore piStore = piStoreDao.load(processInstanceId); - - if (piStore == null) { - return null; - } - - final ExecutionContext executionContext = new ExecutionContextImpl(piStore.getProcessInstanceId()); - - final Map executionContextData = piStore.getExecutionContextData(); - for (final String key : executionContextData.keySet()) { - executionContext.put(key, executionContextData.get(key)); - } - - final ProcessInstance pi = new ProcessInstance(processDefinitions.get(piStore.getProcessDefinitionId()), executionContext); - pi.setNextId(piStore.getNextTaskId()); - pi.setState(piStore.getProcessState()); - - return pi; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.process.ProcessEngine#deleteProcessInstance(java.lang.String) - */ - @Override - public void deleteProcessInstance(String processInstanceId) throws ProcessExecutionException { - if (StringUtils.isEmpty(processInstanceId)) { - throw new ProcessExecutionException("Unable to remove process instance: ProcessInstanceId is empty"); - - } - - try { - piStoreDao.remove(processInstanceId); - - } catch (final EAAFException e) { - throw new ProcessExecutionException("Unable to remove process instance.", e); - - } - - } - - /** - * Finish a process-flow and remove any process-flow related information - * - * @param pi - * @throws ProcessExecutionException - */ - private void processFinishEvent(ProcessInstance pi) throws ProcessExecutionException { - log.info("Finishing process instance '{}'.", pi.getId()); - - try { - piStoreDao.remove(pi.getId()); - - } catch (final EAAFException e) { - throw new ProcessExecutionException("Unable to remove process instance.", e); - - } - pi.setState(ProcessInstanceState.ENDED); - log.debug("Final process context: {}", pi.getExecutionContext().keySet()); - - } - - /** - * Perform some post-validation operations on process definition - * - * Like: check if all tasks that are defined are available on context - * - * @param pd - * @throws ProcessDefinitionParserException - */ - private void postValidationOfProcessDefintion(ProcessDefinition pd) throws ProcessDefinitionParserException{ - try { - for(final TaskInfo task : pd.getTaskInfos().values()) { - createTaskInstance(task); - } - - } catch (final ProcessExecutionException e) { - log.error("Post-validation of process definition: {} find an error: {}", pd.getId(), e.getMessage()); - throw new ProcessDefinitionParserException("Post-validation find an error in process definition:" + pd.getId(), e); - - } - } + + private final Logger log = LoggerFactory.getLogger(getClass()); + + @Autowired + ProcessInstanceStoreDao piStoreDao; + @Autowired + ApplicationContext context; + + private final ProcessDefinitionParser pdp = new ProcessDefinitionParser(); + + private final Map processDefinitions = new ConcurrentHashMap<>(); + + private static final String MDC_CTX_PI_NAME = "processInstanceId"; + private static final String MDC_CTX_TASK_NAME = "taskId"; + + private ExpressionEvaluator transitionConditionExpressionEvaluator; + + @Override + public void registerProcessDefinition(final ProcessDefinition processDefinition) { + log.info("Registering process definition '{}'.", processDefinition.getId()); + processDefinitions.put(processDefinition.getId(), processDefinition); + } + + @Override + public String registerProcessDefinition(final InputStream processDefinitionInputStream) + throws ProcessDefinitionParserException { + final ProcessDefinition pd = pdp.parse(processDefinitionInputStream); + + postValidationOfProcessDefintion(pd); + + registerProcessDefinition(pd); + return pd.getId(); + } + + /** + * Sets the process definitions. + * + * @param processDefinitions The process definitions. + * @throws IllegalArgumentException In case the process definitions contain definitions with the + * same identifier. + */ + public void setProcessDefinitions(final Iterable processDefinitions) { + this.processDefinitions.clear(); + for (final ProcessDefinition pd : processDefinitions) { + if (this.processDefinitions.containsKey(pd.getId())) { + throw new IllegalArgumentException( + "Duplicate process definition identifier '" + pd.getId() + "'."); + } + registerProcessDefinition(pd); + } + } + + /** + * Sets an expression evaluator that should be used to process transition condition expressions. + * + * @param transitionConditionExpressionEvaluator The expression evaluator. + */ + public void setTransitionConditionExpressionEvaluator( + final ExpressionEvaluator transitionConditionExpressionEvaluator) { + this.transitionConditionExpressionEvaluator = transitionConditionExpressionEvaluator; + } + + + @Override + public String createProcessInstance(final String processDefinitionId, + final ExecutionContext executionContext) throws ProcessExecutionException { + // look for respective process definition + final ProcessDefinition pd = processDefinitions.get(processDefinitionId); + if (pd == null) { + throw new ProcessExecutionException( + "Unable to find process definition for process '" + processDefinitionId + "'."); + } + // create and keep process instance + final ProcessInstance pi = new ProcessInstance(pd, executionContext); + log.info("Creating process instance from process definition '{}': {}", processDefinitionId, + pi.getId()); + + try { + saveOrUpdateProcessInstance(pi); + + } catch (final EaafException e) { + throw new ProcessExecutionException("Unable to persist process instance.", e); + } + + return pi.getId(); + } + + @Override + public String createProcessInstance(final String processDefinitionId) + throws ProcessExecutionException { + return createProcessInstance(processDefinitionId, null); + } + + @Override + public void start(final IRequest pendingReq) throws ProcessExecutionException { + try { + if (StringUtils.isEmpty(pendingReq.getProcessInstanceId())) { + log.error("Pending-request with id:" + pendingReq.getPendingRequestId() + + " includes NO 'ProcessInstanceId'"); + throw new ProcessExecutionException("Pending-request with id:" + + pendingReq.getPendingRequestId() + " includes NO 'ProcessInstanceId'"); + } + + final ProcessInstance pi = loadProcessInstance(pendingReq.getProcessInstanceId()); + + if (pi == null) { + throw new ProcessExecutionException( + "Process instance '" + pendingReq.getProcessInstanceId() + "' does not exist."); + + } + + MDC.put(MDC_CTX_PI_NAME, pi.getId()); + + if (!ProcessInstanceState.NOT_STARTED.equals(pi.getState())) { + throw new ProcessExecutionException("Process instance '" + pi.getId() + + "' has already been started (current state is " + pi.getState() + ")."); + } + log.info("Starting process instance '{}'.", pi.getId()); + // execute process + pi.setState(ProcessInstanceState.STARTED); + execute(pi, pendingReq); + + // store ProcessInstance if it is not already ended + if (!ProcessInstanceState.ENDED.equals(pi.getState())) { + saveOrUpdateProcessInstance(pi); + } + + } catch (final EaafException e) { + throw new ProcessExecutionException("Unable to load/save process instance.", e); + + } finally { + MDC.remove(MDC_CTX_PI_NAME); + } + } + + @Override + public void signal(final IRequest pendingReq) throws ProcessExecutionException { + + try { + if (StringUtils.isEmpty(pendingReq.getProcessInstanceId())) { + log.error("Pending-request with id:" + pendingReq.getPendingRequestId() + + " includes NO 'ProcessInstanceId'"); + throw new ProcessExecutionException("Pending-request with id:" + + pendingReq.getPendingRequestId() + " includes NO 'ProcessInstanceId'"); + } + + final ProcessInstance pi = loadProcessInstance(pendingReq.getProcessInstanceId()); + + if (pi == null) { + throw new ProcessExecutionException( + "Process instance '" + pendingReq.getProcessInstanceId() + "' does not exist."); + + } + + MDC.put(MDC_CTX_PI_NAME, pi.getId()); + + if (!ProcessInstanceState.SUSPENDED.equals(pi.getState())) { + throw new ProcessExecutionException("Process instance '" + pi.getId() + + "' has not been suspended (current state is " + pi.getState() + ")."); + } + + log.debug("Waking up process instance '{}'.", pi.getId()); + pi.setState(ProcessInstanceState.STARTED); + + // put pending-request ID on execution-context because it could be changed + pi.getExecutionContext().put(EAAFConstants.PARAM_HTTP_TARGET_PENDINGREQUESTID, + pendingReq.getPendingRequestId()); + + execute(pi, pendingReq); + + // store ProcessInstance if it is not already ended + if (!ProcessInstanceState.ENDED.equals(pi.getState())) { + saveOrUpdateProcessInstance(pi); + } + + } catch (final EaafException e) { + throw new ProcessExecutionException("Unable to load/save process instance.", e); + + } finally { + MDC.remove(MDC_CTX_PI_NAME); + } + } + + + /** + * Instantiates a task implementation given by a {@link TaskInfo}. + * + * @param ti The task info. + * @return A Task implementation or {@code null} if the task info does not reference any task + * implementing classes. + * @throws ProcessExecutionException Thrown in case of error (when the referenced class does not + * implement {@link Task} for instance). + */ + private Task createTaskInstance(final TaskInfo ti) throws ProcessExecutionException { + final String clazz = StringUtils.trimToNull(ti.getTaskImplementingClass()); + Task task = null; + + if (clazz != null) { + log.debug("Instantiating task implementing class '{}'.", clazz); + Object instanceClass = null; + try { + instanceClass = context.getBean(clazz); + + } catch (final Exception e) { + throw new ProcessExecutionException( + "Unable to get class '" + clazz + "' associated with task '" + ti.getId() + "' .", e); + + } + if (instanceClass == null || !(instanceClass instanceof Task)) { + throw new ProcessExecutionException("Class '" + clazz + "' associated with task '" + + ti.getId() + "' is not assignable to " + Task.class.getName() + "."); + + } + try { + task = (Task) instanceClass; + + } catch (final Exception e) { + throw new ProcessExecutionException("Unable to instantiate class '" + clazz + + "' associated with task '" + ti.getId() + "' .", e); + } + } + + return task; + } + + /** + * Starts/executes a given process instance. + * + * @param pi The process instance. + * @param pendingReq current pending request + * @throws ProcessExecutionException Thrown in case of error. + */ + private void execute(final ProcessInstance pi, IRequest pendingReq) + throws ProcessExecutionException { + if (ProcessInstanceState.ENDED.equals(pi.getState())) { + throw new ProcessExecutionException( + "Process for instance '" + pi.getId() + "' has already been ended."); + } + final ProcessDefinition pd = pi.getProcessDefinition(); + final ProcessNode processNode = pd.getProcessNode(pi.getNextId()); + log.debug("Processing node '{}'.", processNode.getId()); + + // distinguish process node types StartEvent, TaskInfo and EndEvent + + if (processNode instanceof TaskInfo) { + // TaskInfo types need to be executed + final TaskInfo ti = (TaskInfo) processNode; + MDC.put(MDC_CTX_TASK_NAME, ti.getId()); + try { + log.debug("Processing task '{}'.", ti.getId()); + final Task task = createTaskInstance(ti); + if (task != null) { + try { + log.debug("Executing task implementation for task '{}'.", ti.getId()); + log.trace("Execution context before task execution: {}", + pi.getExecutionContext().keySet()); + pendingReq = task.execute(pendingReq, pi.getExecutionContext()); + log.debug("Returned from execution of task '{}'.", ti.getId()); + log.trace("Execution context after task execution: {}", + pi.getExecutionContext().keySet()); + + } catch (final Throwable t) { + throw new ProcessExecutionException("Error executing task '" + ti.getId() + "'.", t); + + } + + // check if process was cancelled dynamically by task + if (pi.getExecutionContext().isProcessCancelled()) { + log.debug("Processing task '{}' was cancelled by Task: '{}'.", pi.getId(), ti.getId()); + processFinishEvent(pi); + return; + + } + + } else { + log.debug("No task implementing class set."); + + } + } finally { + MDC.remove(MDC_CTX_TASK_NAME); + + } + + } else if (processNode instanceof EndEvent) { + processFinishEvent(pi); + return; + + } + + final ExpressionEvaluationContext expressionContext = new ExpressionEvaluationContextImpl(pi); + + // traverse pointer + final Transition t = IterableUtils.find(processNode.getOutgoingTransitions(), transition -> { + if (transitionConditionExpressionEvaluator != null + && transition.getConditionExpression() != null) { + log.trace("Evaluating transition expression '{}'.", transition.getConditionExpression()); + return transitionConditionExpressionEvaluator.evaluate(expressionContext, + transition.getConditionExpression()); + } + return true; + }); + if (t == null) { + throw new ProcessExecutionException( + "No valid transition starting from process node '" + processNode.getId() + "'."); + } + log.trace("Found suitable transition: {}", t); + // update pointer + log.trace("Shifting process token from '{}' to '{}'.", pi.getNextId(), t.getTo().getId()); + pi.setNextId(t.getTo().getId()); + + // inspect current task + if (t.getTo() instanceof TaskInfo && (((TaskInfo) t.getTo()).isAsync())) { + // immediately return in case of asynchonous task + log.debug("Suspending process instance '{}' for asynchronous task '{}'.", pi.getId(), + t.getTo().getId()); + pi.setState(ProcessInstanceState.SUSPENDED); + return; + } + + // continue execution in case of StartEvent or Task + if (processNode instanceof StartEvent || processNode instanceof TaskInfo) { + execute(pi, pendingReq); + } + } + + @Override + public ProcessInstance getProcessInstance(final String processInstanceId) { + + ProcessInstance processInstance; + try { + processInstance = loadProcessInstance(processInstanceId); + + } catch (final EaafException e) { + throw new RuntimeException( + "The process instance '" + processInstanceId + "' could not be retrieved.", e); + } + + if (processInstance == null) { + throw new IllegalArgumentException( + "The process instance '" + processInstanceId + "' does not/no longer exist."); + } + + return processInstance; + } + + /** + * Persists a {@link ProcessInstance} to the database. + * + * @param processInstance The object to persist. + * @throws MOADatabaseException Thrown if an error occurs while accessing the database. + */ + private void saveOrUpdateProcessInstance(final ProcessInstance processInstance) + throws EaafException { + final ProcessInstanceStore store = new ProcessInstanceStore(); + + final ExecutionContext ctx = processInstance.getExecutionContext(); + + final Map ctxData = new HashMap<>(); + for (final String key : ctx.keySet()) { + ctxData.put(key, ctx.get(key)); + } + store.setExecutionContextData(ctxData); + + store.setNextTaskId(processInstance.getNextId()); + store.setProcessDefinitionId(processInstance.getProcessDefinition().getId()); + + store.setProcessInstanceId(processInstance.getId()); + store.setProcessState(processInstance.getState()); + + piStoreDao.saveOrUpdate(store); + } + + /** + * Load a {@link ProcessInstance} with a certain id from the database. + * + * @param processInstanceId The process instance id + * @return The process instance corresponding to the id or {@code null} if no such object is + * found. + * @throws MOADatabaseException Thrown if an error occurs while accessing the database. + */ + private ProcessInstance loadProcessInstance(final String processInstanceId) throws EaafException { + + final ProcessInstanceStore piStore = piStoreDao.load(processInstanceId); + + if (piStore == null) { + return null; + } + + final ExecutionContext executionContext = + new ExecutionContextImpl(piStore.getProcessInstanceId()); + + final Map executionContextData = piStore.getExecutionContextData(); + for (final Entry el : executionContextData.entrySet()) { + executionContext.put(el.getKey(), el.getValue()); + } + + final ProcessInstance pi = new ProcessInstance( + processDefinitions.get(piStore.getProcessDefinitionId()), executionContext); + pi.setNextId(piStore.getNextTaskId()); + pi.setState(piStore.getProcessState()); + + return pi; + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.process.ProcessEngine#deleteProcessInstance(java.lang.String) + */ + @Override + public void deleteProcessInstance(final String processInstanceId) + throws ProcessExecutionException { + if (StringUtils.isEmpty(processInstanceId)) { + throw new ProcessExecutionException( + "Unable to remove process instance: ProcessInstanceId is empty"); + + } + + try { + piStoreDao.remove(processInstanceId); + + } catch (final EaafException e) { + throw new ProcessExecutionException("Unable to remove process instance.", e); + + } + + } + + /** + * Finish a process-flow and remove any process-flow related information. + * + * @param pi current process instance + * @throws ProcessExecutionException In case of an process error + */ + private void processFinishEvent(final ProcessInstance pi) throws ProcessExecutionException { + log.info("Finishing process instance '{}'.", pi.getId()); + + try { + piStoreDao.remove(pi.getId()); + + } catch (final EaafException e) { + throw new ProcessExecutionException("Unable to remove process instance.", e); + + } + pi.setState(ProcessInstanceState.ENDED); + log.debug("Final process context: {}", pi.getExecutionContext().keySet()); + + } + + /** + * Perform some post-validation operations on process definition. + * + *

+ * Like: check if all tasks that are defined are available on context + *

+ * + * @param pd current process definition + * @throws ProcessDefinitionParserException In case of a parser error + */ + private void postValidationOfProcessDefintion(final ProcessDefinition pd) + throws ProcessDefinitionParserException { + try { + for (final TaskInfo task : pd.getTaskInfos().values()) { + createTaskInstance(task); + } + + } catch (final ProcessExecutionException e) { + log.error("Post-validation of process definition: {} find an error: {}", pd.getId(), + e.getMessage()); + throw new ProcessDefinitionParserException( + "Post-validation find an error in process definition:" + pd.getId(), e); + + } + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ProcessInstance.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ProcessInstance.java index 6db1dc7d..69683529 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ProcessInstance.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ProcessInstance.java @@ -1,190 +1,185 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process; import java.io.Serializable; import java.util.Date; - +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.impl.idp.process.model.ProcessDefinition; +import at.gv.egiz.eaaf.core.impl.idp.process.support.SecureRandomHolder; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.time.DurationFormatUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; -import at.gv.egiz.eaaf.core.impl.idp.process.model.ProcessDefinition; -import at.gv.egiz.eaaf.core.impl.idp.process.support.SecureRandomHolder; - /** - * Represents a process being executed. The process instance provides information about the process and its state. - * + * Represents a process being executed. The process instance provides information about the process + * and its state. + * * @author tknall - * + * */ public class ProcessInstance implements Serializable { - private static final long serialVersionUID = 1L; - private static final int RND_ID_LENGTH = 22; - - private final ProcessDefinition processDefinition; - private String nextId; - private Date lru; - private final ExecutionContext executionContext; - private ProcessInstanceState state = ProcessInstanceState.NOT_STARTED; - - private final Logger log = LoggerFactory.getLogger(getClass()); - - /** - * Creates a new process instance, based on a given process definition and a - * given execution context. If the given execution context is {@code null} a new execution context will be created.

- * The process instance id of the execution context will be newly generated if it is {@code null} in the execution context. - * - * @param processDefinition - * The process definition. - * @param executionContext - * The execution context (may be {@code null}). If {@code null} a new execution context will be created internally. - */ - ProcessInstance(ProcessDefinition processDefinition, ExecutionContext executionContext) { - this.processDefinition = processDefinition; - nextId = processDefinition.getStartEvent().getId(); - if (executionContext == null) { - executionContext = new ExecutionContextImpl(); - } - if (executionContext.getProcessInstanceId() == null) { - final String pdIdLocalPart = RandomStringUtils.random(RND_ID_LENGTH, 0, 0, true, true, null, - SecureRandomHolder.getInstance()); - executionContext.setProcessInstanceId(this.processDefinition.getId() + "-" + pdIdLocalPart); - } else { - log.debug("Using process instance id from execution context."); - } - log.debug("Creating process instance with id '{}'.", executionContext.getProcessInstanceId()); - this.executionContext = executionContext; - touch(); - } - - /** - * Returns the underlying process definition. - * - * @return The underlying process definition. - */ - ProcessDefinition getProcessDefinition() { - touch(); - return processDefinition; - } - - /** - * Returns the id of the process node to be executed next. - * - * @return The process node pointer indicating the process node to be executed next. - */ - public String getNextId() { - touch(); - return nextId; - } - - /** - * Sets the internal pointer to the process node to be executed next. - * - * @param nextId - * The process node id to be executed next. - */ - void setNextId(String nextId) { - touch(); - this.nextId = nextId; - } - - /** - * Returns the current state of the process instance. - * - * @return The current state. - */ - public ProcessInstanceState getState() { - touch(); - return state; - } - - /** - * Sets the current state of the process instance. - * - * @param state - * The current state. - */ - void setState(ProcessInstanceState state) { - touch(); - this.state = state; - } - - public String getId() { - touch(); - return executionContext.getProcessInstanceId(); - } - - /** - * Updates the last recently used date of the process instance. - */ - private void touch() { - lru = new Date(); - } - - /** - * Returns the date the process instance has been accessed last. - * - * @return The last recently used date. - */ - Date getLru() { - return lru; - } - - /** - * Returns the associated execution context. - * @return The execution context (never {@code null}). - */ - public ExecutionContext getExecutionContext() { - touch(); - return executionContext; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("ProcessInstance ["); - builder.append("id=").append(executionContext.getProcessInstanceId()); - builder.append(", idle since=").append( - DurationFormatUtils.formatDurationWords(new Date().getTime() - this.lru.getTime(), true, true)); - if (processDefinition != null) { - builder.append(", processDefinition.id="); - builder.append(processDefinition.getId()); - } - if (nextId != null) { - builder.append(", nextId="); - builder.append(nextId); - } - builder.append(", executionContext=").append(executionContext); - builder.append("]"); - return builder.toString(); - } + private static final long serialVersionUID = 1L; + private static final int RND_ID_LENGTH = 22; + + private final ProcessDefinition processDefinition; + private String nextId; + private Date lru; + private final ExecutionContext executionContext; + private ProcessInstanceState state = ProcessInstanceState.NOT_STARTED; + + + + /** + * Creates a new process instance, based on a given process definition and a given execution + * context. If the given execution context is {@code null} a new execution context will be + * created. + *

+ * The process instance id of the execution context will be newly generated if it is {@code null} + * in the execution context. + * + * @param processDefinition The process definition. + * @param executionContext The execution context (may be {@code null}). If {@code null} a new + * execution context will be created internally. + */ + ProcessInstance(final ProcessDefinition processDefinition, ExecutionContext executionContext) { + final Logger log = LoggerFactory.getLogger(getClass()); + + this.processDefinition = processDefinition; + nextId = processDefinition.getStartEvent().getId(); + if (executionContext == null) { + executionContext = new ExecutionContextImpl(); + } + if (executionContext.getProcessInstanceId() == null) { + final String pdIdLocalPart = RandomStringUtils.random(RND_ID_LENGTH, 0, 0, true, true, null, + SecureRandomHolder.getInstance()); + executionContext.setProcessInstanceId(this.processDefinition.getId() + "-" + pdIdLocalPart); + } else { + log.debug("Using process instance id from execution context."); + } + log.debug("Creating process instance with id '{}'.", executionContext.getProcessInstanceId()); + this.executionContext = executionContext; + touch(); + } + + /** + * Returns the underlying process definition. + * + * @return The underlying process definition. + */ + ProcessDefinition getProcessDefinition() { + touch(); + return processDefinition; + } + + /** + * Returns the id of the process node to be executed next. + * + * @return The process node pointer indicating the process node to be executed next. + */ + public String getNextId() { + touch(); + return nextId; + } + + /** + * Sets the internal pointer to the process node to be executed next. + * + * @param nextId The process node id to be executed next. + */ + void setNextId(final String nextId) { + touch(); + this.nextId = nextId; + } + + /** + * Returns the current state of the process instance. + * + * @return The current state. + */ + public ProcessInstanceState getState() { + touch(); + return state; + } + + /** + * Sets the current state of the process instance. + * + * @param state The current state. + */ + void setState(final ProcessInstanceState state) { + touch(); + this.state = state; + } + + public String getId() { + touch(); + return executionContext.getProcessInstanceId(); + } + + /** + * Updates the last recently used date of the process instance. + */ + private void touch() { + lru = new Date(); + } + + /** + * Returns the date the process instance has been accessed last. + * + * @return The last recently used date. + */ + Date getLru() { + return lru; + } + + /** + * Returns the associated execution context. + * + * @return The execution context (never {@code null}). + */ + public ExecutionContext getExecutionContext() { + touch(); + return executionContext; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("ProcessInstance ["); + builder.append("id=").append(executionContext.getProcessInstanceId()); + builder.append(", idle since=").append(DurationFormatUtils + .formatDurationWords(new Date().getTime() - this.lru.getTime(), true, true)); + if (processDefinition != null) { + builder.append(", processDefinition.id="); + builder.append(processDefinition.getId()); + } + if (nextId != null) { + builder.append(", nextId="); + builder.append(nextId); + } + builder.append(", executionContext=").append(executionContext); + builder.append("]"); + return builder.toString(); + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ProcessInstanceState.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ProcessInstanceState.java index 1abf5b86..e6bfa480 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ProcessInstanceState.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/ProcessInstanceState.java @@ -1,56 +1,51 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process; /** * Represents a certain process instance state. + * * @author tknall * */ public enum ProcessInstanceState { - - /** - * Indicates that the process with this process instance has not yet been started. - */ - NOT_STARTED, - - /** - * Indicates that the process is currently running. - */ - STARTED, - - /** - * Indicates that the process has been suspended until being waken up by someonce calling {@code signal}. - */ - SUSPENDED, - - /** - * Indicates that the process has been completed. - */ - ENDED + + /** + * Indicates that the process with this process instance has not yet been started. + */ + NOT_STARTED, + + /** + * Indicates that the process is currently running. + */ + STARTED, + + /** + * Indicates that the process has been suspended until being waken up by someonce calling + * {@code signal}. + */ + SUSPENDED, + + /** + * Indicates that the process has been completed. + */ + ENDED } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/dao/ProcessInstanceStore.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/dao/ProcessInstanceStore.java index 0fee29e5..f1abaef3 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/dao/ProcessInstanceStore.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/dao/ProcessInstanceStore.java @@ -1,99 +1,91 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process.dao; import java.io.Serializable; import java.util.Map; - import at.gv.egiz.eaaf.core.impl.idp.process.ProcessInstanceState; -public class ProcessInstanceStore implements Serializable{ +public class ProcessInstanceStore implements Serializable { + + private static final long serialVersionUID = -6147519767313903808L; + + /** + * A process instance identifier qualifies as natural primary key by satisfying these requirements. + * ("unique, constant, required"): + *

    + *
  • unique value
  • + *
  • never changes (immutable)
  • + *
  • never {@code null}
  • + *
+ */ - private static final long serialVersionUID = -6147519767313903808L; + private String processInstanceId; - /** - * A process instance identifier qualifies as natural primary key by satisfying these requirements - * ("unique, constant, required"): - *
    - *
  • unique value
  • - *
  • never changes (immutable)
  • - *
  • never {@code null}
  • - *
- */ + private String processDefinitionId; - private String processInstanceId; + private String nextTaskId; - private String processDefinitionId; + private ProcessInstanceState processState; - private String nextTaskId; + private Map executionContextData; - private ProcessInstanceState processState; - - private Map executionContextData; - - public String getProcessInstanceId() { - return processInstanceId; - } + public String getProcessInstanceId() { + return processInstanceId; + } - public String getProcessDefinitionId() { - return processDefinitionId; - } + public String getProcessDefinitionId() { + return processDefinitionId; + } - public String getNextTaskId() { - return nextTaskId; - } + public String getNextTaskId() { + return nextTaskId; + } - public ProcessInstanceState getProcessState() { - return processState; - } + public ProcessInstanceState getProcessState() { + return processState; + } - @SuppressWarnings("unchecked") - public Map getExecutionContextData() { - return executionContextData; - } + @SuppressWarnings("unchecked") + public Map getExecutionContextData() { + return executionContextData; + } - public void setProcessInstanceId(String processInstanceId) { - this.processInstanceId = processInstanceId; - } + public void setProcessInstanceId(final String processInstanceId) { + this.processInstanceId = processInstanceId; + } - public void setProcessDefinitionId(String processDefinitionId) { - this.processDefinitionId = processDefinitionId; - } + public void setProcessDefinitionId(final String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } - public void setNextTaskId(String nextTaskId) { - this.nextTaskId = nextTaskId; - } + public void setNextTaskId(final String nextTaskId) { + this.nextTaskId = nextTaskId; + } - public void setProcessState(ProcessInstanceState processState) { - this.processState = processState; - } + public void setProcessState(final ProcessInstanceState processState) { + this.processState = processState; + } - public void setExecutionContextData(Map executionContextData) { - this.executionContextData = executionContextData; - } + public void setExecutionContextData(final Map executionContextData) { + this.executionContextData = executionContextData; + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/dao/ProcessInstanceStoreDAOImpl.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/dao/ProcessInstanceStoreDAOImpl.java deleted file mode 100644 index 681c9707..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/dao/ProcessInstanceStoreDAOImpl.java +++ /dev/null @@ -1,97 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.process.dao; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import at.gv.egiz.eaaf.core.api.idp.process.ProcessInstanceStoreDAO; -import at.gv.egiz.eaaf.core.api.storage.ITransactionStorage; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; - -/** - * Database backed implementation of the {@link ProcessInstanceStoreDAO} - * interface. - */ -@Service("ProcessInstanceStoreage") -public class ProcessInstanceStoreDAOImpl implements ProcessInstanceStoreDAO { - - private Logger log = LoggerFactory.getLogger(getClass()); - - @Autowired ITransactionStorage transactionStorage; - - @Override - public void saveOrUpdate(ProcessInstanceStore pIStore) throws EAAFException { - try { - transactionStorage.put(pIStore.getProcessInstanceId(), pIStore, -1); - log.debug("Store process instance with='{}' in the database.", pIStore.getProcessInstanceId()); - - } catch (EAAFException e) { - log.warn("ProcessInstanceStore could not be persisted to the database."); - throw e; - } - } - - @Override - public ProcessInstanceStore load(String processInstanceId) throws EAAFException { - log.debug("Retrieve the ProcessInstanceStore for id='{}' from the database.", processInstanceId); - ProcessInstanceStore result = null; - try { - result = transactionStorage.get(processInstanceId, ProcessInstanceStore.class); - - } catch (Exception e) { - log.error("There are multiple persisted processes with the same process instance id '{}'", - processInstanceId); - - throw e; - } - - if (result != null) { - log.debug("Found process instance store for instance '{}'.", processInstanceId); - - } else { - log.debug("Unable to find process instance store for instance '{}'.", processInstanceId); - - } - - return result; - } - - @Override - public void remove(String processInstanceId) throws EAAFException { - - log.debug("Delete the ProcessInstanceStore for id='{}' from the database.", processInstanceId); - - if (transactionStorage.containsKey(processInstanceId)) - transactionStorage.remove(processInstanceId); - else - log.trace("ProcessInstanceStore for id='{}' was not found and could therefore not be deleted.", processInstanceId); - } - -} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/dao/ProcessInstanceStoreDaoImpl.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/dao/ProcessInstanceStoreDaoImpl.java new file mode 100644 index 00000000..06c8cc1a --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/dao/ProcessInstanceStoreDaoImpl.java @@ -0,0 +1,94 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.impl.idp.process.dao; + +import at.gv.egiz.eaaf.core.api.idp.process.ProcessInstanceStoreDao; +import at.gv.egiz.eaaf.core.api.storage.ITransactionStorage; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** + * Database backed implementation of the {@link ProcessInstanceStoreDao} interface. + */ +@Service("ProcessInstanceStoreage") +public class ProcessInstanceStoreDaoImpl implements ProcessInstanceStoreDao { + + private final Logger log = LoggerFactory.getLogger(getClass()); + + @Autowired + ITransactionStorage transactionStorage; + + @Override + public void saveOrUpdate(final ProcessInstanceStore piStore) throws EaafException { + try { + transactionStorage.put(piStore.getProcessInstanceId(), piStore, -1); + log.debug("Store process instance with='{}' in the database.", + piStore.getProcessInstanceId()); + + } catch (final EaafException e) { + log.warn("ProcessInstanceStore could not be persisted to the database."); + throw e; + } + } + + @Override + public ProcessInstanceStore load(final String processInstanceId) throws EaafException { + log.debug("Retrieve the ProcessInstanceStore for id='{}' from the database.", + processInstanceId); + ProcessInstanceStore result = null; + try { + result = transactionStorage.get(processInstanceId, ProcessInstanceStore.class); + + } catch (final Exception e) { + log.error("There are multiple persisted processes with the same process instance id '{}'", + processInstanceId); + + throw e; + } + + if (result != null) { + log.debug("Found process instance store for instance '{}'.", processInstanceId); + + } else { + log.debug("Unable to find process instance store for instance '{}'.", processInstanceId); + + } + + return result; + } + + @Override + public void remove(final String processInstanceId) throws EaafException { + + log.debug("Delete the ProcessInstanceStore for id='{}' from the database.", processInstanceId); + + if (transactionStorage.containsKey(processInstanceId)) { + transactionStorage.remove(processInstanceId); + } else { + log.trace( + "ProcessInstanceStore for id='{}' was not found and could therefore not be deleted.", + processInstanceId); + } + } + +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/model/EndEvent.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/model/EndEvent.java index 8657d0dc..48919ded 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/model/EndEvent.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/model/EndEvent.java @@ -1,68 +1,60 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process.model; import java.io.Serializable; - import org.apache.commons.collections4.CollectionUtils; /** * Represents an end event. Process execution terminates when an end event is reached. - * + * * @author tknall */ public class EndEvent extends ProcessNode implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("EndEvent ["); - if (getId() != null) { - builder.append("id="); - builder.append(getId()); - } - if (CollectionUtils.isNotEmpty(getIncomingTransitions())) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("incomingTransitions="); - builder.append(getIncomingTransitions()); - } - if (CollectionUtils.isNotEmpty(getOutgoingTransitions())) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("outgoingTransitions="); - builder.append(getOutgoingTransitions()); - } - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("EndEvent ["); + if (getId() != null) { + builder.append("id="); + builder.append(getId()); + } + if (CollectionUtils.isNotEmpty(getIncomingTransitions())) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("incomingTransitions="); + builder.append(getIncomingTransitions()); + } + if (CollectionUtils.isNotEmpty(getOutgoingTransitions())) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("outgoingTransitions="); + builder.append(getOutgoingTransitions()); + } + builder.append("]"); + return builder.toString(); + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/model/ProcessDefinition.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/model/ProcessDefinition.java index b7caef7a..3ab68266 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/model/ProcessDefinition.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/model/ProcessDefinition.java @@ -1,184 +1,177 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process.model; +import java.io.Serializable; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; - import at.gv.egiz.eaaf.core.impl.idp.process.ProcessDefinitionParser; /** - * Represents a single process definition containing + * Represents a single process definition containing. *
    *
  • a {@link StartEvent},
  • *
  • one or more {@linkplain TaskInfo Tasks},
  • *
  • one or more {@linkplain EndEvent EndEvents} and
  • *
  • some {@linkplain Transition Transitions} linking StartEvents, Tasks and EndEvents. *
- * + * * @author tknall - * + * */ -public class ProcessDefinition { - - private String id; - private StartEvent startEvent; - private Map taskInfos = new LinkedHashMap<>(); - private Map endEvents = new LinkedHashMap<>(); - - /** - * Returns the unique identifier of the process definition. - * - * @return The unique identifier (never {@code null} if process definition comes from - * {@link ProcessDefinitionParser}). - */ - public String getId() { - return id; - } - - /** - * Sets the unique identifier of the process definition. - * - * @param id - * The unique identifier. - */ - public void setId(String id) { - this.id = id; - } - - /** - * Returns the start event of the process definition. - * - * @return The start event (never {@code null} if process definition comes from {@link ProcessDefinitionParser}). - */ - public StartEvent getStartEvent() { - return startEvent; - } - - /** - * Sets the start event of the process definition. - * - * @param startEvent - * The start event. - */ - public void setStartEvent(StartEvent startEvent) { - this.startEvent = startEvent; - } - - /** - * Returns a map containing the tasks of the process definition. - * - * @return The tasks (map is never {@code null} if process definition comes from {@link ProcessDefinitionParser}). - */ - public Map getTaskInfos() { - return taskInfos; - } - - /** - * Sets the map containing the tasks. - * - * @param taskInfos - * The map containing the tasks. - */ - public void setTaskInfos(Map taskInfos) { - this.taskInfos = taskInfos; - } - - /** - * Returns a map containing the end events of the process description. - * - * @return The map containing the end events (map is never {@code null} if process definition comes from - * {@link ProcessDefinitionParser}). - */ - public Map getEndEvents() { - return endEvents; - } - - /** - * Sets a map containing the end events of the process description. - * - * @param endEvents - * The map containing the end events. - */ - public void setEndEvents(Map endEvents) { - this.endEvents = endEvents; - } - - /** - * Returns the process node associated with the given {@code id}. - * - * @param id - * The identifier of the process node. - * @return The process node (may be {code null} when no process node with the given {@code id} exists). - */ - public ProcessNode getProcessNode(String id) { - Objects.requireNonNull(id, "Identifier must not be null."); - if (startEvent != null && id.equals(startEvent.getId())) { - return startEvent; - } - TaskInfo task = taskInfos.get(id); - if (task != null) { - return task; - } - return endEvents.get(id); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - if (id != null) { - builder.append("id="); - builder.append(id); - } - if (startEvent != null) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("startEvent="); - builder.append(startEvent); - } - if (taskInfos != null && !taskInfos.isEmpty()) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("tasksInfos="); - builder.append(taskInfos.values()); - } - if (endEvents != null && !endEvents.isEmpty()) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("endEvents="); - builder.append(endEvents.values()); - } - builder.insert(0, "ProcessDefinition ["); - builder.append("]"); - return builder.toString(); - } +public class ProcessDefinition implements Serializable { + + private static final long serialVersionUID = 7896697967510445442L; + + private String id; + private StartEvent startEvent; + private Map taskInfos = new LinkedHashMap<>(); + private Map endEvents = new LinkedHashMap<>(); + + /** + * Returns the unique identifier of the process definition. + * + * @return The unique identifier (never {@code null} if process definition comes from + * {@link ProcessDefinitionParser}). + */ + public String getId() { + return id; + } + + /** + * Sets the unique identifier of the process definition. + * + * @param id The unique identifier. + */ + public void setId(final String id) { + this.id = id; + } + + /** + * Returns the start event of the process definition. + * + * @return The start event (never {@code null} if process definition comes from + * {@link ProcessDefinitionParser}). + */ + public StartEvent getStartEvent() { + return startEvent; + } + + /** + * Sets the start event of the process definition. + * + * @param startEvent The start event. + */ + public void setStartEvent(final StartEvent startEvent) { + this.startEvent = startEvent; + } + + /** + * Returns a map containing the tasks of the process definition. + * + * @return The tasks (map is never {@code null} if process definition comes from + * {@link ProcessDefinitionParser}). + */ + public Map getTaskInfos() { + return taskInfos; + } + + /** + * Sets the map containing the tasks. + * + * @param taskInfos The map containing the tasks. + */ + public void setTaskInfos(final Map taskInfos) { + this.taskInfos = taskInfos; + } + + /** + * Returns a map containing the end events of the process description. + * + * @return The map containing the end events (map is never {@code null} if process definition + * comes from {@link ProcessDefinitionParser}). + */ + public Map getEndEvents() { + return endEvents; + } + + /** + * Sets a map containing the end events of the process description. + * + * @param endEvents The map containing the end events. + */ + public void setEndEvents(final Map endEvents) { + this.endEvents = endEvents; + } + + /** + * Returns the process node associated with the given {@code id}. + * + * @param id The identifier of the process node. + * @return The process node (may be {code null} when no process node with the given {@code id} + * exists). + */ + public ProcessNode getProcessNode(final String id) { + Objects.requireNonNull(id, "Identifier must not be null."); + if (startEvent != null && id.equals(startEvent.getId())) { + return startEvent; + } + final TaskInfo task = taskInfos.get(id); + if (task != null) { + return task; + } + return endEvents.get(id); + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + if (id != null) { + builder.append("id="); + builder.append(id); + } + if (startEvent != null) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("startEvent="); + builder.append(startEvent); + } + if (taskInfos != null && !taskInfos.isEmpty()) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("tasksInfos="); + builder.append(taskInfos.values()); + } + if (endEvents != null && !endEvents.isEmpty()) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("endEvents="); + builder.append(endEvents.values()); + } + builder.insert(0, "ProcessDefinition ["); + builder.append("]"); + return builder.toString(); + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/model/ProcessNode.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/model/ProcessNode.java index 7964fa47..92858edf 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/model/ProcessNode.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/model/ProcessNode.java @@ -1,95 +1,95 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process.model; import java.util.ArrayList; import java.util.List; - import at.gv.egiz.eaaf.core.impl.idp.process.ProcessDefinitionParser; /** * Represents a {@link StartEvent}, an {@link EndEvent} or a {@linkplain TaskInfo Task}. + * * @author tknall * */ public abstract class ProcessNode { - private String id; - private List outgoingTransitions = new ArrayList<>(); - private List incomingTransitions = new ArrayList<>(); + private String id; + private List outgoingTransitions = new ArrayList<>(); + private List incomingTransitions = new ArrayList<>(); + + /** + * Returns the unique identifier of the process node. + * + * @return The unique identifier (never {@code null} if process node comes from a process + * definition from {@link ProcessDefinitionParser}). + */ + public String getId() { + return id; + } - /** - * Returns the unique identifier of the process node. - * - * @return The unique identifier (never {@code null} if process node comes from a process definition from - * {@link ProcessDefinitionParser}). - */ - public String getId() { - return id; - } + /** + * Sets the unique identifier of the process node. + * + * @param id The unique identifier. + */ + public void setId(final String id) { + this.id = id; + } - /** - * Sets the unique identifier of the process node. - * @param id The unique identifier. - */ - public void setId(String id) { - this.id = id; - } + /** + * Returns a list of transitions pointing from this process node to another one. + * + * @return A list of transitions (never {@code null} if process node comes from a process + * definition from {@link ProcessDefinitionParser}). + */ + public List getOutgoingTransitions() { + return outgoingTransitions; + } - /** - * Returns a list of transitions pointing from this process node to another one. - * @return A list of transitions (never {@code null} if process node comes from a process definition from {@link ProcessDefinitionParser}). - */ - public List getOutgoingTransitions() { - return outgoingTransitions; - } + /** + * Sets the list of transitions pointing from this process node to another one. + * + * @param outgoingTransitions The list of transitions originating from this process node. + */ + public void setOutgoingTransitions(final List outgoingTransitions) { + this.outgoingTransitions = outgoingTransitions; + } - /** - * Sets the list of transitions pointing from this process node to another one. - * @param outgoingTransitions The list of transitions originating from this process node. - */ - public void setOutgoingTransitions(List outgoingTransitions) { - this.outgoingTransitions = outgoingTransitions; - } + /** + * Returns a list of transitions pointing from another process node to this one. + * + * @return A list of transitions (never {@code null} if process node comes from a process + * definition from {@link ProcessDefinitionParser}). + */ + public List getIncomingTransitions() { + return incomingTransitions; + } - /** - * Returns a list of transitions pointing from another process node to this one. - * @return A list of transitions (never {@code null} if process node comes from a process definition from {@link ProcessDefinitionParser}). - */ - public List getIncomingTransitions() { - return incomingTransitions; - } + /** + * Sets the list of transitions pointing from another process node to this one. + * + * @param incomingTransitions A list of transitions pointing to this process node. + */ + public void setIncomingTransitions(final List incomingTransitions) { + this.incomingTransitions = incomingTransitions; + } - /** - * Sets the list of transitions pointing from another process node to this one. - * @param incomingTransitions A list of transitions pointing to this process node. - */ - public void setIncomingTransitions(List incomingTransitions) { - this.incomingTransitions = incomingTransitions; - } - } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/model/StartEvent.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/model/StartEvent.java index 8e358b69..698312c7 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/model/StartEvent.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/model/StartEvent.java @@ -1,71 +1,63 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process.model; import java.io.Serializable; - import org.apache.commons.collections4.CollectionUtils; /** - * Represents a start event. Each process description contains a single start event. Process execution starts with a - * start event. - * + * Represents a start event. Each process description contains a single start event. Process + * execution starts with a start event. + * * @author tknall - * + * */ public class StartEvent extends ProcessNode implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("StartEvent ["); - if (getId() != null) { - builder.append("id="); - builder.append(getId()); - } - if (CollectionUtils.isNotEmpty(getIncomingTransitions())) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("incomingTransitions="); - builder.append(getIncomingTransitions()); - } - if (CollectionUtils.isNotEmpty(getOutgoingTransitions())) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("outgoingTransitions="); + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("StartEvent ["); + if (getId() != null) { + builder.append("id="); + builder.append(getId()); + } + if (CollectionUtils.isNotEmpty(getIncomingTransitions())) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("incomingTransitions="); + builder.append(getIncomingTransitions()); + } + if (CollectionUtils.isNotEmpty(getOutgoingTransitions())) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("outgoingTransitions="); - builder.append(getOutgoingTransitions()); - } - builder.append("]"); - return builder.toString(); - } + builder.append(getOutgoingTransitions()); + } + builder.append("]"); + return builder.toString(); + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/model/TaskInfo.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/model/TaskInfo.java index b98045c5..9e384b4c 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/model/TaskInfo.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/model/TaskInfo.java @@ -1,120 +1,117 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. + */ + package at.gv.egiz.eaaf.core.impl.idp.process.model; import java.io.Serializable; - -import org.apache.commons.collections4.CollectionUtils; - import at.gv.egiz.eaaf.core.api.idp.process.Task; +import org.apache.commons.collections4.CollectionUtils; /** * Represents information about a single task to be performed upon process execution. + * * @author tknall * */ public class TaskInfo extends ProcessNode implements Serializable { - private static final long serialVersionUID = 1L; - private static final boolean DEFAULT_ASYNC = false; - - private String taskImplementingClass; - private boolean async = DEFAULT_ASYNC; - - /** - * Determines if the task is marked asynchronous ({@code true}) or synchronous ({@code false}). - * @return A flag indicating if the task should be executed asynchronously or synchronously. (Default: {@code false}) - */ - public boolean isAsync() { - return async; - } + private static final long serialVersionUID = 1L; + private static final boolean DEFAULT_ASYNC = false; + + private String taskImplementingClass; + private boolean async = DEFAULT_ASYNC; + + /** + * Determines if the task is marked asynchronous ({@code true}) or synchronous ({@code false}). + * + * @return A flag indicating if the task should be executed asynchronously or synchronously. + * (Default: {@code false}) + */ + public boolean isAsync() { + return async; + } - /** - * Marks a task to executed asynchronously ({@code true}) or synchronously ({@code false}). - * @param async The flag. - */ - public void setAsync(boolean async) { - this.async = async; - } + /** + * Marks a task to executed asynchronously ({@code true}) or synchronously ({@code false}). + * + * @param async The flag. + */ + public void setAsync(final boolean async) { + this.async = async; + } - /** - * Returns the class that implements the actual task (must implement {@link Task}). - * @return The task implementing class. - */ - public String getTaskImplementingClass() { - return taskImplementingClass; - } + /** + * Returns the class that implements the actual task (must implement {@link Task}). + * + * @return The task implementing class. + */ + public String getTaskImplementingClass() { + return taskImplementingClass; + } - /** - * Sets the class that implements the actual task (must implement {@link Task}). - * @param taskImplementingClass The task implementing class. - */ - public void setTaskImplementingClass(String taskImplementingClass) { - this.taskImplementingClass = taskImplementingClass; - } + /** + * Sets the class that implements the actual task (must implement {@link Task}). + * + * @param taskImplementingClass The task implementing class. + */ + public void setTaskImplementingClass(final String taskImplementingClass) { + this.taskImplementingClass = taskImplementingClass; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - if (getId() != null) { - builder.append("id="); - builder.append(getId()); - } - if (async != DEFAULT_ASYNC) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("async="); - builder.append(async); - } - if (taskImplementingClass != null) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("taskImplementingClass="); - builder.append(taskImplementingClass); - } - if (CollectionUtils.isNotEmpty(getIncomingTransitions())) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("incomingTransitions="); - builder.append(getIncomingTransitions()); - } - if (CollectionUtils.isNotEmpty(getOutgoingTransitions())) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("outgoingTransitions="); - builder.append(getOutgoingTransitions()); - } - builder.insert(0, "TaskInfo ["); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + if (getId() != null) { + builder.append("id="); + builder.append(getId()); + } + if (async != DEFAULT_ASYNC) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("async="); + builder.append(async); + } + if (taskImplementingClass != null) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("taskImplementingClass="); + builder.append(taskImplementingClass); + } + if (CollectionUtils.isNotEmpty(getIncomingTransitions())) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("incomingTransitions="); + builder.append(getIncomingTransitions()); + } + if (CollectionUtils.isNotEmpty(getOutgoingTransitions())) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("outgoingTransitions="); + builder.append(getOutgoingTransitions()); + } + builder.insert(0, "TaskInfo ["); + builder.append("]"); + return builder.toString(); + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/model/Transition.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/model/Transition.java index 542ea7a8..4c7b70f0 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/model/Transition.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/model/Transition.java @@ -1,162 +1,150 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process.model; import java.io.Serializable; - import at.gv.egiz.eaaf.core.impl.idp.process.ProcessDefinitionParser; /** * Represents a single transition from a {@link StartEvent} or {@linkplain TaskInfo Task} to another * {@linkplain TaskInfo Task} or {@link EndEvent}. - * + * * @author tknall - * + * */ public class Transition implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private String id; - private String conditionExpression; - private ProcessNode from; - private ProcessNode to; + private String id; + private String conditionExpression; + private ProcessNode from; + private ProcessNode to; - /** - * Returns the process node (effectively a {@link StartEvent} or {@linkplain TaskInfo Task}) the transition is - * pointing from. - * - * @return The transition's source process node (never {@code null} if transition comes from a process definition - * from {@link ProcessDefinitionParser}). - */ - public ProcessNode getFrom() { - return from; - } + /** + * Returns the process node (effectively a {@link StartEvent} or {@linkplain TaskInfo Task}) the + * transition is pointing from. + * + * @return The transition's source process node (never {@code null} if transition comes from a + * process definition from {@link ProcessDefinitionParser}). + */ + public ProcessNode getFrom() { + return from; + } - /** - * Sets the process node the transition is pointing from. - * - * @param from - * The transition's source process node. - */ - public void setFrom(ProcessNode from) { - this.from = from; - } + /** + * Sets the process node the transition is pointing from. + * + * @param from The transition's source process node. + */ + public void setFrom(final ProcessNode from) { + this.from = from; + } - /** - * Returns the process node (effectively a {@linkplain TaskInfo Task} or {@link EndEvent}) the transition is - * pointing to. - * - * @return The transition's destination process node (never {@code null} if transition comes from a process - * definition from {@link ProcessDefinitionParser}). - */ - public ProcessNode getTo() { - return to; - } + /** + * Returns the process node (effectively a {@linkplain TaskInfo Task} or {@link EndEvent}) the + * transition is pointing to. + * + * @return The transition's destination process node (never {@code null} if transition comes from + * a process definition from {@link ProcessDefinitionParser}). + */ + public ProcessNode getTo() { + return to; + } - /** - * Sets the process node the transition is pointing to. - * - * @param to - * The transition's destination process node. - */ - public void setTo(ProcessNode to) { - this.to = to; - } + /** + * Sets the process node the transition is pointing to. + * + * @param to The transition's destination process node. + */ + public void setTo(final ProcessNode to) { + this.to = to; + } - /** - * Returns the unique identifier of the transition. - * - * @return The unique identifier (may be {@code null}). - */ - public String getId() { - return id; - } + /** + * Returns the unique identifier of the transition. + * + * @return The unique identifier (may be {@code null}). + */ + public String getId() { + return id; + } - /** - * Sets the unique identifier of the transition. - * - * @param id - * The unique identifier. - */ - public void setId(String id) { - this.id = id; - } + /** + * Sets the unique identifier of the transition. + * + * @param id The unique identifier. + */ + public void setId(final String id) { + this.id = id; + } - /** - * Returns the condition expression for this transition. - * - * @return The condition expression (may be {@code null}). - */ - public String getConditionExpression() { - return conditionExpression; - } + /** + * Returns the condition expression for this transition. + * + * @return The condition expression (may be {@code null}). + */ + public String getConditionExpression() { + return conditionExpression; + } - /** - * Sets the condition expression for this transition. - * - * @param conditionExpression - * The condition expression. - */ - public void setConditionExpression(String conditionExpression) { - this.conditionExpression = conditionExpression; - } + /** + * Sets the condition expression for this transition. + * + * @param conditionExpression The condition expression. + */ + public void setConditionExpression(final String conditionExpression) { + this.conditionExpression = conditionExpression; + } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - if (id != null) { - builder.append("id="); - builder.append(id); - } - if (from != null) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("from.id="); - builder.append(from.getId()); - } - if (to != null) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("to.id="); - builder.append(to.getId()); - } - if (conditionExpression != null) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("conditionExpression="); - builder.append(conditionExpression); - } - builder.insert(0, "Transition ["); - builder.append("]"); - return builder.toString(); - } + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + if (id != null) { + builder.append("id="); + builder.append(id); + } + if (from != null) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("from.id="); + builder.append(from.getId()); + } + if (to != null) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("to.id="); + builder.append(to.getId()); + } + if (conditionExpression != null) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("conditionExpression="); + builder.append(conditionExpression); + } + builder.insert(0, "Transition ["); + builder.append("]"); + return builder.toString(); + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/SpringExpressionEvaluator.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/SpringExpressionEvaluator.java index a91963e8..fc01463e 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/SpringExpressionEvaluator.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/SpringExpressionEvaluator.java @@ -1,35 +1,29 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process.spring; import java.util.Objects; - import javax.annotation.PostConstruct; - +import at.gv.egiz.eaaf.core.api.idp.process.ExpressionEvaluationContext; +import at.gv.egiz.eaaf.core.api.idp.process.ExpressionEvaluator; +import at.gv.egiz.eaaf.core.impl.idp.process.model.Transition; import org.apache.commons.lang3.BooleanUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,47 +35,44 @@ import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; -import at.gv.egiz.eaaf.core.api.idp.process.ExpressionEvaluationContext; -import at.gv.egiz.eaaf.core.api.idp.process.ExpressionEvaluator; -import at.gv.egiz.eaaf.core.impl.idp.process.model.Transition; - /** - * Expression evaluator for processing {@link Transition} conditions allowing to reference Spring beans from the - * application context. - * + * Expression evaluator for processing {@link Transition} conditions allowing to reference Spring + * beans from the application context. + * * @author tknall - * + * */ public class SpringExpressionEvaluator implements ExpressionEvaluator { - private Logger log = LoggerFactory.getLogger(getClass()); - private ExpressionParser parser = new SpelExpressionParser(); - private StandardEvaluationContext evaluationContext = new StandardEvaluationContext(); + private final Logger log = LoggerFactory.getLogger(getClass()); + private final ExpressionParser parser = new SpelExpressionParser(); + private final StandardEvaluationContext evaluationContext = new StandardEvaluationContext(); - @Autowired(required = false) - private ApplicationContext ctx; + @Autowired(required = false) + private ApplicationContext ctx; - @PostConstruct - private void init() { - if (ctx != null) { - evaluationContext.setBeanResolver(new BeanFactoryResolver(ctx)); - } - } + @PostConstruct + private void init() { + if (ctx != null) { + evaluationContext.setBeanResolver(new BeanFactoryResolver(ctx)); + } + } - @Override - public boolean evaluate(ExpressionEvaluationContext expressionContext, String expression) { - Objects.requireNonNull(expression, "Expression must not be null."); - log.trace("Evaluating '{}'.", expression); + @Override + public boolean evaluate(final ExpressionEvaluationContext expressionContext, + final String expression) { + Objects.requireNonNull(expression, "Expression must not be null."); + log.trace("Evaluating '{}'.", expression); - Expression expr = parser.parseExpression(expression); - Boolean result = expr.getValue(evaluationContext, expressionContext, Boolean.class); - if (result == null) { - log.warn("Evaluation of '{}' results in null-value.", expression); - } else { - log.debug("Expression '{}' -> {}", expression, result); - } + final Expression expr = parser.parseExpression(expression); + final Boolean result = expr.getValue(evaluationContext, expressionContext, Boolean.class); + if (result == null) { + log.warn("Evaluation of '{}' results in null-value.", expression); + } else { + log.debug("Expression '{}' -> {}", expression, result); + } - return BooleanUtils.isTrue(result); - } + return BooleanUtils.isTrue(result); + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/springweb/AbstractAuthSourceServlet.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/springweb/AbstractAuthSourceServlet.java index 4b007c4c..cc899641 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/springweb/AbstractAuthSourceServlet.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/springweb/AbstractAuthSourceServlet.java @@ -1,34 +1,29 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process.springweb; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; - +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.api.idp.process.ProcessEngine; +import at.gv.egiz.eaaf.core.impl.idp.process.ProcessInstance; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -36,107 +31,95 @@ import org.springframework.beans.factory.NoUniqueBeanDefinitionException; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; -import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; -import at.gv.egiz.eaaf.core.api.idp.process.ProcessEngine; -import at.gv.egiz.eaaf.core.impl.idp.process.ProcessInstance; - /** - * Abstract HttpServlet that provides means for retrieving the process engine (Spring Web required) as well as - * retrieving the underlying process instance and execution context evaluating a certain request parameter. - * + * Abstract HttpServlet that provides means for retrieving the process engine (Spring Web required) + * as well as retrieving the underlying process instance and execution context evaluating a certain + * request parameter. + * * @author tknall - * + * */ public abstract class AbstractAuthSourceServlet extends HttpServlet { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; + + private ProcessEngine processEngine; - private ProcessEngine processEngine; - - /** - * Returns the name of the request parameter representing the respective instance id. - *

Default is {@code processInstanceId}. - * @return The request parameter name. - */ - public String getProcessInstanceIdParameterName() { - return "processInstanceId"; - } + /** + * Returns the name of the request parameter representing the respective instance id. + *

+ * Default is {@code processInstanceId}. + * + * @return The request parameter name. + */ + public String getProcessInstanceIdParameterName() { + return "processInstanceId"; + } - /** - * Returns the underlying process engine instance. - * - * @return The process engine (never {@code null}). - * @throws NoSuchBeanDefinitionException - * if no {@link ProcessEngine} bean was found. - * @throws NoUniqueBeanDefinitionException - * if more than one {@link ProcessEngine} bean was found. - * @throws BeansException - * if a problem getting the {@link ProcessEngine} bean occurred. - * @throws IllegalStateException - * if the Spring WebApplicationContext was not found, which means that the servlet is used outside a - * Spring web environment. - */ - public synchronized ProcessEngine getProcessEngine() { - if (processEngine == null) { - WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); - if (ctx == null) { - throw new IllegalStateException( - "Unable to find Spring WebApplicationContext. Servlet needs to be executed within a Spring web environment."); - } - processEngine = ctx.getBean(ProcessEngine.class); - } - return processEngine; - } + /** + * Returns the underlying process engine instance. + * + * @return The process engine (never {@code null}). + * @throws NoSuchBeanDefinitionException if no {@link ProcessEngine} bean was found. + * @throws NoUniqueBeanDefinitionException if more than one {@link ProcessEngine} bean was found. + * @throws BeansException if a problem getting the {@link ProcessEngine} bean occurred. + * @throws IllegalStateException if the Spring WebApplicationContext was not found, which means + * that the servlet is used outside a Spring web environment. + */ + public synchronized ProcessEngine getProcessEngine() { + if (processEngine == null) { + final WebApplicationContext ctx = + WebApplicationContextUtils.getWebApplicationContext(getServletContext()); + if (ctx == null) { + throw new IllegalStateException( + "Unable to find Spring WebApplicationContext. " + + "Servlet needs to be executed within a Spring web environment."); + } + processEngine = ctx.getBean(ProcessEngine.class); + } + return processEngine; + } - /** - * Retrieves the process instance referenced by the request parameter {@link #getProcessInstanceIdParameterName()}. - * - * @param request - * The HttpServletRequest. - * @return The process instance (never {@code null}). - * @throws NoSuchBeanDefinitionException - * if no {@link ProcessEngine} bean was found. - * @throws NoUniqueBeanDefinitionException - * if more than one {@link ProcessEngine} bean was found. - * @throws BeansException - * if a problem getting the {@link ProcessEngine} bean occurred. - * @throws IllegalStateException - * if the Spring WebApplicationContext was not found, which means that the servlet is used outside a - * Spring web environment. - * @throws IllegalArgumentException - * in case the process instance id referenced by the request parameter - * {@link #getProcessInstanceIdParameterName()} does not exist. - */ - public ProcessInstance getProcessInstance(HttpServletRequest request) { - String processInstanceId = StringUtils.trimToNull(request.getParameter(getProcessInstanceIdParameterName())); - if (processInstanceId == null) { - throw new IllegalArgumentException("Missing request parameter '" + getProcessInstanceIdParameterName() + "'."); - } - return getProcessEngine().getProcessInstance(processInstanceId); - } + /** + * Retrieves the process instance referenced by the request parameter + * {@link #getProcessInstanceIdParameterName()}. + * + * @param request The HttpServletRequest. + * @return The process instance (never {@code null}). + * @throws NoSuchBeanDefinitionException if no {@link ProcessEngine} bean was found. + * @throws NoUniqueBeanDefinitionException if more than one {@link ProcessEngine} bean was found. + * @throws BeansException if a problem getting the {@link ProcessEngine} bean occurred. + * @throws IllegalStateException if the Spring WebApplicationContext was not found, which means + * that the servlet is used outside a Spring web environment. + * @throws IllegalArgumentException in case the process instance id referenced by the request + * parameter {@link #getProcessInstanceIdParameterName()} does not exist. + */ + public ProcessInstance getProcessInstance(final HttpServletRequest request) { + final String processInstanceId = + StringUtils.trimToNull(request.getParameter(getProcessInstanceIdParameterName())); + if (processInstanceId == null) { + throw new IllegalArgumentException( + "Missing request parameter '" + getProcessInstanceIdParameterName() + "'."); + } + return getProcessEngine().getProcessInstance(processInstanceId); + } - /** - * Retrieves the execution context for the respective process instance referenced by the request parameter - * {@link #getProcessInstanceIdParameterName()}. - * - * @param request - * The HttpServletRequest. - * @return The execution context (never {@code null}). - * @throws NoSuchBeanDefinitionException - * if no {@link ProcessEngine} bean was found. - * @throws NoUniqueBeanDefinitionException - * if more than one {@link ProcessEngine} bean was found. - * @throws BeansException - * if a problem getting the {@link ProcessEngine} bean occurred. - * @throws IllegalStateException - * if the Spring WebApplicationContext was not found, which means that the servlet is used outside a - * Spring web environment. - * @throws IllegalArgumentException - * in case the process instance id referenced by the request parameter - * {@link #getProcessInstanceIdParameterName()} does not exist. - */ - public ExecutionContext getExecutionContext(HttpServletRequest request) { - return getProcessInstance(request).getExecutionContext(); - } + /** + * Retrieves the execution context for the respective process instance referenced by the request + * parameter {@link #getProcessInstanceIdParameterName()}. + * + * @param request The HttpServletRequest. + * @return The execution context (never {@code null}). + * @throws NoSuchBeanDefinitionException if no {@link ProcessEngine} bean was found. + * @throws NoUniqueBeanDefinitionException if more than one {@link ProcessEngine} bean was found. + * @throws BeansException if a problem getting the {@link ProcessEngine} bean occurred. + * @throws IllegalStateException if the Spring WebApplicationContext was not found, which means + * that the servlet is used outside a Spring web environment. + * @throws IllegalArgumentException in case the process instance id referenced by the request + * parameter {@link #getProcessInstanceIdParameterName()} does not exist. + */ + public ExecutionContext getExecutionContext(final HttpServletRequest request) { + return getProcessInstance(request).getExecutionContext(); + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/springweb/AbstractTask.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/springweb/AbstractTask.java index b7a20d71..02db6686 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/springweb/AbstractTask.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/springweb/AbstractTask.java @@ -1,50 +1,42 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process.springweb; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - -import org.springframework.web.context.request.RequestAttributes; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; -import org.springframework.web.filter.RequestContextFilter; - import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; import at.gv.egiz.eaaf.core.api.idp.process.Task; import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.filter.RequestContextFilter; /** - * Abstract task implementation providing {@link HttpServletRequest} and {@link HttpServletResponse}. + * Abstract task implementation providing {@link HttpServletRequest} and + * {@link HttpServletResponse}. *

- * Note that this abstract task requires the Spring (web) framework including a {@link RequestContextFilter} to be set - * within {@code web.xml}. - * + * Note that this abstract task requires the Spring (web) framework including a + * {@link RequestContextFilter} to be set within {@code web.xml}. + * *

  * ...
  * <filter>
@@ -57,69 +49,72 @@ import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException;
  * </filter-mapping>
  * ...
  * 
- * + * * @author tknall * @author tlenz - * + * */ public abstract class AbstractTask implements Task { - /** - * Executes the task providing the underlying {@link ExecutionContext} {@code executionContext} as well as the - * respective {@link HttpServletRequest} and {@link HttpServletResponse}. - * - * @param executionContext - * The execution context (never {@code null}). - * @param request - * The HttpServletRequest (never {@code null}). - * @param response - * The HttpServletResponse (never {@code null}). - * @throws IllegalStateException - * Thrown in case the task is nur being run within the required environment. Refer to javadoc for - * further information. - * @throws Exception - * Thrown in case of error executing the task. - */ - public abstract void execute(ExecutionContext executionContext, HttpServletRequest request, - HttpServletResponse response) throws TaskExecutionException; + @Override + public IRequest execute(final IRequest pendingReq, final ExecutionContext executionContext) + throws TaskExecutionException { + final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); + if (requestAttributes != null && requestAttributes instanceof ServletRequestAttributes) { + final HttpServletRequest request = + ((ServletRequestAttributes) requestAttributes).getRequest(); + final HttpServletResponse response = + ((ServletRequestAttributes) requestAttributes).getResponse(); + if (request == null || response == null) { + throw new IllegalStateException( + "Spring's RequestContextHolder did not provide HttpServletResponse. " + + "Did you forget to set the required " + + "org.springframework.web.filter.RequestContextFilter in your web.xml."); + } + return internalExecute(pendingReq, executionContext, request, response); + } else { + throw new IllegalStateException("Task needs to be executed within a Spring web environment."); + } + } + + /** + * Executes the task providing the underlying {@link ExecutionContext} {@code executionContext} as + * well as the respective {@link HttpServletRequest} and {@link HttpServletResponse}. + * + * @param executionContext The execution context (never {@code null}). + * @param request The HttpServletRequest (never {@code null}). + * @param response The HttpServletResponse (never {@code null}). + * @throws IllegalStateException Thrown in case the task is nur being run within the required + * environment. Refer to javadoc for further information. + * @throws Exception Thrown in case of error executing the task. + */ + public abstract void execute(ExecutionContext executionContext, HttpServletRequest request, + HttpServletResponse response) throws TaskExecutionException; + + /** + * Executes the task providing the underlying {@link ExecutionContext} {@code executionContext} + * and the {@link IRequest} {@code pendingReq }as well as the respective + * {@link HttpServletRequest} and {@link HttpServletResponse}. + * + *

+ * This method sets the pending-request object of the task implementation and starts the + * {@code execute} method of the task + *

+ * + * @param pendingReq The pending-request object (never {@code null}). + * @param executionContext The execution context (never {@code null}). + * @param request The HttpServletRequest (never {@code null}). + * @param response The HttpServletResponse (never {@code null}). + * @return The pending-request object, because Process-management works recursive + * + * @throws IllegalStateException Thrown in case the task is being run within the required + * environment. Refer to javadoc for further information. + * @throws Exception Thrown in case of error executing the task. + */ + protected abstract IRequest internalExecute(IRequest pendingReq, + ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) + throws TaskExecutionException; + - /** - * Executes the task providing the underlying {@link ExecutionContext} {@code executionContext} - * and the {@link IRequest} {@code pendingReq }as well as the - * respective {@link HttpServletRequest} and {@link HttpServletResponse}. - * - * This method sets the pending-request object of the task implementation and starts the - * {@code execute} method of the task - * - * @param pendingReq The pending-request object (never {@code null}). - * @param executionContext The execution context (never {@code null}). - * @param request The HttpServletRequest (never {@code null}). - * @param response The HttpServletResponse (never {@code null}). - * @return The pending-request object, because Process-management works recursive - * - * @throws IllegalStateException - * Thrown in case the task is being run within the required environment. Refer to javadoc for - * further information. - * @throws Exception - * Thrown in case of error executing the task. - */ - protected abstract IRequest internalExecute(IRequest pendingReq, ExecutionContext executionContext, HttpServletRequest request, - HttpServletResponse response) throws TaskExecutionException; - - @Override - public IRequest execute(IRequest pendingReq, ExecutionContext executionContext) throws TaskExecutionException { - RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); - if (requestAttributes != null && requestAttributes instanceof ServletRequestAttributes) { - HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); - HttpServletResponse response = ((ServletRequestAttributes) requestAttributes).getResponse(); - if (request == null || response == null) { - throw new IllegalStateException( - "Spring's RequestContextHolder did not provide HttpServletResponse. Did you forget to set the required org.springframework.web.filter.RequestContextFilter in your web.xml."); - } - return internalExecute(pendingReq, executionContext, request, response); - } else { - throw new IllegalStateException("Task needs to be executed within a Spring web environment."); - } - } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/springweb/SpringWebExpressionEvaluator.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/springweb/SpringWebExpressionEvaluator.java index 5ebc1b58..c723a728 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/springweb/SpringWebExpressionEvaluator.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/springweb/SpringWebExpressionEvaluator.java @@ -1,43 +1,33 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process.springweb; import java.io.Serializable; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; import java.util.Map; -import java.util.Map.Entry; import java.util.Objects; - import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; - -import org.apache.commons.lang3.ArrayUtils; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.api.idp.process.ExpressionEvaluationContext; +import at.gv.egiz.eaaf.core.api.idp.process.ExpressionEvaluator; +import at.gv.egiz.eaaf.core.impl.idp.process.model.Transition; import org.apache.commons.lang3.BooleanUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -49,121 +39,89 @@ import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; -import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; -import at.gv.egiz.eaaf.core.api.idp.process.ExpressionEvaluationContext; -import at.gv.egiz.eaaf.core.api.idp.process.ExpressionEvaluator; -import at.gv.egiz.eaaf.core.impl.idp.process.model.Transition; - /** - * Expression evaluator for processing {@link Transition} conditions allowing to + * Expression evaluator for processing {@link Transition} conditions allowing to. *
    *
  • reference Spring beans from the application context using {@code @myBeanName...},
  • *
  • {@link ExecutionContext} properties using {@code ctx['property']},
  • - *
  • Multi valued {@link HttpServletRequest} parameters using {@code requestParameters['foo']} (keep in mind that this - * expression returns an array of String values) and
  • - *
  • Single valued {@link HttpServletRequest} parameters using {@code requestParameter['foo']}
  • + *
  • Multi valued {@link HttpServletRequest} parameters using {@code requestParameters['foo']} + * (keep in mind that this expression returns an array of String values) and
  • + *
  • Single valued {@link HttpServletRequest} parameters using + * {@code requestParameter['foo']}
  • *
- * + * * @author tknall - * + * */ public class SpringWebExpressionEvaluator implements ExpressionEvaluator { - private Logger log = LoggerFactory.getLogger(getClass()); - private ExpressionParser parser = new SpelExpressionParser(); - private StandardEvaluationContext evaluationContext = new StandardEvaluationContext(); - - @Autowired(required = false) - private ApplicationContext ctx; - - @Autowired(required = false) - private HttpServletRequest request; - - @PostConstruct - private void init() { - if (ctx != null) { - evaluationContext.setBeanResolver(new BeanFactoryResolver(ctx)); - } - } - - /** - * Evaluation context that provides access to {@link HttpServletRequest} parameters using - * {@code requestParameter['foo']} for single value parameters or {@code requestParameters['foo']} for multi value - * parameters. Basic calls to {@code ctx} will be delegated. - * - * @author tknall - * - */ - private class SpringWebExpressionEvaluationContext implements ExpressionEvaluationContext { - - private static final long serialVersionUID = 1L; - - /** - * Creates a new expression evaluation context, providing access to HttpServletRequest parameter(s). - * - * @param delegate - * The original {@link ExpressionEvaluationContext} to be delegated to for {@code ctx['foo']} - * expressions. - */ - public SpringWebExpressionEvaluationContext(ExpressionEvaluationContext delegate) { - this.delegate = delegate; - } - - private ExpressionEvaluationContext delegate; - - @Override - public Map getCtx() { - return delegate.getCtx(); - } - - @SuppressWarnings("unused") - public Map getRequestParameter() { - if (request != null) { - Map singleValueMap = new HashMap(); - Iterator> it = request.getParameterMap().entrySet().iterator(); - while (it.hasNext()) { - Entry entry = it.next(); - if (ArrayUtils.isNotEmpty(entry.getValue())) { - singleValueMap.put(entry.getKey(), entry.getValue()[0]); - } - } - return singleValueMap; - } else { - return Collections. emptyMap(); - } - } - - @SuppressWarnings("unused") - public Map getRequestParameters() { - if (request != null) { - return request.getParameterMap(); - } else { - return Collections. emptyMap(); - } - } - - } - - @Override - public boolean evaluate(ExpressionEvaluationContext expressionContext, String expression) { - Objects.requireNonNull(expression, "Expression must not be null."); - log.trace("Evaluating '{}'.", expression); - - Expression expr = parser.parseExpression(expression); - Boolean result = null; - try { - result = expr.getValue(evaluationContext, new SpringWebExpressionEvaluationContext(expressionContext), - Boolean.class); - if (result == null) { - log.debug("Evaluation of '{}' results in null-value.", expression); - } else { - log.debug("Expression '{}' -> {}", expression, result); - } - } catch (Exception e) { - log.warn("Expression '{}' could not be processed.", expression, e); - } - - return BooleanUtils.isTrue(result); - } + private final Logger log = LoggerFactory.getLogger(getClass()); + private final ExpressionParser parser = new SpelExpressionParser(); + private final StandardEvaluationContext evaluationContext = new StandardEvaluationContext(); + + @Autowired(required = false) + private ApplicationContext ctx; + + @PostConstruct + private void init() { + if (ctx != null) { + evaluationContext.setBeanResolver(new BeanFactoryResolver(ctx)); + } + } + + /** + * Evaluation context that provides access to {@link HttpServletRequest} parameters using + * {@code requestParameter['foo']} for single value parameters or {@code requestParameters['foo']} + * for multi value parameters. Basic calls to {@code ctx} will be delegated. + * + * @author tknall + * + */ + private static class SpringWebExpressionEvaluationContext implements ExpressionEvaluationContext { + + private static final long serialVersionUID = 1L; + + /** + * Creates a new expression evaluation context, providing access to HttpServletRequest + * parameter(s). + * + * @param delegate The original {@link ExpressionEvaluationContext} to be delegated to for + * {@code ctx['foo']} expressions. + */ + public SpringWebExpressionEvaluationContext(final ExpressionEvaluationContext delegate) { + this.delegate = delegate; + } + + private final ExpressionEvaluationContext delegate; + + @Override + public Map getCtx() { + return delegate.getCtx(); + } + + } + + @Override + public boolean evaluate(final ExpressionEvaluationContext expressionContext, + final String expression) { + Objects.requireNonNull(expression, "Expression must not be null."); + log.trace("Evaluating '{}'.", expression); + + final Expression expr = parser.parseExpression(expression); + Boolean result = null; + try { + result = expr.getValue(evaluationContext, + new SpringWebExpressionEvaluationContext(expressionContext), Boolean.class); + if (result == null) { + log.debug("Evaluation of '{}' results in null-value.", expression); + } else { + log.debug("Expression '{}' -> {}", expression, result); + } + } catch (final Exception e) { + log.warn("Expression '{}' could not be processed.", expression, e); + } + + return BooleanUtils.isTrue(result); + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/logging/DummyRevisionsLogger.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/logging/DummyRevisionsLogger.java index 77af20c8..0c5129bc 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/logging/DummyRevisionsLogger.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/logging/DummyRevisionsLogger.java @@ -1,76 +1,68 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.logging; + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +package at.gv.egiz.eaaf.core.impl.logging; import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; import at.gv.egiz.eaaf.core.api.logging.IRevisionLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class DummyRevisionsLogger implements IRevisionLogger { - private static final Logger log = LoggerFactory.getLogger(DummyStatisticLogger.class); - - - @Override - public void logEvent(ISPConfiguration oaConfig, int eventCode, String message) { - log.trace("Dummy-logEventOperation"); + private static final Logger log = LoggerFactory.getLogger(DummyStatisticLogger.class); + + + @Override + public void logEvent(final IspConfiguration oaConfig, final int eventCode, final String message) { + log.trace("Dummy-logEventOperation"); - } + } - @Override - public void logEvent(int eventCode, String message) { - log.trace("Dummy-logEventOperation"); + @Override + public void logEvent(final int eventCode, final String message) { + log.trace("Dummy-logEventOperation"); - } + } - @Override - public void logEvent(String sessionID, String transactionID, int eventCode, String message) { - log.trace("Dummy-logEventOperation"); + @Override + public void logEvent(final String sessionID, final String transactionID, final int eventCode, final String message) { + log.trace("Dummy-logEventOperation"); - } + } - @Override - public void logEvent(String sessionID, String transactionID, int eventCode) { - log.trace("Dummy-logEventOperation"); + @Override + public void logEvent(final String sessionID, final String transactionID, final int eventCode) { + log.trace("Dummy-logEventOperation"); - } + } - @Override - public void logEvent(IRequest pendingRequest, int eventCode) { - log.trace("Dummy-logEventOperation"); + @Override + public void logEvent(final IRequest pendingRequest, final int eventCode) { + log.trace("Dummy-logEventOperation"); - } + } - @Override - public void logEvent(IRequest pendingRequest, int eventCode, String message) { - log.trace("Dummy-logEventOperation"); + @Override + public void logEvent(final IRequest pendingRequest, final int eventCode, final String message) { + log.trace("Dummy-logEventOperation"); - } + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/logging/DummyStatisticLogger.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/logging/DummyStatisticLogger.java index 857186db..3d4a2e5e 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/logging/DummyStatisticLogger.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/logging/DummyStatisticLogger.java @@ -1,67 +1,61 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.logging; + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ +package at.gv.egiz.eaaf.core.impl.logging; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.idp.IAuthData; import at.gv.egiz.eaaf.core.api.logging.IStatisticLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; -@Service("DummyStatisticLogger") -public class DummyStatisticLogger implements IStatisticLogger{ - private static final Logger log = LoggerFactory.getLogger(DummyStatisticLogger.class); - - @Override - public void logSuccessOperation(IRequest protocolRequest, - IAuthData authData, boolean isSSOSession) { - log.trace("Dummy-logSuccessOperation"); - } - - @Override - public void logErrorOperation(Throwable throwable) { - log.trace("Dummy-logErrorOperation"); - } - - @Override - public void logErrorOperation(Throwable throwable, IRequest errorRequest) { - log.trace("Dummy-logErrorOperation"); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.advancedlogging.IStatisticLogger#testConnection() - */ - @Override - public void internalTesting() throws Exception { - log.trace("Dummy-logErrorOperation"); - - } +@Service("DummyStatisticLogger") +public class DummyStatisticLogger implements IStatisticLogger { + private static final Logger log = LoggerFactory.getLogger(DummyStatisticLogger.class); + + @Override + public void logSuccessOperation(final IRequest protocolRequest, final IAuthData authData, + final boolean isSsoSession) { + log.trace("Dummy-logSuccessOperation"); + } + + @Override + public void logErrorOperation(final Throwable throwable) { + log.trace("Dummy-logErrorOperation"); + } + + @Override + public void logErrorOperation(final Throwable throwable, final IRequest errorRequest) { + log.trace("Dummy-logErrorOperation"); + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.advancedlogging.IStatisticLogger#testConnection() + */ + @Override + public void internalTesting() throws Exception { + log.trace("Dummy-logErrorOperation"); + + } } diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/utils/DOMUtils.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/utils/DOMUtils.java deleted file mode 100644 index a9d33b74..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/utils/DOMUtils.java +++ /dev/null @@ -1,1267 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ - - -package at.gv.egiz.eaaf.core.impl.utils; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.Vector; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Result; -import javax.xml.transform.Source; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.xerces.parsers.DOMParser; -import org.apache.xerces.parsers.SAXParser; -import org.apache.xerces.parsers.XMLGrammarPreparser; -import org.apache.xerces.util.SymbolTable; -import org.apache.xerces.util.XMLGrammarPoolImpl; -import org.apache.xerces.xni.grammars.XMLGrammarDescription; -import org.apache.xerces.xni.grammars.XMLGrammarPool; -import org.apache.xerces.xni.parser.XMLInputSource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Attr; -import org.w3c.dom.Document; -import org.w3c.dom.DocumentFragment; -import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.EntityResolver; -import org.xml.sax.ErrorHandler; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -import at.gv.egiz.eaaf.core.api.data.XMLNamespaceConstants; - -/** - * Various utility functions for handling XML DOM trees. - * - * The parsing methods in this class make use of some features internal to the - * Xerces DOM parser, mainly for performance reasons. As soon as JAXP - * (currently at version 1.2) is better at schema handling, it should be used as - * the parser interface. - * - */ -public class DOMUtils { - private static final Logger log = LoggerFactory.getLogger(DOMUtils.class); - - /** Feature URI for namespace aware parsing. */ - private static final String NAMESPACES_FEATURE = - "http://xml.org/sax/features/namespaces"; - /** Feature URI for validating parsing. */ - private static final String VALIDATION_FEATURE = - "http://xml.org/sax/features/validation"; - /** Feature URI for schema validating parsing. */ - private static final String SCHEMA_VALIDATION_FEATURE = - "http://apache.org/xml/features/validation/schema"; - /** Feature URI for normalization of element/attribute values. */ - private static final String NORMALIZED_VALUE_FEATURE = - "http://apache.org/xml/features/validation/schema/normalized-value"; - /** Feature URI for parsing ignorable whitespace. */ - private static final String INCLUDE_IGNORABLE_WHITESPACE_FEATURE = - "http://apache.org/xml/features/dom/include-ignorable-whitespace"; - /** Feature URI for creating EntityReference nodes in the DOM tree. */ - private static final String CREATE_ENTITY_REF_NODES_FEATURE = - "http://apache.org/xml/features/dom/create-entity-ref-nodes"; - /** Property URI for providing external schema locations. */ - private static final String EXTERNAL_SCHEMA_LOCATION_PROPERTY = - "http://apache.org/xml/properties/schema/external-schemaLocation"; - /** Property URI for providing the external schema location for elements - * without a namespace. */ - private static final String EXTERNAL_NO_NAMESPACE_SCHEMA_LOCATION_PROPERTY = - "http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation"; - - private static final String EXTERNAL_GENERAL_ENTITIES_FEATURE = - "http://xml.org/sax/features/external-general-entities"; - - private static final String EXTERNAL_PARAMETER_ENTITIES_FEATURE = - "http://xml.org/sax/features/external-parameter-entities"; - - public static final String DISALLOW_DOCTYPE_FEATURE = - "http://apache.org/xml/features/disallow-doctype-decl"; - - - - /** Property URI for the Xerces grammar pool. */ - private static final String GRAMMAR_POOL = - org.apache.xerces.impl.Constants.XERCES_PROPERTY_PREFIX - + org.apache.xerces.impl.Constants.XMLGRAMMAR_POOL_PROPERTY; - /** A prime number for initializing the symbol table. */ - private static final int BIG_PRIME = 2039; - /** Symbol table for the grammar pool. */ - private static SymbolTable symbolTable = new SymbolTable(BIG_PRIME); - /** Xerces schema grammar pool. */ - private static XMLGrammarPool grammarPool = new XMLGrammarPoolImpl(); - /** Set holding the NamespaceURIs of the grammarPool, to prevent multiple - * entries of same grammars to the pool */ - private static Set grammarNamespaces; - - static { - grammarPool.lockPool(); - grammarNamespaces = new HashSet(); - } - - /** - * Preparse a schema and add it to the schema pool. - * The method only adds the schema to the pool if a schema having the same - * systemId (namespace URI) is not already present in the pool. - * - * @param inputStream An InputStream providing the contents of - * the schema. - * @param systemId The systemId (namespace URI) to use for the schema. - * @throws IOException An error occurred reading the schema. - */ - public static void addSchemaToPool(InputStream inputStream, String systemId) - throws IOException { - XMLGrammarPreparser preparser; - - if (!grammarNamespaces.contains(systemId)) { - - grammarNamespaces.add(systemId); - - // unlock the pool so that we can add another grammar - grammarPool.unlockPool(); - - // prepare the preparser - preparser = new XMLGrammarPreparser(symbolTable); - preparser.registerPreparser(XMLGrammarDescription.XML_SCHEMA, null); - preparser.setProperty(GRAMMAR_POOL, grammarPool); - preparser.setFeature(NAMESPACES_FEATURE, true); - preparser.setFeature(VALIDATION_FEATURE, true); - - // add the grammar to the pool - preparser.preparseGrammar( - XMLGrammarDescription.XML_SCHEMA, - new XMLInputSource(null, systemId, null, inputStream, null)); - - // lock the pool again so that schemas are not added automatically - grammarPool.lockPool(); - } - } - - /** - * Parse an XML document from an InputStream. - * - * @param inputStream The InputStream containing the XML - * document. - * @param validating If true, parse validating. - * @param externalSchemaLocations A String containing namespace - * URI to schema location pairs, the same way it is accepted by the xsi: - * schemaLocation attribute. - * @param externalNoNamespaceSchemaLocation The schema location of the - * schema for elements without a namespace, the same way it is accepted by the - * xsi:noNamespaceSchemaLocation attribute. - * @param entityResolver An EntityResolver to resolve external - * entities (schemas and DTDs). If null, it will not be set. - * @param errorHandler An ErrorHandler to decide what to do - * with parsing errors. If null, it will not be set. - * @return The parsed XML document as a DOM tree. - * @throws SAXException An error occurred parsing the document. - * @throws IOException An error occurred reading the document. - * @throws ParserConfigurationException An error occurred configuring the XML - * parser. - */ - public static Document parseDocument( - InputStream inputStream, - boolean validating, - String externalSchemaLocations, - String externalNoNamespaceSchemaLocation, - EntityResolver entityResolver, - ErrorHandler errorHandler, - Map parserFeatures) - throws SAXException, IOException, ParserConfigurationException { - - DOMParser parser; - -// class MyEntityResolver implements EntityResolver { -// -// public InputSource resolveEntity(String publicId, String systemId) -// throws SAXException, IOException { -// return new InputSource(new ByteArrayInputStream(new byte[0])); -// } -// } - - - //if Debug is enabled make a copy of inputStream to enable debug output in case of SAXException - byte buffer [] = null; - ByteArrayInputStream baStream = null; - if(true == log.isDebugEnabled()) { - buffer = IOUtils.toByteArray(inputStream); - baStream = new ByteArrayInputStream(buffer); - - } - - - - // create the DOM parser - if (symbolTable != null) { - parser = new DOMParser(symbolTable, grammarPool); - } else { - parser = new DOMParser(); - } - - // set parser features and properties - try { - parser.setFeature(NAMESPACES_FEATURE, true); - parser.setFeature(VALIDATION_FEATURE, validating); - parser.setFeature(SCHEMA_VALIDATION_FEATURE, validating); - parser.setFeature(NORMALIZED_VALUE_FEATURE, false); - parser.setFeature(INCLUDE_IGNORABLE_WHITESPACE_FEATURE, true); - parser.setFeature(CREATE_ENTITY_REF_NODES_FEATURE, false); - parser.setFeature(EXTERNAL_GENERAL_ENTITIES_FEATURE, false); - parser.setFeature(EXTERNAL_PARAMETER_ENTITIES_FEATURE, false); - - //set external added parser features - if (parserFeatures != null) { - for (Entry el : parserFeatures.entrySet()) { - String key = el.getKey(); - if (StringUtils.isNotEmpty(key)) { - Object value = el.getValue(); - if (value != null && value instanceof Boolean) - parser.setFeature(key, (boolean)value); - - else - log.warn("This XML parser only allows features with 'boolean' values"); - - } else - log.warn("Can not set 'null' feature to XML parser"); - } - } - - //fix XXE problem - //parser.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); - - - if (validating) { - if (externalSchemaLocations != null) { - parser.setProperty( - EXTERNAL_SCHEMA_LOCATION_PROPERTY, - externalSchemaLocations); - } - if (externalNoNamespaceSchemaLocation != null) { - parser.setProperty( - EXTERNAL_NO_NAMESPACE_SCHEMA_LOCATION_PROPERTY, - externalNoNamespaceSchemaLocation); - } - } - - // set entity resolver and error handler - if (entityResolver != null) { - parser.setEntityResolver(entityResolver); - } - if (errorHandler != null) { - parser.setErrorHandler(errorHandler); - } - - // parse the document and return it - // if debug is enabled: use copy of strem (baStream) else use orig stream - if(null != baStream) - parser.parse(new InputSource(baStream)); - else - parser.parse(new InputSource(inputStream)); - } catch(SAXException e) { - if(true == log.isDebugEnabled() && null != buffer) { - String xmlContent = new String(buffer); - log.debug("SAXException in:\n" + xmlContent); - } - throw(e); - } - - return parser.getDocument(); - } - - /** - * Parse an XML document from an InputStream. - * - * @param inputStream The InputStream containing the XML - * document. - * @param validating If true, parse validating. - * @param externalSchemaLocations A String containing namespace - * URI to schema location pairs, the same way it is accepted by the xsi: - * schemaLocation attribute. - * @param externalNoNamespaceSchemaLocation The schema location of the - * schema for elements without a namespace, the same way it is accepted by the - * xsi:noNamespaceSchemaLocation attribute. - * @param entityResolver An EntityResolver to resolve external - * entities (schemas and DTDs). If null, it will not be set. - * @param errorHandler An ErrorHandler to decide what to do - * with parsing errors. If null, it will not be set. - * @return The parsed XML document as a DOM tree. - * @throws SAXException An error occurred parsing the document. - * @throws IOException An error occurred reading the document. - * @throws ParserConfigurationException An error occurred configuring the XML - * parser. - */ - public static Document parseDocumentSimple(InputStream inputStream) - throws SAXException, IOException, ParserConfigurationException { - - DOMParser parser; - - parser = new DOMParser(); - // set parser features and properties - parser.setFeature(NAMESPACES_FEATURE, true); - parser.setFeature(VALIDATION_FEATURE, false); - parser.setFeature(SCHEMA_VALIDATION_FEATURE, false); - parser.setFeature(NORMALIZED_VALUE_FEATURE, false); - parser.setFeature(INCLUDE_IGNORABLE_WHITESPACE_FEATURE, true); - parser.setFeature(CREATE_ENTITY_REF_NODES_FEATURE, false); - - parser.parse(new InputSource(inputStream)); - - return parser.getDocument(); - } - - - /** - * Parse an XML document from an InputStream. - * - * It uses a MOAEntityResolver as the EntityResolver - * and a MOAErrorHandler as the ErrorHandler. - * - * @param inputStream The InputStream containing the XML - * document. - * @param validating If true, parse validating. - * @param externalSchemaLocations A String containing namespace - * URI to schema location pairs, the same way it is accepted by the xsi: - * schemaLocation attribute. - * @param externalNoNamespaceSchemaLocation The schema location of the - * schema for elements without a namespace, the same way it is accepted by the - * xsi:noNamespaceSchemaLocation attribute. - * @param parserFeatures - * @return The parsed XML document as a DOM tree. - * @throws SAXException An error occurred parsing the document. - * @throws IOException An error occurred reading the document. - * @throws ParserConfigurationException An error occurred configuring the XML - * parser. - */ - public static Document parseDocument( - InputStream inputStream, - boolean validating, - String externalSchemaLocations, - String externalNoNamespaceSchemaLocation, Map parserFeatures) - throws SAXException, IOException, ParserConfigurationException { - - - - return parseDocument( - inputStream, - validating, - externalSchemaLocations, - externalNoNamespaceSchemaLocation, - new EAAFDomEntityResolver(), - null, - parserFeatures); - } - - /** - * Parse an XML document from a String. - * - * It uses a MOAEntityResolver as the EntityResolver - * and a MOAErrorHandler as the ErrorHandler. - * - * @param xmlString The String containing the XML document. - * @param encoding The encoding of the XML document. - * @param validating If true, parse validating. - * @param externalSchemaLocations A String containing namespace - * URI to schema location pairs, the same way it is accepted by the xsi: - * schemaLocation attribute. - * @param externalNoNamespaceSchemaLocation The schema location of the - * schema for elements without a namespace, the same way it is accepted by the - * xsi:noNamespaceSchemaLocation attribute. - * @return The parsed XML document as a DOM tree. - * @throws SAXException An error occurred parsing the document. - * @throws IOException An error occurred reading the document. - * @throws ParserConfigurationException An error occurred configuring the XML - * parser. - */ - public static Document parseDocument( - String xmlString, - String encoding, - boolean validating, - String externalSchemaLocations, - String externalNoNamespaceSchemaLocation, - Map parserFeatures) - throws SAXException, IOException, ParserConfigurationException { - - InputStream in = new ByteArrayInputStream(xmlString.getBytes(encoding)); - return parseDocument( - in, - validating, - externalSchemaLocations, - externalNoNamespaceSchemaLocation, - parserFeatures); - } - - - /** - * Parse an XML document from a String. - * - * It uses a MOAEntityResolver as the EntityResolver - * and a MOAErrorHandler as the ErrorHandler. - * - * @param xmlString The String containing the XML document. - * @param encoding The encoding of the XML document. - * @param validating If true, parse validating. - * @param externalSchemaLocations A String containing namespace - * URI to schema location pairs, the same way it is accepted by the xsi: - * schemaLocation attribute. - * @param externalNoNamespaceSchemaLocation The schema location of the - * schema for elements without a namespace, the same way it is accepted by the - * xsi:noNamespaceSchemaLocation attribute. - * @return The parsed XML document as a DOM tree. - * @throws SAXException An error occurred parsing the document. - * @throws IOException An error occurred reading the document. - * @throws ParserConfigurationException An error occurred configuring the XML - * parser. - */ - public static Document parseDocument( - String xmlString, - String encoding, - boolean validating, - String externalSchemaLocations, - String externalNoNamespaceSchemaLocation) - throws SAXException, IOException, ParserConfigurationException { - - InputStream in = new ByteArrayInputStream(xmlString.getBytes(encoding)); - return parseDocument( - in, - validating, - externalSchemaLocations, - externalNoNamespaceSchemaLocation, - null); - } - - /** - * Parse an UTF-8 encoded XML document from a String. - * - * @param xmlString The String containing the XML document. - * @param validating If true, parse validating. - * @param externalSchemaLocations A String containing namespace - * URI to schema location pairs, the same way it is accepted by the xsi: - * schemaLocation attribute. - * @param externalNoNamespaceSchemaLocation The schema location of the - * schema for elements without a namespace, the same way it is accepted by the - * xsi:noNamespaceSchemaLocation attribute. - * @return The parsed XML document as a DOM tree. - * @throws SAXException An error occurred parsing the document. - * @throws IOException An error occurred reading the document. - * @throws ParserConfigurationException An error occurred configuring the XML - * parser. - */ - public static Document parseDocument( - String xmlString, - boolean validating, - String externalSchemaLocations, - String externalNoNamespaceSchemaLocation) - throws SAXException, IOException, ParserConfigurationException { - - return parseDocument( - xmlString, - "UTF-8", - validating, - externalSchemaLocations, - externalNoNamespaceSchemaLocation); - } - - /** - * A convenience method to parse an XML document validating. - * - * @param inputStream The InputStream containing the XML - * document. - * @return The root element of the parsed XML document. - * @throws SAXException An error occurred parsing the document. - * @throws IOException An error occurred reading the document. - * @throws ParserConfigurationException An error occurred configuring the XML - * parser. - */ - public static Element parseXmlValidating(InputStream inputStream) - throws ParserConfigurationException, SAXException, IOException { - return DOMUtils - .parseDocument(inputStream, true, XMLNamespaceConstants.ALL_SCHEMA_LOCATIONS, null, null) - .getDocumentElement(); - } - - /** - * A convenience method to parse an XML document validating. - * - * @param inputStream The InputStream containing the XML - * document. - * @param parserFeatures Set additional features to XML parser - * @return The root element of the parsed XML document. - * @throws SAXException An error occurred parsing the document. - * @throws IOException An error occurred reading the document. - * @throws ParserConfigurationException An error occurred configuring the XML - * parser. - */ - public static Element parseXmlValidating(InputStream inputStream, Map parserFeatures) - throws ParserConfigurationException, SAXException, IOException { - return DOMUtils - .parseDocument(inputStream, true, XMLNamespaceConstants.ALL_SCHEMA_LOCATIONS, null, parserFeatures) - .getDocumentElement(); - } - - /** - * A convenience method to parse an XML document non validating. - * This method disallow DocType declarations - * - * @param inputStream The InputStream containing the XML - * document. - * @return The root element of the parsed XML document. - * @throws SAXException An error occurred parsing the document. - * @throws IOException An error occurred reading the document. - * @throws ParserConfigurationException An error occurred configuring the XML - * parser. - */ - public static Element parseXmlNonValidating(InputStream inputStream) - throws ParserConfigurationException, SAXException, IOException { - return DOMUtils - .parseDocument(inputStream, false, XMLNamespaceConstants.ALL_SCHEMA_LOCATIONS, null, - Collections.unmodifiableMap(new HashMap() { - private static final long serialVersionUID = 1L; - { - put(DOMUtils.DISALLOW_DOCTYPE_FEATURE, true); - - } - })).getDocumentElement(); - } - - /** - * Schema validate a given DOM element. - * - * @param element The element to validate. - * @param externalSchemaLocations A String containing namespace - * URI to schema location pairs, the same way it is accepted by the xsi: - * schemaLocation attribute. - * @param externalNoNamespaceSchemaLocation The schema location of the - * schema for elements without a namespace, the same way it is accepted by the - * xsi:noNamespaceSchemaLocation attribute. - * @return true, if the element validates against - * the schemas declared in it. - * @throws SAXException An error occurred parsing the document. - * @throws IOException An error occurred reading the document from its - * serialized representation. - * @throws ParserConfigurationException An error occurred configuring the XML - * @throws TransformerException An error occurred serializing the element. - */ - public static boolean validateElement( - Element element, - String externalSchemaLocations, - String externalNoNamespaceSchemaLocation) - throws - ParserConfigurationException, - IOException, - SAXException, - TransformerException { - - byte[] docBytes; - SAXParser parser; - - // create the SAX parser - if (symbolTable != null) { - parser = new SAXParser(symbolTable, grammarPool); - } else { - parser = new SAXParser(); - } - - // serialize the document - docBytes = serializeNode(element, "UTF-8"); - - // set up parser features and attributes - parser.setFeature(NAMESPACES_FEATURE, true); - parser.setFeature(VALIDATION_FEATURE, true); - parser.setFeature(SCHEMA_VALIDATION_FEATURE, true); - parser.setFeature(EXTERNAL_GENERAL_ENTITIES_FEATURE, false); - parser.setFeature(DISALLOW_DOCTYPE_FEATURE, true); - - - if (externalSchemaLocations != null) { - parser.setProperty( - EXTERNAL_SCHEMA_LOCATION_PROPERTY, - externalSchemaLocations); - } - if (externalNoNamespaceSchemaLocation != null) { - parser.setProperty( - EXTERNAL_NO_NAMESPACE_SCHEMA_LOCATION_PROPERTY, - "externalNoNamespaceSchemaLocation"); - } - - // set up entity resolver and error handler - parser.setEntityResolver(new EAAFDomEntityResolver()); - - // parse validating - parser.parse(new InputSource(new ByteArrayInputStream(docBytes))); - return true; - } - - - /** - * Schema validate a given DOM element. - * - * @param element The element to validate. - * @param externalSchemaLocations A String containing namespace - * URI to schema location pairs, the same way it is accepted by the xsi: - * schemaLocation attribute. - * @param externalNoNamespaceSchemaLocation The schema location of the - * schema for elements without a namespace, the same way it is accepted by the - * xsi:noNamespaceSchemaLocation attribute. - * @return true, if the element validates against - * the schemas declared in it. - * @throws SAXException An error occurred parsing the document. - * @throws IOException An error occurred reading the document from its - * serialized representation. - * @throws ParserConfigurationException An error occurred configuring the XML - * @throws TransformerException An error occurred serializing the element. - */ - public static boolean validateElement( - Element element, - String externalSchemaLocations, - String externalNoNamespaceSchemaLocation, - EntityResolver entityResolver) - throws - ParserConfigurationException, - IOException, - SAXException, - TransformerException { - - byte[] docBytes; - SAXParser parser; - - // create the SAX parser - if (symbolTable != null) { - parser = new SAXParser(symbolTable, grammarPool); - } else { - parser = new SAXParser(); - } - - // serialize the document - docBytes = serializeNode(element, "UTF-8"); - - // set up parser features and attributes - parser.setFeature(NAMESPACES_FEATURE, true); - parser.setFeature(VALIDATION_FEATURE, true); - parser.setFeature(SCHEMA_VALIDATION_FEATURE, true); - - if (externalSchemaLocations != null) { - parser.setProperty( - EXTERNAL_SCHEMA_LOCATION_PROPERTY, - externalSchemaLocations); - } - if (externalNoNamespaceSchemaLocation != null) { - parser.setProperty( - EXTERNAL_NO_NAMESPACE_SCHEMA_LOCATION_PROPERTY, - "externalNoNamespaceSchemaLocation"); - } - - // set up entity resolver and error handler - parser.setEntityResolver(entityResolver); - - // parse validating - parser.parse(new InputSource(new ByteArrayInputStream(docBytes))); - return true; - } - - /** - * Serialize the given DOM node. - * - * The node will be serialized using the UTF-8 encoding. - * - * @param node The node to serialize. - * @return String The String representation of the given DOM - * node. - * @throws TransformerException An error occurred transforming the - * node to a String. - * @throws IOException An IO error occurred writing the node to a byte array. - */ - public static String serializeNode(Node node) - throws TransformerException, IOException { - return new String(serializeNode(node, "UTF-8", false), "UTF-8"); - } - - - /** - * Serialize the given DOM node. - * - * The node will be serialized using the UTF-8 encoding. - * - * @param node The node to serialize. - * @param omitXmlDeclaration The boolean value for omitting the XML Declaration. - * @return String The String representation of the given DOM - * node. - * @throws TransformerException An error occurred transforming the - * node to a String. - * @throws IOException An IO error occurred writing the node to a byte array. - */ - public static String serializeNode(Node node, boolean omitXmlDeclaration) - throws TransformerException, IOException { - return new String(serializeNode(node, "UTF-8", omitXmlDeclaration), "UTF-8"); - } - - /** - * Serialize the given DOM node. - * - * The node will be serialized using the UTF-8 encoding. - * - * @param node The node to serialize. - * @param omitXmlDeclaration The boolean value for omitting the XML Declaration. - * @param lineSeperator Sets the line seperator String of the parser - * @return String The String representation of the given DOM - * node. - * @throws TransformerException An error occurred transforming the - * node to a String. - * @throws IOException An IO error occurred writing the node to a byte array. - */ - public static String serializeNode(Node node, boolean omitXmlDeclaration, String lineSeperator) - throws TransformerException, IOException { - return new String(serializeNode(node, "UTF-8", omitXmlDeclaration, lineSeperator), "UTF-8"); - } - - /** - * Serialize the given DOM node to a byte array. - * - * @param node The node to serialize. - * @param xmlEncoding The XML encoding to use. - * @return The serialized node, as a byte array. Using a compatible encoding - * this can easily be converted into a String. - * @throws TransformerException An error occurred transforming the node to a - * byte array. - * @throws IOException An IO error occurred writing the node to a byte array. - */ - public static byte[] serializeNode(Node node, String xmlEncoding) - throws TransformerException, IOException { - return serializeNode(node, xmlEncoding, false); - } - - /** - * Serialize the given DOM node to a byte array. - * - * @param node The node to serialize. - * @param xmlEncoding The XML encoding to use. - * @param omitDeclaration The boolean value for omitting the XML Declaration. - * @return The serialized node, as a byte array. Using a compatible encoding - * this can easily be converted into a String. - * @throws TransformerException An error occurred transforming the node to a - * byte array. - * @throws IOException An IO error occurred writing the node to a byte array. - */ - public static byte[] serializeNode(Node node, String xmlEncoding, boolean omitDeclaration) - throws TransformerException, IOException { - return serializeNode(node, xmlEncoding, omitDeclaration, null); - } - - - /** - * Serialize the given DOM node to a byte array. - * - * @param node The node to serialize. - * @param xmlEncoding The XML encoding to use. - * @param omitDeclaration The boolean value for omitting the XML Declaration. - * @param lineSeperator Sets the line seperator String of the parser - * @return The serialized node, as a byte array. Using a compatible encoding - * this can easily be converted into a String. - * @throws TransformerException An error occurred transforming the node to a - * byte array. - * @throws IOException An IO error occurred writing the node to a byte array. - */ - public static byte[] serializeNode(Node node, String xmlEncoding, boolean omitDeclaration, String lineSeperator) - throws TransformerException, IOException { - - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - Transformer transformer = transformerFactory.newTransformer(); - ByteArrayOutputStream bos = new ByteArrayOutputStream(16384); - - transformer.setOutputProperty(OutputKeys.METHOD, "xml"); - transformer.setOutputProperty(OutputKeys.ENCODING, xmlEncoding); - String omit = omitDeclaration ? "yes" : "no"; - transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omit); - if (null!=lineSeperator) { - transformer.setOutputProperty("{http://xml.apache.org/xalan}line-separator", lineSeperator);//does not work for xalan <= 2.5.1 - } - transformer.transform(new DOMSource(node), new StreamResult(bos)); - - bos.flush(); - bos.close(); - - return bos.toByteArray(); - } - - /** - * Return the text that a node contains. - * - * This routine: - *
    - *
  • Ignores comments and processing instructions.
  • - *
  • Concatenates TEXT nodes, CDATA nodes, and the results recursively - * processing EntityRef nodes.
  • - *
  • Ignores any element nodes in the sublist. (Other possible options are - * to recurse into element sublists or throw an exception.)
  • - *
- * - * @param node A DOM node from which to extract text. - * @return A String representing its contents. - */ - public static String getText(Node node) { - if (!node.hasChildNodes()) { - return ""; - } - - StringBuffer result = new StringBuffer(); - NodeList list = node.getChildNodes(); - - for (int i = 0; i < list.getLength(); i++) { - Node subnode = list.item(i); - if (subnode.getNodeType() == Node.TEXT_NODE) { - result.append(subnode.getNodeValue()); - } else if (subnode.getNodeType() == Node.CDATA_SECTION_NODE) { - result.append(subnode.getNodeValue()); - } else if (subnode.getNodeType() == Node.ENTITY_REFERENCE_NODE) { - // Recurse into the subtree for text - // (and ignore comments) - result.append(getText(subnode)); - } - } - return result.toString(); - } - - /** - * Build the namespace prefix to namespace URL mapping in effect for a given - * node. - * - * @param node The context node for which build the map. - * @return The namespace prefix to namespace URL mapping ( - * a String value to String value mapping). - */ - public static Map getNamespaceDeclarations(Node node) { - Map nsDecls = new HashMap(); - int i; - - do { - if (node.hasAttributes()) { - NamedNodeMap attrs = node.getAttributes(); - - for (i = 0; i < attrs.getLength(); i++) { - Attr attr = (Attr) attrs.item(i); - - // add prefix mapping if none exists - if ("xmlns".equals(attr.getPrefix()) - || "xmlns".equals(attr.getName())) { - - String nsPrefix = - attr.getPrefix() != null ? attr.getLocalName() : ""; - - if (nsDecls.get(nsPrefix) == null) { - nsDecls.put(nsPrefix, attr.getValue()); - } - } - } - } - } while ((node = node.getParentNode()) != null); - - return nsDecls; - } - - /** - * Add all namespace declarations declared in the parent(s) of a given - * element and used in the subtree of the given element to the given element. - * - * @param context The element to which to add the namespaces. - */ - public static void localizeNamespaceDeclarations(Element context) { - Node parent = context.getParentNode(); - - if (parent != null) { - Map namespaces = getNamespaceDeclarations(context.getParentNode()); - Set nsUris = collectNamespaceURIs(context); - Iterator iter; - - for (iter = namespaces.entrySet().iterator(); iter.hasNext();) { - Map.Entry e = (Map.Entry) iter.next(); - - if (nsUris.contains(e.getValue())) { - String prefix = (String) e.getKey(); - String nsUri = (String) e.getValue(); - String nsAttrName = "".equals(prefix) ? "xmlns" : "xmlns:" + prefix; - - context.setAttributeNS(XMLNamespaceConstants.XMLNS_NS_URI, nsAttrName, nsUri); - } - } - } - } - - /** - * Collect all the namespace URIs used in the subtree of a given element. - * - * @param context The element that should be searched for namespace URIs. - * @return All namespace URIs used in the subtree of context, - * including the ones used in context itself. - */ - public static Set collectNamespaceURIs(Element context) { - Set result = new HashSet(); - - collectNamespaceURIsImpl(context, result); - return result; - } - - /** - * A recursive method to do the work of collectNamespaceURIs. - * - * @param context The context element to evaluate. - * @param result The result, passed as a parameter to avoid unnecessary - * instantiations of Set. - */ - private static void collectNamespaceURIsImpl(Element context, Set result) { - NamedNodeMap attrs = context.getAttributes(); - NodeList childNodes = context.getChildNodes(); - String nsUri; - int i; - - // add the namespace of the context element - nsUri = context.getNamespaceURI(); - if (nsUri != null && nsUri != XMLNamespaceConstants.XMLNS_NS_URI) { - result.add(nsUri); - } - - // add all namespace URIs from attributes - for (i = 0; i < attrs.getLength(); i++) { - nsUri = attrs.item(i).getNamespaceURI(); - if (nsUri != null && nsUri != XMLNamespaceConstants.XMLNS_NS_URI) { - result.add(nsUri); - } - } - - // add all namespaces from subelements - for (i = 0; i < childNodes.getLength(); i++) { - Node node = childNodes.item(i); - - if (node.getNodeType() == Node.ELEMENT_NODE) { - collectNamespaceURIsImpl((Element) node, result); - } - } - } - - /** - * Check, that each attribute node in the given NodeList has its - * parent in the NodeList as well. - * - * @param nodes The NodeList to check. - * @return true, if each attribute node in nodes - * has its parent in nodes as well. - */ - public static boolean checkAttributeParentsInNodeList(NodeList nodes) { - Set nodeSet = new HashSet(); - int i; - - // put the nodes into the nodeSet - for (i = 0; i < nodes.getLength(); i++) { - nodeSet.add(nodes.item(i)); - } - - // check that each attribute node's parent is in the node list - for (i = 0; i < nodes.getLength(); i++) { - Node n = nodes.item(i); - - if (n.getNodeType() == Node.ATTRIBUTE_NODE) { - Attr attr = (Attr) n; - Element owner = attr.getOwnerElement(); - - if (owner == null) { - if (!isNamespaceDeclaration(attr)) { - return false; - } - } - - if (!nodeSet.contains(owner) && !isNamespaceDeclaration(attr)) { - return false; - } - } - } - - return true; - } - - /** - * Convert an unstructured NodeList into a - * DocumentFragment. - * - * @param nodeList Contains the node list to be converted into a DOM - * DocumentFragment. - * @return the resulting DocumentFragment. The DocumentFragment will be - * backed by a new DOM Document, i.e. all noded of the node list will be - * cloned. - * @throws ParserConfigurationException An error occurred creating the - * DocumentFragment. - * @precondition The nodes in the node list appear in document order - * @precondition for each Attr node in the node list, the owning Element is - * in the node list as well. - * @precondition each Element or Attr node in the node list is namespace - * aware. - */ - public static DocumentFragment nodeList2DocumentFragment(NodeList nodeList) - throws ParserConfigurationException { - - DocumentBuilder builder = - DocumentBuilderFactory.newInstance().newDocumentBuilder(); - Document doc = builder.newDocument(); - DocumentFragment result = doc.createDocumentFragment(); - - if (null == nodeList || nodeList.getLength() == 0) { - return result; - } - - int currPos = 0; - currPos = - nodeList2DocumentFragment(nodeList, currPos, result, null, null) + 1; - - while (currPos < nodeList.getLength()) { - currPos = - nodeList2DocumentFragment(nodeList, currPos, result, null, null) + 1; - } - return result; - } - - /** - * Helper method for the nodeList2DocumentFragment. - * - * @param nodeList The NodeList to convert. - * @param currPos The current position in the nodeList. - * @param result The resulting DocumentFragment. - * @param currOrgElem The current original element. - * @param currClonedElem The current cloned element. - * @return The current position. - */ - private static int nodeList2DocumentFragment( - NodeList nodeList, - int currPos, - DocumentFragment result, - Element currOrgElem, - Element currClonedElem) { - - while (currPos < nodeList.getLength()) { - Node currentNode = nodeList.item(currPos); - switch (currentNode.getNodeType()) { - case Node.COMMENT_NODE : - case Node.PROCESSING_INSTRUCTION_NODE : - case Node.TEXT_NODE : - { - // Append current node either to resulting DocumentFragment or to - // current cloned Element - if (null == currClonedElem) { - result.appendChild( - result.getOwnerDocument().importNode(currentNode, false)); - } else { - // Stop processing if current Node is not a descendant of - // current Element - if (!isAncestor(currOrgElem, currentNode)) { - return --currPos; - } - - currClonedElem.appendChild( - result.getOwnerDocument().importNode(currentNode, false)); - } - break; - } - - case Node.ELEMENT_NODE : - { - Element nextCurrOrgElem = (Element) currentNode; - Element nextCurrClonedElem = - result.getOwnerDocument().createElementNS( - nextCurrOrgElem.getNamespaceURI(), - nextCurrOrgElem.getNodeName()); - - // Append current Node either to resulting DocumentFragment or to - // current cloned Element - if (null == currClonedElem) { - result.appendChild(nextCurrClonedElem); - currOrgElem = nextCurrOrgElem; - currClonedElem = nextCurrClonedElem; - } else { - // Stop processing if current Node is not a descendant of - // current Element - if (!isAncestor(currOrgElem, currentNode)) { - return --currPos; - } - - currClonedElem.appendChild(nextCurrClonedElem); - } - - // Process current Node (of type Element) recursively - currPos = - nodeList2DocumentFragment( - nodeList, - ++currPos, - result, - nextCurrOrgElem, - nextCurrClonedElem); - - break; - } - - case Node.ATTRIBUTE_NODE : - { - Attr currAttr = (Attr) currentNode; - - // GK 20030411: Hack to overcome problems with IAIK IXSIL - if (currAttr.getOwnerElement() == null) - break; - if (currClonedElem == null) - break; - - // currClonedElem must be the owner Element of currAttr if - // preconditions are met - currClonedElem.setAttributeNS( - currAttr.getNamespaceURI(), - currAttr.getNodeName(), - currAttr.getValue()); - break; - } - - default : - { - // All other nodes will be ignored - } - } - - currPos++; - } - - return currPos; - } - - /** - * Check, if the given attribute is a namespace declaration. - * - * @param attr The attribute to check. - * @return true, if the attribute is a namespace declaration, - * false otherwise. - */ - private static boolean isNamespaceDeclaration(Attr attr) { - return XMLNamespaceConstants.XMLNS_NS_URI.equals(attr.getNamespaceURI()); - } - - /** - * Check, if a given DOM element is an ancestor of a given node. - * - * @param candAnc The DOM element to check for being the ancestor. - * @param cand The node to check for being the child. - * @return true, if candAnc is an (indirect) - * ancestor of cand; false otherwise. - */ - public static boolean isAncestor(Element candAnc, Node cand) { - Node currPar = cand.getParentNode(); - - while (currPar != null) { - if (candAnc == currPar) - return true; - currPar = currPar.getParentNode(); - } - return false; - } - - /** - * Selects the (first) element from a node list and returns it. - * - * @param nl The NodeList to get the element from. - * @return The (first) element included in the node list or null - * if the node list is null or empty or no element is - * included in the list. - */ - public static Element getElementFromNodeList (NodeList nl) { - if ((nl == null) || (nl.getLength() == 0)) { - return null; - } - for (int i=0; i + * The parsing methods in this class make use of some features internal to the Xerces DOM parser, + * mainly for performance reasons. As soon as JAXP (currently at version 1.2) is better at schema + * handling, it should be used as the parser interface. + *

+ * + */ +public class DomUtils { + private static final Logger log = LoggerFactory.getLogger(DomUtils.class); + + /** Feature URI for namespace aware parsing. */ + private static final String NAMESPACES_FEATURE = "http://xml.org/sax/features/namespaces"; + /** Feature URI for validating parsing. */ + private static final String VALIDATION_FEATURE = "http://xml.org/sax/features/validation"; + /** Feature URI for schema validating parsing. */ + private static final String SCHEMA_VALIDATION_FEATURE = + "http://apache.org/xml/features/validation/schema"; + /** Feature URI for normalization of element/attribute values. */ + private static final String NORMALIZED_VALUE_FEATURE = + "http://apache.org/xml/features/validation/schema/normalized-value"; + /** Feature URI for parsing ignorable whitespace. */ + private static final String INCLUDE_IGNORABLE_WHITESPACE_FEATURE = + "http://apache.org/xml/features/dom/include-ignorable-whitespace"; + /** Feature URI for creating EntityReference nodes in the DOM tree. */ + private static final String CREATE_ENTITY_REF_NODES_FEATURE = + "http://apache.org/xml/features/dom/create-entity-ref-nodes"; + /** Property URI for providing external schema locations. */ + private static final String EXTERNAL_SCHEMA_LOCATION_PROPERTY = + "http://apache.org/xml/properties/schema/external-schemaLocation"; + /** + * Property URI for providing the external schema location for elements without a namespace. + */ + private static final String EXTERNAL_NO_NAMESPACE_SCHEMA_LOCATION_PROPERTY = + "http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation"; + + private static final String EXTERNAL_GENERAL_ENTITIES_FEATURE = + "http://xml.org/sax/features/external-general-entities"; + + private static final String EXTERNAL_PARAMETER_ENTITIES_FEATURE = + "http://xml.org/sax/features/external-parameter-entities"; + + public static final String DISALLOW_DOCTYPE_FEATURE = + "http://apache.org/xml/features/disallow-doctype-decl"; + + + + /** Property URI for the Xerces grammar pool. */ + private static final String GRAMMAR_POOL = org.apache.xerces.impl.Constants.XERCES_PROPERTY_PREFIX + + org.apache.xerces.impl.Constants.XMLGRAMMAR_POOL_PROPERTY; + /** A prime number for initializing the symbol table. */ + private static final int BIG_PRIME = 2039; + /** Symbol table for the grammar pool. */ + private static SymbolTable symbolTable = new SymbolTable(BIG_PRIME); + /** Xerces schema grammar pool. */ + private static XMLGrammarPool grammarPool = new XMLGrammarPoolImpl(); + /** + * Set holding the NamespaceURIs of the grammarPool, to prevent multiple entries of same grammars + * to the pool. + */ + private static Set grammarNamespaces; + + static { + grammarPool.lockPool(); + grammarNamespaces = new HashSet(); + } + + /** + * Preparse a schema and add it to the schema pool. The method only adds the schema to the pool if + * a schema having the same systemId (namespace URI) is not already present in the + * pool. + * + * @param inputStream An InputStream providing the contents of the schema. + * @param systemId The systemId (namespace URI) to use for the schema. + * @throws IOException An error occurred reading the schema. + */ + public static void addSchemaToPool(final InputStream inputStream, final String systemId) + throws IOException { + XMLGrammarPreparser preparser; + + if (!grammarNamespaces.contains(systemId)) { + + grammarNamespaces.add(systemId); + + // unlock the pool so that we can add another grammar + grammarPool.unlockPool(); + + // prepare the preparser + preparser = new XMLGrammarPreparser(symbolTable); + preparser.registerPreparser(XMLGrammarDescription.XML_SCHEMA, null); + preparser.setProperty(GRAMMAR_POOL, grammarPool); + preparser.setFeature(NAMESPACES_FEATURE, true); + preparser.setFeature(VALIDATION_FEATURE, true); + + // add the grammar to the pool + preparser.preparseGrammar(XMLGrammarDescription.XML_SCHEMA, + new XMLInputSource(null, systemId, null, inputStream, null)); + + // lock the pool again so that schemas are not added automatically + grammarPool.lockPool(); + } + } + + /** + * Parse an XML document from an InputStream. + * + *

+ * It uses a MOAEntityResolver as the EntityResolver and a + * MOAErrorHandler as the ErrorHandler. + *

+ * + * @param inputStream The InputStream containing the XML document. + * @param validating If true, parse validating. + * @param externalSchemaLocations A String containing namespace URI to schema + * location pairs, the same way it is accepted by the xsi: + * schemaLocation attribute. + * @param externalNoNamespaceSchemaLocation The schema location of the schema for elements without + * a namespace, the same way it is accepted by the + * xsi:noNamespaceSchemaLocation attribute. + * @param parserFeatures Map of features that should be set into XML parser + * @return The parsed XML document as a DOM tree. + * @throws SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document. + * @throws ParserConfigurationException An error occurred configuring the XML parser. + */ + public static Document parseDocument(final InputStream inputStream, final boolean validating, + final String externalSchemaLocations, final String externalNoNamespaceSchemaLocation, + final Map parserFeatures) + throws SAXException, IOException, ParserConfigurationException { + + return parseDocument(inputStream, validating, externalSchemaLocations, + externalNoNamespaceSchemaLocation, new EaafDomEntityResolver(), null, parserFeatures); + } + + /** + * Parse an XML document from a String. + * + *

+ * It uses a MOAEntityResolver as the EntityResolver and a + * MOAErrorHandler as the ErrorHandler. + *

+ * + * @param xmlString The String containing the XML document. + * @param encoding The encoding of the XML document. + * @param validating If true, parse validating. + * @param externalSchemaLocations A String containing namespace URI to schema + * location pairs, the same way it is accepted by the xsi: + * schemaLocation attribute. + * @param externalNoNamespaceSchemaLocation The schema location of the schema for elements without + * a namespace, the same way it is accepted by the + * xsi:noNamespaceSchemaLocation attribute. + * @return The parsed XML document as a DOM tree. + * @throws SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document. + * @throws ParserConfigurationException An error occurred configuring the XML parser. + */ + public static Document parseDocument(final String xmlString, final String encoding, + final boolean validating, final String externalSchemaLocations, + final String externalNoNamespaceSchemaLocation, final Map parserFeatures) + throws SAXException, IOException, ParserConfigurationException { + + final InputStream in = new ByteArrayInputStream(xmlString.getBytes(encoding)); + return parseDocument(in, validating, externalSchemaLocations, externalNoNamespaceSchemaLocation, + parserFeatures); + } + + /** + * Parse an XML document from a String. + * + *

+ * It uses a MOAEntityResolver as the EntityResolver and a + * MOAErrorHandler as the ErrorHandler. + *

+ * + * @param xmlString The String containing the XML document. + * @param encoding The encoding of the XML document. + * @param validating If true, parse validating. + * @param externalSchemaLocations A String containing namespace URI to schema + * location pairs, the same way it is accepted by the xsi: + * schemaLocation attribute. + * @param externalNoNamespaceSchemaLocation The schema location of the schema for elements without + * a namespace, the same way it is accepted by the + * xsi:noNamespaceSchemaLocation attribute. + * @return The parsed XML document as a DOM tree. + * @throws SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document. + * @throws ParserConfigurationException An error occurred configuring the XML parser. + */ + public static Document parseDocument(final String xmlString, final String encoding, + final boolean validating, final String externalSchemaLocations, + final String externalNoNamespaceSchemaLocation) + throws SAXException, IOException, ParserConfigurationException { + + final InputStream in = new ByteArrayInputStream(xmlString.getBytes(encoding)); + return parseDocument(in, validating, externalSchemaLocations, externalNoNamespaceSchemaLocation, + null); + } + + /** + * Parse an UTF-8 encoded XML document from a String. + * + * @param xmlString The String containing the XML document. + * @param validating If true, parse validating. + * @param externalSchemaLocations A String containing namespace URI to schema + * location pairs, the same way it is accepted by the xsi: + * schemaLocation attribute. + * @param externalNoNamespaceSchemaLocation The schema location of the schema for elements without + * a namespace, the same way it is accepted by the + * xsi:noNamespaceSchemaLocation attribute. + * @return The parsed XML document as a DOM tree. + * @throws SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document. + * @throws ParserConfigurationException An error occurred configuring the XML parser. + */ + public static Document parseDocument(final String xmlString, final boolean validating, + final String externalSchemaLocations, final String externalNoNamespaceSchemaLocation) + throws SAXException, IOException, ParserConfigurationException { + + return parseDocument(xmlString, "UTF-8", validating, externalSchemaLocations, + externalNoNamespaceSchemaLocation); + } + + /** + * Parse an XML document from an InputStream. + * + * @param inputStream The InputStream containing the XML document. + * @param validating If true, parse validating. + * @param externalSchemaLocations A String containing namespace URI to schema + * location pairs, the same way it is accepted by the xsi: + * schemaLocation attribute. + * @param externalNoNamespaceSchemaLocation The schema location of the schema for elements without + * a namespace, the same way it is accepted by the + * xsi:noNamespaceSchemaLocation attribute. + * @param entityResolver An EntityResolver to resolve external entities (schemas and + * DTDs). If null, it will not be set. + * @param errorHandler An ErrorHandler to decide what to do with parsing errors. If + * null, it will not be set. + * @return The parsed XML document as a DOM tree. + * @throws SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document. + * @throws ParserConfigurationException An error occurred configuring the XML parser. + */ + public static Document parseDocument(final InputStream inputStream, final boolean validating, + final String externalSchemaLocations, final String externalNoNamespaceSchemaLocation, + final EntityResolver entityResolver, final ErrorHandler errorHandler, + final Map parserFeatures) + throws SAXException, IOException, ParserConfigurationException { + + DOMParser parser; + + // class MyEntityResolver implements EntityResolver { + // + // public InputSource resolveEntity(String publicId, String systemId) + // throws SAXException, IOException { + // return new InputSource(new ByteArrayInputStream(new byte[0])); + // } + // } + + + // if Debug is enabled make a copy of inputStream to enable debug output in case of SAXException + byte[] buffer = null; + ByteArrayInputStream baStream = null; + if (true == log.isDebugEnabled()) { + buffer = IOUtils.toByteArray(inputStream); + baStream = new ByteArrayInputStream(buffer); + + } + + + + // create the DOM parser + if (symbolTable != null) { + parser = new DOMParser(symbolTable, grammarPool); + } else { + parser = new DOMParser(); + } + + // set parser features and properties + try { + parser.setFeature(NAMESPACES_FEATURE, true); + parser.setFeature(VALIDATION_FEATURE, validating); + parser.setFeature(SCHEMA_VALIDATION_FEATURE, validating); + parser.setFeature(NORMALIZED_VALUE_FEATURE, false); + parser.setFeature(INCLUDE_IGNORABLE_WHITESPACE_FEATURE, true); + parser.setFeature(CREATE_ENTITY_REF_NODES_FEATURE, false); + parser.setFeature(EXTERNAL_GENERAL_ENTITIES_FEATURE, false); + parser.setFeature(EXTERNAL_PARAMETER_ENTITIES_FEATURE, false); + + // set external added parser features + if (parserFeatures != null) { + for (final Entry el : parserFeatures.entrySet()) { + final String key = el.getKey(); + if (StringUtils.isNotEmpty(key)) { + final Object value = el.getValue(); + if (value != null && value instanceof Boolean) { + parser.setFeature(key, (boolean) value); + } else { + log.warn("This XML parser only allows features with 'boolean' values"); + } + + } else { + log.warn("Can not set 'null' feature to XML parser"); + } + } + } + + // fix XXE problem + // parser.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + + + if (validating) { + if (externalSchemaLocations != null) { + parser.setProperty(EXTERNAL_SCHEMA_LOCATION_PROPERTY, externalSchemaLocations); + } + if (externalNoNamespaceSchemaLocation != null) { + parser.setProperty(EXTERNAL_NO_NAMESPACE_SCHEMA_LOCATION_PROPERTY, + externalNoNamespaceSchemaLocation); + } + } + + // set entity resolver and error handler + if (entityResolver != null) { + parser.setEntityResolver(entityResolver); + } + if (errorHandler != null) { + parser.setErrorHandler(errorHandler); + } + + // parse the document and return it + // if debug is enabled: use copy of strem (baStream) else use orig stream + if (null != baStream) { + parser.parse(new InputSource(baStream)); + } else { + parser.parse(new InputSource(inputStream)); + } + } catch (final SAXException e) { + if (true == log.isDebugEnabled() && null != buffer) { + final String xmlContent = new String(buffer, "UTF-8"); + log.debug("SAXException in:\n" + xmlContent); + } + throw (e); + } + + return parser.getDocument(); + } + + /** + * Simple document parser. + * + * @param inputStream data to parse + * @return Element + * @throws SAXException In case of an error + * @throws IOException In case of an error + * @throws ParserConfigurationException In case of an error + */ + public static Document parseDocumentSimple(final InputStream inputStream) + throws SAXException, IOException, ParserConfigurationException { + + DOMParser parser; + + parser = new DOMParser(); + // set parser features and properties + parser.setFeature(NAMESPACES_FEATURE, true); + parser.setFeature(VALIDATION_FEATURE, false); + parser.setFeature(SCHEMA_VALIDATION_FEATURE, false); + parser.setFeature(NORMALIZED_VALUE_FEATURE, false); + parser.setFeature(INCLUDE_IGNORABLE_WHITESPACE_FEATURE, true); + parser.setFeature(CREATE_ENTITY_REF_NODES_FEATURE, false); + + parser.parse(new InputSource(inputStream)); + + return parser.getDocument(); + } + + + + + + + + + + + + /** + * A convenience method to parse an XML document validating. + * + * @param inputStream The InputStream containing the XML document. + * @return The root element of the parsed XML document. + * @throws SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document. + * @throws ParserConfigurationException An error occurred configuring the XML parser. + */ + public static Element parseXmlValidating(final InputStream inputStream) + throws ParserConfigurationException, SAXException, IOException { + return DomUtils + .parseDocument(inputStream, true, XMLNamespaceConstants.ALL_SCHEMA_LOCATIONS, null, null) + .getDocumentElement(); + } + + /** + * A convenience method to parse an XML document validating. + * + * @param inputStream The InputStream containing the XML document. + * @param parserFeatures Set additional features to XML parser + * @return The root element of the parsed XML document. + * @throws SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document. + * @throws ParserConfigurationException An error occurred configuring the XML parser. + */ + public static Element parseXmlValidating(final InputStream inputStream, + final Map parserFeatures) + throws ParserConfigurationException, SAXException, IOException { + return DomUtils.parseDocument(inputStream, true, XMLNamespaceConstants.ALL_SCHEMA_LOCATIONS, + null, parserFeatures).getDocumentElement(); + } + + /** + * A convenience method to parse an XML document non validating. This method disallow DocType + * declarations + * + * @param inputStream The InputStream containing the XML document. + * @return The root element of the parsed XML document. + * @throws SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document. + * @throws ParserConfigurationException An error occurred configuring the XML parser. + */ + public static Element parseXmlNonValidating(final InputStream inputStream) + throws ParserConfigurationException, SAXException, IOException { + return DomUtils.parseDocument(inputStream, false, XMLNamespaceConstants.ALL_SCHEMA_LOCATIONS, + null, Collections.unmodifiableMap(new HashMap() { + private static final long serialVersionUID = 1L; + { + put(DomUtils.DISALLOW_DOCTYPE_FEATURE, true); + + } + })).getDocumentElement(); + } + + /** + * Schema validate a given DOM element. + * + * @param element The element to validate. + * @param externalSchemaLocations A String containing namespace URI to schema + * location pairs, the same way it is accepted by the xsi: + * schemaLocation attribute. + * @param externalNoNamespaceSchemaLocation The schema location of the schema for elements without + * a namespace, the same way it is accepted by the + * xsi:noNamespaceSchemaLocation attribute. + * @return true, if the element validates against the schemas declared + * in it. + * @throws SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document from its serialized representation. + * @throws ParserConfigurationException An error occurred configuring the XML + * @throws TransformerException An error occurred serializing the element. + */ + public static boolean validateElement(final Element element, final String externalSchemaLocations, + final String externalNoNamespaceSchemaLocation) + throws ParserConfigurationException, IOException, SAXException, TransformerException { + + byte[] docBytes; + SAXParser parser; + + // create the SAX parser + if (symbolTable != null) { + parser = new SAXParser(symbolTable, grammarPool); + } else { + parser = new SAXParser(); + } + + // serialize the document + docBytes = serializeNode(element, "UTF-8"); + + // set up parser features and attributes + parser.setFeature(NAMESPACES_FEATURE, true); + parser.setFeature(VALIDATION_FEATURE, true); + parser.setFeature(SCHEMA_VALIDATION_FEATURE, true); + parser.setFeature(EXTERNAL_GENERAL_ENTITIES_FEATURE, false); + parser.setFeature(DISALLOW_DOCTYPE_FEATURE, true); + + + if (externalSchemaLocations != null) { + parser.setProperty(EXTERNAL_SCHEMA_LOCATION_PROPERTY, externalSchemaLocations); + } + if (externalNoNamespaceSchemaLocation != null) { + parser.setProperty(EXTERNAL_NO_NAMESPACE_SCHEMA_LOCATION_PROPERTY, + "externalNoNamespaceSchemaLocation"); + } + + // set up entity resolver and error handler + parser.setEntityResolver(new EaafDomEntityResolver()); + + // parse validating + parser.parse(new InputSource(new ByteArrayInputStream(docBytes))); + return true; + } + + + /** + * Schema validate a given DOM element. + * + * @param element The element to validate. + * @param externalSchemaLocations A String containing namespace URI to schema + * location pairs, the same way it is accepted by the xsi: + * schemaLocation attribute. + * @param externalNoNamespaceSchemaLocation The schema location of the schema for elements without + * a namespace, the same way it is accepted by the + * xsi:noNamespaceSchemaLocation attribute. + * @return true, if the element validates against the schemas declared + * in it. + * @throws SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document from its serialized representation. + * @throws ParserConfigurationException An error occurred configuring the XML + * @throws TransformerException An error occurred serializing the element. + */ + public static boolean validateElement(final Element element, final String externalSchemaLocations, + final String externalNoNamespaceSchemaLocation, final EntityResolver entityResolver) + throws ParserConfigurationException, IOException, SAXException, TransformerException { + + byte[] docBytes; + SAXParser parser; + + // create the SAX parser + if (symbolTable != null) { + parser = new SAXParser(symbolTable, grammarPool); + } else { + parser = new SAXParser(); + } + + // serialize the document + docBytes = serializeNode(element, "UTF-8"); + + // set up parser features and attributes + parser.setFeature(NAMESPACES_FEATURE, true); + parser.setFeature(VALIDATION_FEATURE, true); + parser.setFeature(SCHEMA_VALIDATION_FEATURE, true); + + if (externalSchemaLocations != null) { + parser.setProperty(EXTERNAL_SCHEMA_LOCATION_PROPERTY, externalSchemaLocations); + } + if (externalNoNamespaceSchemaLocation != null) { + parser.setProperty(EXTERNAL_NO_NAMESPACE_SCHEMA_LOCATION_PROPERTY, + "externalNoNamespaceSchemaLocation"); + } + + // set up entity resolver and error handler + parser.setEntityResolver(entityResolver); + + // parse validating + parser.parse(new InputSource(new ByteArrayInputStream(docBytes))); + return true; + } + + /** + * Serialize the given DOM node. + * + *

+ * The node will be serialized using the UTF-8 encoding. + *

+ * + * @param node The node to serialize. + * @return String The String representation of the given DOM node. + * @throws TransformerException An error occurred transforming the node to a String. + * @throws IOException An IO error occurred writing the node to a byte array. + */ + public static String serializeNode(final Node node) throws TransformerException, IOException { + return new String(serializeNode(node, "UTF-8", false), "UTF-8"); + } + + + /** + * Serialize the given DOM node. + * + *

+ * The node will be serialized using the UTF-8 encoding. + *

+ * + * @param node The node to serialize. + * @param omitXmlDeclaration The boolean value for omitting the XML Declaration. + * @return String The String representation of the given DOM node. + * @throws TransformerException An error occurred transforming the node to a String. + * @throws IOException An IO error occurred writing the node to a byte array. + */ + public static String serializeNode(final Node node, final boolean omitXmlDeclaration) + throws TransformerException, IOException { + return new String(serializeNode(node, "UTF-8", omitXmlDeclaration), "UTF-8"); + } + + /** + * Serialize the given DOM node. + * + *

+ * The node will be serialized using the UTF-8 encoding. + *

+ * + * @param node The node to serialize. + * @param omitXmlDeclaration The boolean value for omitting the XML Declaration. + * @param lineSeperator Sets the line seperator String of the parser + * @return String The String representation of the given DOM node. + * @throws TransformerException An error occurred transforming the node to a String. + * @throws IOException An IO error occurred writing the node to a byte array. + */ + public static String serializeNode(final Node node, final boolean omitXmlDeclaration, + final String lineSeperator) throws TransformerException, IOException { + return new String(serializeNode(node, "UTF-8", omitXmlDeclaration, lineSeperator), "UTF-8"); + } + + /** + * Serialize the given DOM node to a byte array. + * + * @param node The node to serialize. + * @param xmlEncoding The XML encoding to use. + * @return The serialized node, as a byte array. Using a compatible encoding this can easily be + * converted into a String. + * @throws TransformerException An error occurred transforming the node to a byte array. + * @throws IOException An IO error occurred writing the node to a byte array. + */ + public static byte[] serializeNode(final Node node, final String xmlEncoding) + throws TransformerException, IOException { + return serializeNode(node, xmlEncoding, false); + } + + /** + * Serialize the given DOM node to a byte array. + * + * @param node The node to serialize. + * @param xmlEncoding The XML encoding to use. + * @param omitDeclaration The boolean value for omitting the XML Declaration. + * @return The serialized node, as a byte array. Using a compatible encoding this can easily be + * converted into a String. + * @throws TransformerException An error occurred transforming the node to a byte array. + * @throws IOException An IO error occurred writing the node to a byte array. + */ + public static byte[] serializeNode(final Node node, final String xmlEncoding, + final boolean omitDeclaration) throws TransformerException, IOException { + return serializeNode(node, xmlEncoding, omitDeclaration, null); + } + + + /** + * Serialize the given DOM node to a byte array. + * + * @param node The node to serialize. + * @param xmlEncoding The XML encoding to use. + * @param omitDeclaration The boolean value for omitting the XML Declaration. + * @param lineSeperator Sets the line seperator String of the parser + * @return The serialized node, as a byte array. Using a compatible encoding this can easily be + * converted into a String. + * @throws TransformerException An error occurred transforming the node to a byte array. + * @throws IOException An IO error occurred writing the node to a byte array. + */ + public static byte[] serializeNode(final Node node, final String xmlEncoding, + final boolean omitDeclaration, final String lineSeperator) + throws TransformerException, IOException { + + final TransformerFactory transformerFactory = TransformerFactory.newInstance(); + final Transformer transformer = transformerFactory.newTransformer(); + final ByteArrayOutputStream bos = new ByteArrayOutputStream(16384); + + transformer.setOutputProperty(OutputKeys.METHOD, "xml"); + transformer.setOutputProperty(OutputKeys.ENCODING, xmlEncoding); + final String omit = omitDeclaration ? "yes" : "no"; + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omit); + if (null != lineSeperator) { + transformer.setOutputProperty("{http://xml.apache.org/xalan}line-separator", lineSeperator); + // does not work for xalan <= 2.5.1 + } + transformer.transform(new DOMSource(node), new StreamResult(bos)); + + bos.flush(); + bos.close(); + + return bos.toByteArray(); + } + + /** + * Return the text that a node contains. + * + *

+ * This routine: + *

+ *
    + *
  • Ignores comments and processing instructions.
  • + *
  • Concatenates TEXT nodes, CDATA nodes, and the results recursively processing EntityRef + * nodes.
  • + *
  • Ignores any element nodes in the sublist. (Other possible options are to recurse into + * element sublists or throw an exception.)
  • + *
+ * + * @param node A DOM node from which to extract text. + * @return A String representing its contents. + */ + public static String getText(final Node node) { + if (!node.hasChildNodes()) { + return ""; + } + + final StringBuffer result = new StringBuffer(); + final NodeList list = node.getChildNodes(); + + for (int i = 0; i < list.getLength(); i++) { + final Node subnode = list.item(i); + if (subnode.getNodeType() == Node.TEXT_NODE) { + result.append(subnode.getNodeValue()); + } else if (subnode.getNodeType() == Node.CDATA_SECTION_NODE) { + result.append(subnode.getNodeValue()); + } else if (subnode.getNodeType() == Node.ENTITY_REFERENCE_NODE) { + // Recurse into the subtree for text + // (and ignore comments) + result.append(getText(subnode)); + } + } + return result.toString(); + } + + /** + * Build the namespace prefix to namespace URL mapping in effect for a given node. + * + * @param node The context node for which build the map. + * @return The namespace prefix to namespace URL mapping ( a String value to + * String value mapping). + */ + public static Map getNamespaceDeclarations(Node node) { + final Map nsDecls = new HashMap(); + int i; + + do { + if (node.hasAttributes()) { + final NamedNodeMap attrs = node.getAttributes(); + + for (i = 0; i < attrs.getLength(); i++) { + final Attr attr = (Attr) attrs.item(i); + + // add prefix mapping if none exists + if ("xmlns".equals(attr.getPrefix()) || "xmlns".equals(attr.getName())) { + + final String nsPrefix = attr.getPrefix() != null ? attr.getLocalName() : ""; + + if (nsDecls.get(nsPrefix) == null) { + nsDecls.put(nsPrefix, attr.getValue()); + } + } + } + } + } while ((node = node.getParentNode()) != null); + + return nsDecls; + } + + /** + * Add all namespace declarations declared in the parent(s) of a given element and used in the + * subtree of the given element to the given element. + * + * @param context The element to which to add the namespaces. + */ + public static void localizeNamespaceDeclarations(final Element context) { + final Node parent = context.getParentNode(); + + if (parent != null) { + final Map namespaces = getNamespaceDeclarations(context.getParentNode()); + final Set nsUris = collectNamespaceUris(context); + Iterator iter; + + for (iter = namespaces.entrySet().iterator(); iter.hasNext();) { + final Map.Entry e = (Map.Entry) iter.next(); + + if (nsUris.contains(e.getValue())) { + final String prefix = (String) e.getKey(); + final String nsUri = (String) e.getValue(); + final String nsAttrName = "".equals(prefix) ? "xmlns" : "xmlns:" + prefix; + + context.setAttributeNS(XMLNamespaceConstants.XMLNS_NS_URI, nsAttrName, nsUri); + } + } + } + } + + /** + * Collect all the namespace URIs used in the subtree of a given element. + * + * @param context The element that should be searched for namespace URIs. + * @return All namespace URIs used in the subtree of context, including the ones used + * in context itself. + */ + public static Set collectNamespaceUris(final Element context) { + final Set result = new HashSet(); + + collectNamespaceUrisImpl(context, result); + return result; + } + + /** + * A recursive method to do the work of collectNamespaceURIs. + * + * @param context The context element to evaluate. + * @param result The result, passed as a parameter to avoid unnecessary instantiations of + * Set. + */ + private static void collectNamespaceUrisImpl(final Element context, final Set result) { + final NamedNodeMap attrs = context.getAttributes(); + final NodeList childNodes = context.getChildNodes(); + String nsUri; + int i; + + // add the namespace of the context element + nsUri = context.getNamespaceURI(); + if (nsUri != null && nsUri != XMLNamespaceConstants.XMLNS_NS_URI) { + result.add(nsUri); + } + + // add all namespace URIs from attributes + for (i = 0; i < attrs.getLength(); i++) { + nsUri = attrs.item(i).getNamespaceURI(); + if (nsUri != null && nsUri != XMLNamespaceConstants.XMLNS_NS_URI) { + result.add(nsUri); + } + } + + // add all namespaces from subelements + for (i = 0; i < childNodes.getLength(); i++) { + final Node node = childNodes.item(i); + + if (node.getNodeType() == Node.ELEMENT_NODE) { + collectNamespaceUrisImpl((Element) node, result); + } + } + } + + /** + * Check, that each attribute node in the given NodeList has its parent in the + * NodeList as well. + * + * @param nodes The NodeList to check. + * @return true, if each attribute node in nodes has its parent in + * nodes as well. + */ + public static boolean checkAttributeParentsInNodeList(final NodeList nodes) { + final Set nodeSet = new HashSet(); + int i; + + // put the nodes into the nodeSet + for (i = 0; i < nodes.getLength(); i++) { + nodeSet.add(nodes.item(i)); + } + + // check that each attribute node's parent is in the node list + for (i = 0; i < nodes.getLength(); i++) { + final Node n = nodes.item(i); + + if (n.getNodeType() == Node.ATTRIBUTE_NODE) { + final Attr attr = (Attr) n; + final Element owner = attr.getOwnerElement(); + + if (owner == null) { + if (!isNamespaceDeclaration(attr)) { + return false; + } + } + + if (!nodeSet.contains(owner) && !isNamespaceDeclaration(attr)) { + return false; + } + } + } + + return true; + } + + /** + * Convert an unstructured NodeList into a DocumentFragment. + * + * @param nodeList Contains the node list to be converted into a DOM DocumentFragment. + * @return the resulting DocumentFragment. The DocumentFragment will be backed by a new DOM + * Document, i.e. all noded of the node list will be cloned. + * @throws ParserConfigurationException An error occurred creating the DocumentFragment. + * @precondition The nodes in the node list appear in document order + * @precondition for each Attr node in the node list, the owning Element is in the node list as + * well. + * @precondition each Element or Attr node in the node list is namespace aware. + */ + public static DocumentFragment nodeList2DocumentFragment(final NodeList nodeList) + throws ParserConfigurationException { + + final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + final Document doc = builder.newDocument(); + final DocumentFragment result = doc.createDocumentFragment(); + + if (null == nodeList || nodeList.getLength() == 0) { + return result; + } + + int currPos = 0; + currPos = nodeList2DocumentFragment(nodeList, currPos, result, null, null) + 1; + + while (currPos < nodeList.getLength()) { + currPos = nodeList2DocumentFragment(nodeList, currPos, result, null, null) + 1; + } + return result; + } + + /** + * Helper method for the nodeList2DocumentFragment. + * + * @param nodeList The NodeList to convert. + * @param currPos The current position in the nodeList. + * @param result The resulting DocumentFragment. + * @param currOrgElem The current original element. + * @param currClonedElem The current cloned element. + * @return The current position. + */ + private static int nodeList2DocumentFragment(final NodeList nodeList, int currPos, + final DocumentFragment result, Element currOrgElem, Element currClonedElem) { + + while (currPos < nodeList.getLength()) { + final Node currentNode = nodeList.item(currPos); + switch (currentNode.getNodeType()) { + case Node.COMMENT_NODE: + case Node.PROCESSING_INSTRUCTION_NODE: + case Node.TEXT_NODE: { + // Append current node either to resulting DocumentFragment or to + // current cloned Element + if (null == currClonedElem) { + result.appendChild(result.getOwnerDocument().importNode(currentNode, false)); + } else { + // Stop processing if current Node is not a descendant of + // current Element + if (!isAncestor(currOrgElem, currentNode)) { + return --currPos; + } + + currClonedElem.appendChild(result.getOwnerDocument().importNode(currentNode, false)); + } + break; + } + + case Node.ELEMENT_NODE: { + final Element nextCurrOrgElem = (Element) currentNode; + final Element nextCurrClonedElem = result.getOwnerDocument() + .createElementNS(nextCurrOrgElem.getNamespaceURI(), nextCurrOrgElem.getNodeName()); + + // Append current Node either to resulting DocumentFragment or to + // current cloned Element + if (null == currClonedElem) { + result.appendChild(nextCurrClonedElem); + currOrgElem = nextCurrOrgElem; + currClonedElem = nextCurrClonedElem; + } else { + // Stop processing if current Node is not a descendant of + // current Element + if (!isAncestor(currOrgElem, currentNode)) { + return --currPos; + } + + currClonedElem.appendChild(nextCurrClonedElem); + } + + // Process current Node (of type Element) recursively + currPos = nodeList2DocumentFragment(nodeList, ++currPos, result, nextCurrOrgElem, + nextCurrClonedElem); + + break; + } + + case Node.ATTRIBUTE_NODE: { + final Attr currAttr = (Attr) currentNode; + + // GK 20030411: Hack to overcome problems with IAIK IXSIL + if (currAttr.getOwnerElement() == null) { + break; + } + if (currClonedElem == null) { + break; + } + + // currClonedElem must be the owner Element of currAttr if + // preconditions are met + currClonedElem.setAttributeNS(currAttr.getNamespaceURI(), currAttr.getNodeName(), + currAttr.getValue()); + break; + } + + default: { + // All other nodes will be ignored + } + } + + currPos++; + } + + return currPos; + } + + /** + * Check, if the given attribute is a namespace declaration. + * + * @param attr The attribute to check. + * @return true, if the attribute is a namespace declaration, false + * otherwise. + */ + private static boolean isNamespaceDeclaration(final Attr attr) { + return XMLNamespaceConstants.XMLNS_NS_URI.equals(attr.getNamespaceURI()); + } + + /** + * Check, if a given DOM element is an ancestor of a given node. + * + * @param candAnc The DOM element to check for being the ancestor. + * @param cand The node to check for being the child. + * @return true, if candAnc is an (indirect) ancestor of + * cand; false otherwise. + */ + public static boolean isAncestor(final Element candAnc, final Node cand) { + Node currPar = cand.getParentNode(); + + while (currPar != null) { + if (candAnc == currPar) { + return true; + } + currPar = currPar.getParentNode(); + } + return false; + } + + /** + * Selects the (first) element from a node list and returns it. + * + * @param nl The NodeList to get the element from. + * @return The (first) element included in the node list or null if the node list is + * null or empty or no element is included in the list. + */ + public static Element getElementFromNodeList(final NodeList nl) { + if ((nl == null) || (nl.getLength() == 0)) { + return null; + } + for (int i = 0; i < nl.getLength(); i++) { + final Node node = nl.item(i); + if (node.getNodeType() == Node.ELEMENT_NODE) { + return (Element) node; + } + } + return null; + } + + /** + * Returns all child elements of the given element. + * + * @param parent The element to get the child elements from. + * + * @return A list including all child elements of the given element. Maybe empty if the parent + * element has no child elements. + */ + public static List getChildElements(final Element parent) { + final Vector v = new Vector(); + final NodeList nl = parent.getChildNodes(); + final int length = nl.getLength(); + for (int i = 0; i < length; i++) { + final Node node = nl.item(i); + if (node.getNodeType() == Node.ELEMENT_NODE) { + v.add(node); + } + } + return v; + } + + /** + * Returns a byte array from given node. + * + * @param node Element node + * @return transformed node + * @throws TransformerException in case of an error + */ + public static byte[] nodeToByteArray(final Node node) throws TransformerException { + final Source source = new DOMSource(node); + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + // StringWriter stringWriter = new StringWriter(); + final Result result = new StreamResult(out); + final TransformerFactory factory = TransformerFactory.newInstance(); + final Transformer transformer = factory.newTransformer(); + transformer.transform(source, result); + return out.toByteArray(); + } + + +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/utils/EAAFDomEntityResolver.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/utils/EAAFDomEntityResolver.java deleted file mode 100644 index 5be0a475..00000000 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/utils/EAAFDomEntityResolver.java +++ /dev/null @@ -1,128 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ - - -package at.gv.egiz.eaaf.core.impl.utils; - -import java.io.InputStream; - -import org.apache.xerces.util.URI; -import org.apache.xerces.util.URI.MalformedURIException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.xml.sax.EntityResolver; -import org.xml.sax.InputSource; - -import at.gv.egiz.eaaf.core.api.data.XMLNamespaceConstants; - -/** - * An EntityResolver that looks up entities stored as - * local resources. - * - *

The following DTDs are mapped to local resources: - *

    - *
  • The XMLSchema.dtd
  • - *
  • The datatypes.dtd
  • - *
- *

- *

For all other resources, an attempt is made to resolve them as resources, - * either absolute or relative to Constants.SCHEMA_ROOT. - * - */ -public class EAAFDomEntityResolver implements EntityResolver { - private static final Logger log = LoggerFactory.getLogger(EAAFDomEntityResolver.class); - - /** - * Resolve an entity. - * - * The systemId parameter is used to perform the lookup of the - * entity as a resource, either by interpreting the systemId as - * an absolute resource path, or by appending the last path component of - * systemId to Constants.SCHEMA_ROOT. - * - * @param publicId The public ID of the resource. - * @param systemId The system ID of the resource. - * @return An InputSource from which the entity can be read, or - * null, if the entity could not be found. - * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String) - */ - public InputSource resolveEntity(String publicId, String systemId) { - InputStream stream; - int slashPos; - - if (publicId != null) { - // check if we can resolve some standard dtd's - if (publicId.equalsIgnoreCase("-//W3C//DTD XMLSchema 200102//EN")) { - return new InputSource( - getClass().getResourceAsStream( - XMLNamespaceConstants.SCHEMA_ROOT + "XMLSchema.dtd")); - } else if (publicId.equalsIgnoreCase("datatypes")) { - return new InputSource( - getClass().getResourceAsStream( - XMLNamespaceConstants.SCHEMA_ROOT + "datatypes.dtd")); - } - } else if (systemId != null) { - // get the URI path - try { - URI uri = new URI(systemId); - systemId = uri.getPath(); - - if (!"file".equals(uri.getScheme()) || "".equals(systemId.trim())) { - return null; - } - - } catch (MalformedURIException e) { - return null; - } - - // try to get the resource from the full path - stream = getClass().getResourceAsStream(systemId); - if (stream != null) { - InputSource source = new InputSource(stream); - - source.setSystemId(systemId); - return source; - } - - // try to get the resource from the last path component - slashPos = systemId.lastIndexOf('/'); - if (slashPos >= 0 && systemId.length() > slashPos) { - systemId = systemId.substring(slashPos + 1, systemId.length()); - stream = - getClass().getResourceAsStream(XMLNamespaceConstants.SCHEMA_ROOT + systemId); - if (stream != null) { - InputSource source = new InputSource(stream); - - source.setSystemId(systemId); - return source; - } - } - } - - return null; // nothing found - let the parser handle the entity - } -} \ No newline at end of file diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/utils/EaafDomEntityResolver.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/utils/EaafDomEntityResolver.java new file mode 100644 index 00000000..c2700214 --- /dev/null +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/utils/EaafDomEntityResolver.java @@ -0,0 +1,118 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + + + +package at.gv.egiz.eaaf.core.impl.utils; + +import java.io.InputStream; +import at.gv.egiz.eaaf.core.api.data.XMLNamespaceConstants; +import org.apache.xerces.util.URI; +import org.apache.xerces.util.URI.MalformedURIException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.xml.sax.EntityResolver; +import org.xml.sax.InputSource; + +/** + * An EntityResolver that looks up entities stored as local resources. + * + *

+ * The following DTDs are mapped to local resources: + *

    + *
  • The XMLSchema.dtd
  • + *
  • The datatypes.dtd
  • + *
+ *

+ *

+ * For all other resources, an attempt is made to resolve them as resources, either absolute or + * relative to Constants.SCHEMA_ROOT. + * + */ +public class EaafDomEntityResolver implements EntityResolver { + private static final Logger log = LoggerFactory.getLogger(EaafDomEntityResolver.class); + + /** + * Resolve an entity. + *

+ * The systemId parameter is used to perform the lookup of the entity as a resource, + * either by interpreting the systemId as an absolute resource path, or by appending + * the last path component of systemId to Constants.SCHEMA_ROOT. + *

+ * + * @param publicId The public ID of the resource. + * @param systemId The system ID of the resource. + * @return An InputSource from which the entity can be read, or null, if + * the entity could not be found. + * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String) + */ + @Override + public InputSource resolveEntity(final String publicId, String systemId) { + InputStream stream; + int slashPos; + + if (publicId != null) { + // check if we can resolve some standard dtd's + if (publicId.equalsIgnoreCase("-//W3C//DTD XMLSchema 200102//EN")) { + return new InputSource( + getClass().getResourceAsStream(XMLNamespaceConstants.SCHEMA_ROOT + "XMLSchema.dtd")); + } else if (publicId.equalsIgnoreCase("datatypes")) { + return new InputSource( + getClass().getResourceAsStream(XMLNamespaceConstants.SCHEMA_ROOT + "datatypes.dtd")); + } + } else if (systemId != null) { + // get the URI path + try { + final URI uri = new URI(systemId); + systemId = uri.getPath(); + + if (!"file".equals(uri.getScheme()) || "".equals(systemId.trim())) { + return null; + } + + } catch (final MalformedURIException e) { + return null; + } + + // try to get the resource from the full path + stream = getClass().getResourceAsStream(systemId); + if (stream != null) { + final InputSource source = new InputSource(stream); + + source.setSystemId(systemId); + return source; + } + + // try to get the resource from the last path component + slashPos = systemId.lastIndexOf('/'); + if (slashPos >= 0 && systemId.length() > slashPos) { + systemId = systemId.substring(slashPos + 1, systemId.length()); + stream = getClass().getResourceAsStream(XMLNamespaceConstants.SCHEMA_ROOT + systemId); + if (stream != null) { + final InputSource source = new InputSource(stream); + + source.setSystemId(systemId); + return source; + } + } + } + + return null; // nothing found - let the parser handle the entity + } +} diff --git a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/utils/XPathUtils.java b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/utils/XPathUtils.java index c50b9e08..d6745c78 100644 --- a/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/utils/XPathUtils.java +++ b/eaaf_core/src/main/java/at/gv/egiz/eaaf/core/impl/utils/XPathUtils.java @@ -1,36 +1,30 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.utils; import java.util.List; import java.util.Map; - +import at.gv.egiz.eaaf.core.api.data.XMLNamespaceConstants; +import at.gv.egiz.eaaf.core.exceptions.XPathException; import org.jaxen.JaxenException; import org.jaxen.NamespaceContext; import org.jaxen.Navigator; @@ -43,35 +37,31 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.traversal.NodeIterator; -import at.gv.egiz.eaaf.core.api.data.XMLNamespaceConstants; -import at.gv.egiz.eaaf.core.exceptions.XPathException; - /** * Utility methods to evaluate XPath expressions on DOM nodes. - * + * * @author Patrick Peck * @version $Id$ */ public class XPathUtils { /** - * The XPath expression selecting all nodes under a given root (including the - * root node itself). + * The XPath expression selecting all nodes under a given root (including the root node itself). */ - public static final String ALL_NODES_XPATH = - "(.//. | .//@* | .//namespace::*)"; + public static final String ALL_NODES_XPATH = "(.//. | .//@* | .//namespace::*)"; /** The DocumentNavigator to use for navigating the document. */ - private static Navigator documentNavigator = - DocumentNavigator.getInstance(); + private static Navigator documentNavigator = DocumentNavigator.getInstance(); /** The default namespace prefix to namespace URI mappings. */ private static NamespaceContext NS_CONTEXT; - - static { - SimpleNamespaceContext ctx = new SimpleNamespaceContext(); + + static { + final SimpleNamespaceContext ctx = new SimpleNamespaceContext(); ctx.addNamespace(XMLNamespaceConstants.MOA_PREFIX, XMLNamespaceConstants.MOA_NS_URI); - ctx.addNamespace(XMLNamespaceConstants.MOA_CONFIG_PREFIX, XMLNamespaceConstants.MOA_CONFIG_NS_URI); - ctx.addNamespace(XMLNamespaceConstants.MOA_ID_CONFIG_PREFIX, XMLNamespaceConstants.MOA_ID_CONFIG_NS_URI); + ctx.addNamespace(XMLNamespaceConstants.MOA_CONFIG_PREFIX, + XMLNamespaceConstants.MOA_CONFIG_NS_URI); + ctx.addNamespace(XMLNamespaceConstants.MOA_ID_CONFIG_PREFIX, + XMLNamespaceConstants.MOA_ID_CONFIG_NS_URI); ctx.addNamespace(XMLNamespaceConstants.SL10_PREFIX, XMLNamespaceConstants.SL10_NS_URI); ctx.addNamespace(XMLNamespaceConstants.SL11_PREFIX, XMLNamespaceConstants.SL11_NS_URI); ctx.addNamespace(XMLNamespaceConstants.SL12_PREFIX, XMLNamespaceConstants.SL12_NS_URI); @@ -82,7 +72,8 @@ public class XPathUtils { ctx.addNamespace(XMLNamespaceConstants.DSIG_PREFIX, XMLNamespaceConstants.DSIG_NS_URI); ctx.addNamespace(XMLNamespaceConstants.XSLT_PREFIX, XMLNamespaceConstants.XSLT_NS_URI); ctx.addNamespace(XMLNamespaceConstants.XSI_PREFIX, XMLNamespaceConstants.XSI_NS_URI); - ctx.addNamespace(XMLNamespaceConstants.DSIG_FILTER2_PREFIX, XMLNamespaceConstants.DSIG_FILTER2_NS_URI); + ctx.addNamespace(XMLNamespaceConstants.DSIG_FILTER2_PREFIX, + XMLNamespaceConstants.DSIG_FILTER2_NS_URI); ctx.addNamespace(XMLNamespaceConstants.DSIG_EC_PREFIX, XMLNamespaceConstants.DSIG_EC_NS_URI); ctx.addNamespace(XMLNamespaceConstants.MD_PREFIX, XMLNamespaceConstants.MD_NS_URI); ctx.addNamespace(XMLNamespaceConstants.MDP_PREFIX, XMLNamespaceConstants.MDP_NS_URI); @@ -94,452 +85,398 @@ public class XPathUtils { ctx.addNamespace(XMLNamespaceConstants.SAML2_PREFIX, XMLNamespaceConstants.SAML2_NS_URI); ctx.addNamespace(XMLNamespaceConstants.SAML2P_PREFIX, XMLNamespaceConstants.SAML2P_NS_URI); ctx.addNamespace(XMLNamespaceConstants.XENC_PREFIX, XMLNamespaceConstants.XENC_NS_URI); - ctx.addNamespace(XMLNamespaceConstants.XADES_1_1_1_NS_PREFIX, XMLNamespaceConstants.XADES_1_1_1_NS_URI); + ctx.addNamespace(XMLNamespaceConstants.XADES_1_1_1_NS_PREFIX, + XMLNamespaceConstants.XADES_1_1_1_NS_URI); NS_CONTEXT = ctx; } /** - * Return a NodeIterator over the nodes matching the XPath - * expression. - * - * All namespace URIs and prefixes declared in the Constants - * interface are used for resolving namespaces. - * - * @param contextNode The root node from which to evaluate the XPath - * expression. + * Return a NodeIterator over the nodes matching the XPath expression. + * + *

+ * All namespace URIs and prefixes declared in the Constants interface are used for + * resolving namespaces. + *

+ * + * @param contextNode The root node from which to evaluate the XPath expression. * @param exp The XPath expression to evaluate. * @return An iterator over the resulting nodes. * @throws XPathException An error occurred evaluating the XPath expression. */ - public static NodeIterator selectNodeIterator(Node contextNode, String exp) - throws XPathException { + public static NodeIterator selectNodeIterator(final Node contextNode, final String exp) + throws XPathException { return selectNodeIterator(contextNode, NS_CONTEXT, exp); } /** - * Return a NodeIterator over the nodes matching the XPath - * expression. - * - * @param contextNode The root node from which to evaluate the XPath - * expression. - * @param namespaceElement An element from which to build the - * namespace mapping for evaluating the XPath expression + * Return a NodeIterator over the nodes matching the XPath expression. + * + * @param contextNode The root node from which to evaluate the XPath expression. + * @param namespaceElement An element from which to build the namespace mapping for evaluating the + * XPath expression * @param exp The XPath expression to evaluate. * @return An iterator over the resulting nodes. * @throws XPathException An error occurred evaluating the XPath expression. */ - public static NodeIterator selectNodeIterator( - Node contextNode, - Element namespaceElement, - String exp) - throws XPathException { + public static NodeIterator selectNodeIterator(final Node contextNode, + final Element namespaceElement, final String exp) throws XPathException { try { - SimpleNamespaceContext ctx = new SimpleNamespaceContext(); + final SimpleNamespaceContext ctx = new SimpleNamespaceContext(); ctx.addElementNamespaces(documentNavigator, namespaceElement); return selectNodeIterator(contextNode, ctx, exp); - - } catch (JaxenException e) { - throw new XPathException("XPath operation FAILED. Reason: " + e.getMessage(), e); - + + } catch (final JaxenException e) { + throw new XPathException("XPath operation FAILED. Reason: " + e.getMessage(), e); + } } /** - * Return a NodeIterator over the nodes matching the XPath - * expression. - * - * @param contextNode The root node from which to evaluate the XPath - * expression. - * @param namespaceMapping A namespace prefix to namespace URI mapping - * (String to String) for evaluating the XPath - * expression. + * Return a NodeIterator over the nodes matching the XPath expression. + * + * @param contextNode The root node from which to evaluate the XPath expression. + * @param namespaceMapping A namespace prefix to namespace URI mapping (String to + * String) for evaluating the XPath expression. * @param exp The XPath expression to evaluate. * @return An iterator over the resulting nodes. * @throws XPathException An error occurred evaluating the XPath expression. */ - public static NodeIterator selectNodeIterator( - Node contextNode, - Map namespaceMapping, - String exp) - throws XPathException { + public static NodeIterator selectNodeIterator(final Node contextNode, final Map namespaceMapping, + final String exp) throws XPathException { - SimpleNamespaceContext ctx = new SimpleNamespaceContext(namespaceMapping); + final SimpleNamespaceContext ctx = new SimpleNamespaceContext(namespaceMapping); return selectNodeIterator(contextNode, ctx, exp); } /** - * Return a NodeIterator over the nodes matching the XPath - * expression. - * - * @param contextNode The root node from which to evaluate the XPath - * expression. - * @param nsContext The NamespaceContext for resolving namespace - * prefixes to namespace URIs for evaluating the XPath expression. + * Return a NodeIterator over the nodes matching the XPath expression. + * + * @param contextNode The root node from which to evaluate the XPath expression. + * @param nsContext The NamespaceContext for resolving namespace prefixes to + * namespace URIs for evaluating the XPath expression. * @param exp The XPath expression to evaluate. * @return An iterator over the resulting nodes. * @throws XPathException An error occurred evaluating the XPath expression. */ - private static NodeIterator selectNodeIterator( - Node contextNode, - NamespaceContext nsContext, - String exp) - throws XPathException { + private static NodeIterator selectNodeIterator(final Node contextNode, + final NamespaceContext nsContext, final String exp) throws XPathException { try { - DOMXPath xpath = new DOMXPath(exp); + final DOMXPath xpath = new DOMXPath(exp); List nodes; xpath.setNamespaceContext(nsContext); nodes = xpath.selectNodes(contextNode); return new NodeIteratorAdapter(nodes.listIterator()); - - } catch (JaxenException e) { - throw new XPathException("XPath operation FAILED. Reason: " + e.getMessage(), e); - + + } catch (final JaxenException e) { + throw new XPathException("XPath operation FAILED. Reason: " + e.getMessage(), e); + } } /** - * Return a NodeList of all the nodes matching the XPath - * expression. - * - * All namespace URIs and prefixes declared in the Constants - * interface are used for resolving namespaces. - * - * @param contextNode The root node from which to evaluate the XPath - * expression. + * Return a NodeList of all the nodes matching the XPath expression. + *

+ * All namespace URIs and prefixes declared in the Constants interface are used for + * resolving namespaces. + *

+ * @param contextNode The root node from which to evaluate the XPath expression. * @param exp The XPath expression to evaluate. * @return A NodeList containing the matching nodes. * @throws XPathException An error occurred evaluating the XPath expression. */ - public static NodeList selectNodeList(Node contextNode, String exp) - throws XPathException { + public static NodeList selectNodeList(final Node contextNode, final String exp) + throws XPathException { return selectNodeList(contextNode, NS_CONTEXT, exp); } /** - * Return a NodeList of all the nodes matching the XPath - * expression. - * - * @param contextNode The root node from which to evaluate the XPath - * expression. - * @param namespaceElement An element from which to build the - * namespace mapping for evaluating the XPath expression + * Return a NodeList of all the nodes matching the XPath expression. + * + * @param contextNode The root node from which to evaluate the XPath expression. + * @param namespaceElement An element from which to build the namespace mapping for evaluating the + * XPath expression * @param exp The XPath expression to evaluate. * @return A NodeList containing the matching nodes. * @throws XPathException An error occurred evaluating the XPath expression. */ - public static NodeList selectNodeList( - Node contextNode, - Element namespaceElement, - String exp) - throws XPathException { + public static NodeList selectNodeList(final Node contextNode, final Element namespaceElement, + final String exp) throws XPathException { try { - SimpleNamespaceContext ctx = new SimpleNamespaceContext(); + final SimpleNamespaceContext ctx = new SimpleNamespaceContext(); ctx.addElementNamespaces(documentNavigator, namespaceElement); return selectNodeList(contextNode, ctx, exp); - - } catch (JaxenException e) { - throw new XPathException("XPath operation FAILED. Reason: " + e.getMessage(), e); - + + } catch (final JaxenException e) { + throw new XPathException("XPath operation FAILED. Reason: " + e.getMessage(), e); + } } /** - * Return a NodeList of all the nodes matching the XPath - * expression. - * - * @param contextNode The root node from which to evaluate the XPath - * expression. - * @param namespaceMapping A namespace prefix to namespace URI mapping - * (String to String) for evaluating the XPath - * expression. + * Return a NodeList of all the nodes matching the XPath expression. + * + * @param contextNode The root node from which to evaluate the XPath expression. + * @param namespaceMapping A namespace prefix to namespace URI mapping (String to + * String) for evaluating the XPath expression. * @param exp The XPath expression to evaluate. * @return A NodeList containing the matching nodes. * @throws XPathException An error occurred evaluating the XPath expression. */ - public static NodeList selectNodeList( - Node contextNode, - Map namespaceMapping, - String exp) - throws XPathException { + public static NodeList selectNodeList(final Node contextNode, final Map namespaceMapping, + final String exp) throws XPathException { - SimpleNamespaceContext ctx = new SimpleNamespaceContext(namespaceMapping); + final SimpleNamespaceContext ctx = new SimpleNamespaceContext(namespaceMapping); return selectNodeList(contextNode, ctx, exp); } /** - * Return a NodeList of all the nodes matching the XPath - * expression. - * - * @param contextNode The root node from which to evaluate the XPath - * expression. - * @param nsContext The NamespaceContext for resolving namespace - * prefixes to namespace URIs for evaluating the XPath expression. + * Return a NodeList of all the nodes matching the XPath expression. + * + * @param contextNode The root node from which to evaluate the XPath expression. + * @param nsContext The NamespaceContext for resolving namespace prefixes to + * namespace URIs for evaluating the XPath expression. * @param exp The XPath expression to evaluate. * @return A NodeList containing the matching nodes. * @throws XPathException An error occurred evaluating the XPath expression. */ - private static NodeList selectNodeList(Node contextNode, NamespaceContext nsContext, String exp) throws XPathException { - try { - DOMXPath xpath = new DOMXPath(exp); - List nodes; - xpath.setNamespaceContext(nsContext); - nodes = xpath.selectNodes(contextNode); - return new NodeListAdapter(nodes); - - } catch (JaxenException e) { - throw new XPathException("XPath operation FAILED. Reason: " + e.getMessage(), e); - - } + private static NodeList selectNodeList(final Node contextNode, final NamespaceContext nsContext, + final String exp) throws XPathException { + try { + final DOMXPath xpath = new DOMXPath(exp); + List nodes; + xpath.setNamespaceContext(nsContext); + nodes = xpath.selectNodes(contextNode); + return new NodeListAdapter(nodes); + + } catch (final JaxenException e) { + throw new XPathException("XPath operation FAILED. Reason: " + e.getMessage(), e); + + } } /** * Select the first node matching an XPath expression. - * - * All namespace URIs and prefixes declared in the Constants - * interface are used for resolving namespaces. - * - * @param contextNode The root node from which to evaluate the XPath - * expression. + *

+ * All namespace URIs and prefixes declared in the Constants interface are used for + * resolving namespaces. + *

+ * @param contextNode The root node from which to evaluate the XPath expression. * @param exp The XPath expression to evaluate. - * @return Node The first node matching the XPath expression, or - * null, if no node matched. + * @return Node The first node matching the XPath expression, or null, if no node + * matched. * @throws XPathException An error occurred evaluating the XPath expression. */ - public static Node selectSingleNode(Node contextNode, String exp) - throws XPathException { + public static Node selectSingleNode(final Node contextNode, final String exp) + throws XPathException { return selectSingleNode(contextNode, NS_CONTEXT, exp); } /** * Select the first node matching an XPath expression. - * - * @param contextNode The root node from which to evaluate the XPath - * expression. - * @param namespaceElement An element from which to build the - * namespace mapping for evaluating the XPath expression + * + * @param contextNode The root node from which to evaluate the XPath expression. + * @param namespaceElement An element from which to build the namespace mapping for evaluating the + * XPath expression * @param exp The XPath expression to evaluate. - * @return Node The first node matching the XPath expression, or - * null, if no node matched. + * @return Node The first node matching the XPath expression, or null, if no node + * matched. * @throws XPathException An error occurred evaluating the XPath expression. */ - public static Node selectSingleNode( - Node contextNode, - Element namespaceElement, - String exp) - throws XPathException { + public static Node selectSingleNode(final Node contextNode, final Element namespaceElement, + final String exp) throws XPathException { try { - SimpleNamespaceContext ctx = new SimpleNamespaceContext(); + final SimpleNamespaceContext ctx = new SimpleNamespaceContext(); ctx.addElementNamespaces(documentNavigator, namespaceElement); return selectSingleNode(contextNode, ctx, exp); - - } catch (JaxenException e) { - throw new XPathException("XPath operation FAILED. Reason: " + e.getMessage(), e); - + + } catch (final JaxenException e) { + throw new XPathException("XPath operation FAILED. Reason: " + e.getMessage(), e); + } } /** * Select the first node matching an XPath expression. - * - * @param contextNode The root node from which to evaluate the XPath - * expression. - * @param namespaceMapping A namespace prefix to namespace URI mapping - * (String to String) for evaluating the XPath - * expression. + * + * @param contextNode The root node from which to evaluate the XPath expression. + * @param namespaceMapping A namespace prefix to namespace URI mapping (String to + * String) for evaluating the XPath expression. * @param exp The XPath expression to evaluate. - * @return Node The first node matching the XPath expression, or - * null, if no node matched. + * @return Node The first node matching the XPath expression, or null, if no node + * matched. * @throws XPathException An error occurred evaluating the XPath expression. */ - public static Node selectSingleNode( - Node contextNode, - Map namespaceMapping, - String exp) - throws XPathException { + public static Node selectSingleNode(final Node contextNode, final Map namespaceMapping, + final String exp) throws XPathException { - SimpleNamespaceContext ctx = new SimpleNamespaceContext(namespaceMapping); + final SimpleNamespaceContext ctx = new SimpleNamespaceContext(namespaceMapping); return selectSingleNode(contextNode, ctx, exp); } /** * Select the first node matching an XPath expression. - * - * @param contextNode The root node from which to evaluate the XPath - * expression. - * @param nsContext The NamespaceContext for resolving namespace - * prefixes to namespace URIs for evaluating the XPath expression. + * + * @param contextNode The root node from which to evaluate the XPath expression. + * @param nsContext The NamespaceContext for resolving namespace prefixes to + * namespace URIs for evaluating the XPath expression. * @param exp The XPath expression to evaluate. - * @return Node The first node matching the XPath expression, or - * null, if no node matched. + * @return Node The first node matching the XPath expression, or null, if no node + * matched. * @throws XPathException An error occurred evaluating the XPath expression. */ - public static Node selectSingleNode( - Node contextNode, - NamespaceContext nsContext, - String exp) - throws XPathException { + public static Node selectSingleNode(final Node contextNode, final NamespaceContext nsContext, + final String exp) throws XPathException { try { - DOMXPath xpath = new DOMXPath(exp); + final DOMXPath xpath = new DOMXPath(exp); xpath.setNamespaceContext(nsContext); return (Node) xpath.selectSingleNode(contextNode); - - } catch (JaxenException e) { - throw new XPathException("XPath operation FAILED. Reason: " + e.getMessage(), e); - + + } catch (final JaxenException e) { + throw new XPathException("XPath operation FAILED. Reason: " + e.getMessage(), e); + } } /** - * Return the value of a DOM element whose location is given by an XPath - * expression. - * + * Return the value of a DOM element whose location is given by an XPath expression. + * * @param root The root element from which to evaluate the XPath. - * @param xpath The XPath expression pointing to the element whose value - * to return. - * @param def The default value to return, if no element can be found using - * the given xpath. - * @return The element value, if it can be located using the - * xpath. Otherwise, def is returned. + * @param xpath The XPath expression pointing to the element whose value to return. + * @param def The default value to return, if no element can be found using the given + * xpath. + * @return The element value, if it can be located using the xpath. Otherwise, + * def is returned. */ - public static String getElementValue( - Element root, - String xpath, - String def) { + public static String getElementValue(final Element root, final String xpath, final String def) { - Element elem = (Element) XPathUtils.selectSingleNode(root, xpath); - return elem != null ? DOMUtils.getText(elem) : def; + final Element elem = (Element) XPathUtils.selectSingleNode(root, xpath); + return elem != null ? DomUtils.getText(elem) : def; } /** - * Return the value of a DOM attribute whose location is given by an XPath - * expression. - * + * Return the value of a DOM attribute whose location is given by an XPath expression. + * * @param root The root element from which to evaluate the XPath. - * @param xpath The XPath expression pointing to the attribute whose value to - * return. - * @param def The default value to return, if no attribute can be found using - * the given xpath. - * @return The element value, if it can be located using the - * xpath. Otherwise, def is returned. + * @param xpath The XPath expression pointing to the attribute whose value to return. + * @param def The default value to return, if no attribute can be found using the given + * xpath. + * @return The element value, if it can be located using the xpath. Otherwise, + * def is returned. */ - public static String getAttributeValue( - Element root, - String xpath, - String def) { + public static String getAttributeValue(final Element root, final String xpath, final String def) { - Attr attr = (Attr) XPathUtils.selectSingleNode(root, xpath); + final Attr attr = (Attr) XPathUtils.selectSingleNode(root, xpath); return attr != null ? attr.getValue() : def; } - + /** - * Returns the namespace prefix used within XPathUtils for referring to - * the namespace of the specified (Security Layer command) element. - * - * This namespace prefix can be used in various XPath expression evaluation methods - * within XPathUtils without explicitely binding it to the particular - * namespace. - * - * @param contextElement The (Security Layer command) element. - * - * @return the namespace prefix used within XPathUtils for referring to - * the namespace of the specified (Security Layer command) element. - * - * throws XpathException If the specified element has a namespace other than the ones - * known by this implementation as valid Security Layer namespaces (cf. - * @link Constants#SL10_NS_URI, @link Constants#SL11_NS_URI, @link Constants#SL12_NS_URI). + * Returns the namespace prefix used within XPathUtils for referring to the namespace + * of the specified (Security Layer command) element. + *

+ * This namespace prefix can be used in various XPath expression evaluation methods within + * XPathUtils without explicitely binding it to the particular namespace. + *

+ * @param contextElement The (Security Layer command) element. + * + * @return the namespace prefix used within XPathUtils for referring to the namespace + * of the specified (Security Layer command) element. + * + * throws XpathException If the specified element has a namespace other than the ones + * known by this implementation as valid Security Layer namespaces (cf. + * @link Constants#SL10_NS_URI, @link Constants#SL11_NS_URI, @link Constants#SL12_NS_URI). */ - public static String getSlPrefix (Element contextElement) throws XPathException - { - String sLNamespace = contextElement.getNamespaceURI(); - String sLPrefix = null; - - if (sLNamespace.equals(XMLNamespaceConstants.SL10_NS_URI)) - sLPrefix = XMLNamespaceConstants.SL10_PREFIX; - - else if (sLNamespace.equals(XMLNamespaceConstants.SL12_NS_URI)) - sLPrefix = XMLNamespaceConstants.SL12_PREFIX; - - else if (sLNamespace.equals(XMLNamespaceConstants.SL11_NS_URI)) - sLPrefix = XMLNamespaceConstants.SL11_PREFIX; - - else - throw new XPathException("XPath operation FAILED. Reason: "); - - return sLPrefix; + public static String getSlPrefix(final Element contextElement) throws XPathException { + final String sLNamespace = contextElement.getNamespaceURI(); + String slPrefix = null; + + if (sLNamespace.equals(XMLNamespaceConstants.SL10_NS_URI)) { + slPrefix = XMLNamespaceConstants.SL10_PREFIX; + } else if (sLNamespace.equals(XMLNamespaceConstants.SL12_NS_URI)) { + slPrefix = XMLNamespaceConstants.SL12_PREFIX; + } else if (sLNamespace.equals(XMLNamespaceConstants.SL11_NS_URI)) { + slPrefix = XMLNamespaceConstants.SL11_PREFIX; + } else { + throw new XPathException("XPath operation FAILED. Reason: "); + } + + return slPrefix; } - - + + /** - * Return the SecurityLayer namespace prefix of the context element. - * If the context element is not the element that lies within the - * SecurityLayer namespace. The Securitylayer namespace is derived from - * the xmlns:sl10, sl11 or sl - * attribute of the context element. - * + * Return the SecurityLayer namespace prefix of the context element. If the context element is not + * the element that lies within the SecurityLayer namespace. The Securitylayer namespace is + * derived from the xmlns:sl10, sl11 or sl attribute of the + * context element. + *

* The returned prefix is needed for evaluating XPATH expressions. - * - * @param contextElement The element to get a prefix for the Securitylayer namespace, - * that is used within the corresponding document. - * - * @return The string sl10, sl11 or sl, - * depending on the SecurityLayer namespace of the contextElement. - * - * throws XPathException If no (vlalid) SecurityLayer namespace prefix or namespace - * is defined. + *

+ * @param contextElement The element to get a prefix for the Securitylayer namespace, that is used + * within the corresponding document. + * + * @return The string sl10, sl11 or sl, depending on the + * SecurityLayer namespace of the contextElement. + * + * throws XPathException If no (vlalid) SecurityLayer namespace prefix or namespace is + * defined. */ - public static String getSlPrefixFromNoRoot (Element contextElement) throws XPathException { - - String slPrefix = checkSLnsDeclaration(contextElement, XMLNamespaceConstants.SL10_PREFIX, XMLNamespaceConstants.SL10_NS_URI); - if (slPrefix == null) - slPrefix = checkSLnsDeclaration(contextElement, XMLNamespaceConstants.SL11_PREFIX, XMLNamespaceConstants.SL11_NS_URI); - - if (slPrefix == null) - slPrefix = checkSLnsDeclaration(contextElement, XMLNamespaceConstants.SL12_PREFIX, XMLNamespaceConstants.SL12_NS_URI); - + public static String getSlPrefixFromNoRoot(final Element contextElement) throws XPathException { + + String slPrefix = checkSLnsDeclaration(contextElement, XMLNamespaceConstants.SL10_PREFIX, + XMLNamespaceConstants.SL10_NS_URI); + if (slPrefix == null) { + slPrefix = checkSLnsDeclaration(contextElement, XMLNamespaceConstants.SL11_PREFIX, + XMLNamespaceConstants.SL11_NS_URI); + } + + if (slPrefix == null) { + slPrefix = checkSLnsDeclaration(contextElement, XMLNamespaceConstants.SL12_PREFIX, + XMLNamespaceConstants.SL12_NS_URI); + } + return slPrefix; - + } - + /** - * Checks if the context element has an attribute xmlns:slPrefix and - * if the prefix of that attribute corresponds with a valid SecurityLayer namespace. - * - * @param contextElement The element to be checked. - * @param slPrefix The prefix which should be checked. Must be a valid SecurityLayer - * namespace prefix. - * @param slNameSpace The SecurityLayer namespace that corresponds to the specified prefix. - * - * @return The valid SecurityLayer prefix or null if this prefix is - * not used. - * @throws XPathException + * Checks if the context element has an attribute xmlns:slPrefix and if the prefix of + * that attribute corresponds with a valid SecurityLayer namespace. + * + * @param contextElement The element to be checked. + * @param slPrefix The prefix which should be checked. Must be a valid SecurityLayer namespace + * prefix. + * @param slNameSpace The SecurityLayer namespace that corresponds to the specified prefix. + * + * @return The valid SecurityLayer prefix or null if this prefix is not used. + * @throws XPathException In case of an error */ - private static String checkSLnsDeclaration(Element contextElement, String slPrefix, String slNameSpace) - throws XPathException - { - String nsAtt = "xmlns:" + slPrefix; - String nameSpace = contextElement.getAttribute(nsAtt); + private static String checkSLnsDeclaration(final Element contextElement, final String slPrefix, + final String slNameSpace) throws XPathException { + final String nsAtt = "xmlns:" + slPrefix; + final String nameSpace = contextElement.getAttribute(nsAtt); if (nameSpace == "") { return null; - + } else { // check if namespace is correct - if (nameSpace.equals(slNameSpace)) + if (nameSpace.equals(slNameSpace)) { return slPrefix; - else - throw new XPathException("Unknown Namespace declaration"); + } else { + throw new XPathException("Unknown Namespace declaration"); + } } } diff --git a/eaaf_core/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider b/eaaf_core/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider index d827c51f..c0f782cc 100644 --- a/eaaf_core/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider +++ b/eaaf_core/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider @@ -1 +1 @@ -at.gv.egiz.eaaf.core.impl.idp.EAAFCoreSpringResourceProvider \ No newline at end of file +at.gv.egiz.eaaf.core.impl.idp.EaafCoreSpringResourceProvider \ No newline at end of file diff --git a/eaaf_core/src/main/resources/META-INF/services/at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder b/eaaf_core/src/main/resources/META-INF/services/at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder index 7b977193..30f1cb57 100644 --- a/eaaf_core/src/main/resources/META-INF/services/at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder +++ b/eaaf_core/src/main/resources/META-INF/services/at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder @@ -1,15 +1,15 @@ at.gv.egiz.eaaf.core.impl.idp.builder.attributes.BirthdateAttributeBuilder -at.gv.egiz.eaaf.core.impl.idp.builder.attributes.EIDIssuingNationAttributeBuilder -at.gv.egiz.eaaf.core.impl.idp.builder.attributes.EIDSourcePIN -at.gv.egiz.eaaf.core.impl.idp.builder.attributes.EIDSourcePINType +at.gv.egiz.eaaf.core.impl.idp.builder.attributes.EidIssuingNationAttributeBuilder +at.gv.egiz.eaaf.core.impl.idp.builder.attributes.EidSourcePin +at.gv.egiz.eaaf.core.impl.idp.builder.attributes.EidSourcePinType at.gv.egiz.eaaf.core.impl.idp.builder.attributes.GivenNameAttributeBuilder at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PrincipalNameAttributeBuilder -at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PVPVersionAttributeBuilder -at.gv.egiz.eaaf.core.impl.idp.builder.attributes.EIDeIDASQAALevelAttributeBuilder -at.gv.egiz.eaaf.core.impl.idp.builder.attributes.BPKAttributeBuilder -at.gv.egiz.eaaf.core.impl.idp.builder.attributes.EIDSectorForIDAttributeBuilder -at.gv.egiz.eaaf.core.impl.idp.builder.attributes.EIDIdentityLinkBuilder -at.gv.egiz.eaaf.core.impl.idp.builder.attributes.EIDEIDTokenBuilder -at.gv.egiz.eaaf.core.impl.idp.builder.attributes.EIDSignerCertificate +at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PvpVersionAttributeBuilder +at.gv.egiz.eaaf.core.impl.idp.builder.attributes.EidEidasQaaLevelAttributeBuilder +at.gv.egiz.eaaf.core.impl.idp.builder.attributes.BpkAttributeBuilder +at.gv.egiz.eaaf.core.impl.idp.builder.attributes.EidSectorForIdAttributeBuilder +at.gv.egiz.eaaf.core.impl.idp.builder.attributes.EidIdentityLinkBuilder +at.gv.egiz.eaaf.core.impl.idp.builder.attributes.EidEidTokenBuilder +at.gv.egiz.eaaf.core.impl.idp.builder.attributes.EidSignerCertificate at.gv.egiz.eaaf.core.impl.idp.builder.attributes.EidIdentityStatusLevelAttributeBuiler -at.gv.egiz.eaaf.core.impl.idp.builder.attributes.EIDCcsURL \ No newline at end of file +at.gv.egiz.eaaf.core.impl.idp.builder.attributes.EidCcsUrl \ No newline at end of file diff --git a/eaaf_core/src/main/resources/eaaf_core.beans.xml b/eaaf_core/src/main/resources/eaaf_core.beans.xml index 27b0f381..288507cb 100644 --- a/eaaf_core/src/main/resources/eaaf_core.beans.xml +++ b/eaaf_core/src/main/resources/eaaf_core.beans.xml @@ -1,46 +1,49 @@ - + - - - - - - - - - - - - - - - - - - - - - - - - + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:context="http://www.springframework.org/schema/context" + xmlns:tx="http://www.springframework.org/schema/tx" + xmlns:aop="http://www.springframework.org/schema/aop" + xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd + http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/AuthenticationDataBuilderTest.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/AuthenticationDataBuilderTest.java index c4acbaad..586d464e 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/AuthenticationDataBuilderTest.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/AuthenticationDataBuilderTest.java @@ -3,7 +3,12 @@ package at.gv.egiz.eaaf.core.impl.idp.auth; import java.io.ByteArrayInputStream; import java.util.HashMap; import java.util.Map; - +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; +import at.gv.egiz.eaaf.core.impl.idp.auth.data.SimpleIdentityLinkAssertionParser; +import at.gv.egiz.eaaf.core.impl.idp.module.test.DummyConfiguration; +import at.gv.egiz.eaaf.core.impl.idp.module.test.DummySpConfiguration; +import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -11,97 +16,203 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.Base64Utils; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; -import at.gv.egiz.eaaf.core.impl.idp.auth.data.SimpleIdentityLinkAssertionParser; -import at.gv.egiz.eaaf.core.impl.idp.module.test.DummyConfiguration; -import at.gv.egiz.eaaf.core.impl.idp.module.test.DummySPConfiguration; -import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl; - @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/SpringTest-context_eaaf_core.xml") public class AuthenticationDataBuilderTest { - @Autowired private TestAuthenticationDataBuilder authBuilder; - @Autowired private DummyConfiguration authConfig; - - private static final String DUMMY_IDL_2 = "PHNhbWw6QXNzZXJ0aW9uIEFzc2VydGlvbklEPSJlbGdhdGVzdC5lZ2l6Lmd2LmF0LUFzc2VydGlvbklEWFhYxZB6Z8O8cl9YWFhUw7x6ZWvDp2kiIElzc3VlSW5zdGFudD0iMjAxOS0wMy0wNFQxNTo1MzowNCswMTowMCIgSXNzdWVyPSJodHRwOi8vcG9ydGFsLmJtaS5ndi5hdC9yZWYvc3pyL2lzc3VlciIgTWFqb3JWZXJzaW9uPSIxIiBNaW5vclZlcnNpb249IjAiIHhtbG5zOmRzaWc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyMiIHhtbG5zOmVjZHNhPSJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSMiIHhtbG5zOnByPSJodHRwOi8vcmVmZXJlbmNlLmUtZ292ZXJubWVudC5ndi5hdC9uYW1lc3BhY2UvcGVyc29uZGF0YS8yMDAyMDIyOCMiIHhtbG5zOnNhbWw9InVybjpvYXNpczpuYW1lczp0YzpTQU1MOjEuMDphc3NlcnRpb24iIHhtbG5zOnNpPSJodHRwOi8vd3d3LnczLm9yZy8yMDAxL1hNTFNjaGVtYS1pbnN0YW5jZSI+Cgk8c2FtbDpBdHRyaWJ1dGVTdGF0ZW1lbnQ+CgkJPHNhbWw6U3ViamVjdD4KCQkJPHNhbWw6U3ViamVjdENvbmZpcm1hdGlvbj4KCQkJCTxzYW1sOkNvbmZpcm1hdGlvbk1ldGhvZD51cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoxLjA6Y206c2VuZGVyLXZvdWNoZXM8L3NhbWw6Q29uZmlybWF0aW9uTWV0aG9kPgoJCQkJPHNhbWw6U3ViamVjdENvbmZpcm1hdGlvbkRhdGE+CgkJCQkJPHByOlBlcnNvbiBzaTp0eXBlPSJwcjpQaHlzaWNhbFBlcnNvblR5cGUiPjxwcjpJZGVudGlmaWNhdGlvbj48cHI6VmFsdWU+UlV4SFFWUmxjM1JRUWpCWVdGakZrSHBudzd4eVgxaFlXRlREdkhwbGE4T25hUT09PC9wcjpWYWx1ZT48cHI6VHlwZT51cm46cHVibGljaWQ6Z3YuYXQ6YmFzZWlkPC9wcjpUeXBlPjwvcHI6SWRlbnRpZmljYXRpb24+PHByOk5hbWU+PHByOkdpdmVuTmFtZT5YWFjFkHonZ8O8cjwvcHI6R2l2ZW5OYW1lPjxwcjpGYW1pbHlOYW1lIHByaW1hcnk9InVuZGVmaW5lZCI+WFhYVMO8emVrw6dpPC9wcjpGYW1pbHlOYW1lPjwvcHI6TmFtZT48cHI6RGF0ZU9mQmlydGg+MTk3My0wNi0wNDwvcHI6RGF0ZU9mQmlydGg+PC9wcjpQZXJzb24+CgkJCQk8L3NhbWw6U3ViamVjdENvbmZpcm1hdGlvbkRhdGE+CgkJCTwvc2FtbDpTdWJqZWN0Q29uZmlybWF0aW9uPgoJCTwvc2FtbDpTdWJqZWN0PgoJCTxzYW1sOkF0dHJpYnV0ZSBBdHRyaWJ1dGVOYW1lPSJDaXRpemVuUHVibGljS2V5IiBBdHRyaWJ1dGVOYW1lc3BhY2U9InVybjpwdWJsaWNpZDpndi5hdDpuYW1lc3BhY2VzOmlkZW50aXR5bGluazoxLjIiPjxzYW1sOkF0dHJpYnV0ZVZhbHVlPjxkc2lnOlJTQUtleVZhbHVlPjxkc2lnOk1vZHVsdXM+L1VLUkZIYkFhRWtnVmRnTTFTRE9KaldIcUszN3JKWVN0UHF0VVh6bzlWTm9yTzgzWW95emE5YjBkcDdtdVM4b2paMjRZRVBMUUZ3WQpCSVpkbTROSHJBNXZsVlZrRGV1Qng2bVRwRXBldTdkMkUzd3VZbVFXTjQxUXhWajZPcFhvSHRzek9jajd1Rm9mem1SR09PVUIzNUxDCkg2QzBMTFpJNTU5a3BPbmFxa2RLbU83dnduYVE0eTEwcHpCdjJ3U3BTZnY0djlIV3NCYUYxUWtYNmlmQ3lBbklLS3FKczR6S1RuK2EKR0kvS0FKOXdoam9GQk9yd1MzTlFpK1ZSVGxPYTdKdHdxeHBJZUYrT3c0R2wzaWdVb2szaGtsYlUyeElYcG5VeXNQYWhqUTBMNm5ORApZVHVmUC9jRmxrNWkvR1BZdmtONjJHd0Z4Rko1bDBoL1A3QWtJaCtWZmRCL0Q3SFVYaC9PV2dmek9MK2ZFRGdiL1dHM1BNenlObVFNCm5QQkdQb21hdGFOREtla0hhNUYwOUxFUHR5L0ZwMDUxLzFEUTZUMXhzamZ5ZG11aVZsWDZIRUZqZjFkYmQ4cUtGRm5TQ3NxRHBQdUQKR0hNcStKS0lmN25HQWtYSWxraTA1Nzd1bzM0MmxaeHBUVlRGVkFGdkJHS0Z6azNlQzMyT0NwOUo8L2RzaWc6TW9kdWx1cz48ZHNpZzpFeHBvbmVudD5BUUFCPC9kc2lnOkV4cG9uZW50PjwvZHNpZzpSU0FLZXlWYWx1ZT48L3NhbWw6QXR0cmlidXRlVmFsdWU+PC9zYW1sOkF0dHJpYnV0ZT48c2FtbDpBdHRyaWJ1dGUgQXR0cmlidXRlTmFtZT0iQ2l0aXplblB1YmxpY0tleSIgQXR0cmlidXRlTmFtZXNwYWNlPSJ1cm46cHVibGljaWQ6Z3YuYXQ6bmFtZXNwYWNlczppZGVudGl0eWxpbms6MS4yIj48c2FtbDpBdHRyaWJ1dGVWYWx1ZT48ZHNpZzpSU0FLZXlWYWx1ZT48ZHNpZzpNb2R1bHVzPnlQWGJhcEZhYXBycWlmVXVJaUxzR0FMaVdTTGRsUGNRN0VGZGZ5UzM0RVNJNGEyQnMwbUxTbm5FY1djeHJjWlgzcmxJUXBKaklwb1UKQStSRG9sNVBrU3BoSENMNkl2SVFNZmtreEg1Z0s2akN6VFNWOVJFVm1xUlRFMXNxUmNCUUduRFlwMjZwSFFoYzBHSG13NnVqeCtQTwp1dlE2Mm9hUUlxUXZ0T2ZLWFBReXlXTDE5clhXOTcrRUcweTBLd2VpOHRWY01uamJ5ZEtNL3Z5d01Fb3FFcU1mMEYrR0tjd3A3ZW50ClpzcnVEVEgrY0tJYnBXdUpLZzAwVUhraG45QWZkYlBXdzZWOWUrQmhxU0lYcTBoaEhmSkNBdzZwWXVYaVY2dE9ESlBGdnUxN1diQnQKV3B1ejJOR1RMU3Y3NXJlaklCa09TMk5MS0FmV3JhVmhUaDY3Vnc9PTwvZHNpZzpNb2R1bHVzPjxkc2lnOkV4cG9uZW50PkFRQUI8L2RzaWc6RXhwb25lbnQ+PC9kc2lnOlJTQUtleVZhbHVlPjwvc2FtbDpBdHRyaWJ1dGVWYWx1ZT48L3NhbWw6QXR0cmlidXRlPgoJPC9zYW1sOkF0dHJpYnV0ZVN0YXRlbWVudD4KPGRzaWc6U2lnbmF0dXJlIHhtbG5zOmRzaWc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyMiPjxkc2lnOlNpZ25lZEluZm8+PGRzaWc6Q2Fub25pY2FsaXphdGlvbk1ldGhvZCBBbGdvcml0aG09Imh0dHA6Ly93d3cudzMub3JnLzIwMDEvMTAveG1sLWV4Yy1jMTRuIyIvPjxkc2lnOlNpZ25hdHVyZU1ldGhvZCBBbGdvcml0aG09Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyNyc2Etc2hhMSIvPjxkc2lnOlJlZmVyZW5jZSBVUkk9IiI+PGRzaWc6VHJhbnNmb3Jtcz48ZHNpZzpUcmFuc2Zvcm0gQWxnb3JpdGhtPSJodHRwOi8vd3d3LnczLm9yZy9UUi8xOTk5L1JFQy14cGF0aC0xOTk5MTExNiI+PGRzaWc6WFBhdGg+bm90KGFuY2VzdG9yLW9yLXNlbGY6OnByOklkZW50aWZpY2F0aW9uKTwvZHNpZzpYUGF0aD48L2RzaWc6VHJhbnNmb3JtPjxkc2lnOlRyYW5zZm9ybSBBbGdvcml0aG09Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyNlbnZlbG9wZWQtc2lnbmF0dXJlIi8+PC9kc2lnOlRyYW5zZm9ybXM+PGRzaWc6RGlnZXN0TWV0aG9kIEFsZ29yaXRobT0iaHR0cDovL3d3dy53My5vcmcvMjAwMC8wOS94bWxkc2lnI3NoYTEiLz48ZHNpZzpEaWdlc3RWYWx1ZT43TmZyRUJKZGw4NTRyZG1BaDFjdFEyWDdXTWM9PC9kc2lnOkRpZ2VzdFZhbHVlPjwvZHNpZzpSZWZlcmVuY2U+PGRzaWc6UmVmZXJlbmNlIFR5cGU9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyNNYW5pZmVzdCIgVVJJPSIjbWFuaWZlc3QiPjxkc2lnOkRpZ2VzdE1ldGhvZCBBbGdvcml0aG09Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyNzaGExIi8+PGRzaWc6RGlnZXN0VmFsdWU+aGZnOHphM21ZcXU1UVNiVXpYSHhEZTUvU05FPTwvZHNpZzpEaWdlc3RWYWx1ZT48L2RzaWc6UmVmZXJlbmNlPjwvZHNpZzpTaWduZWRJbmZvPjxkc2lnOlNpZ25hdHVyZVZhbHVlPm11V2IzOVRhZ0NkM053V2N1NWlrRUp1SnBaZG5lZFJEY2RtMTdJWnYrT0VWRXRxeWxSdXIvd1g2QUdVQ1UvUFUKWm5DdWROR1ZwQ0hMWXpIaXBONWM4b2JtbmhsbElOb1NFTk81b3Y1amlNb05Lb2RBZXhKSU42bVpPREJkL1RtVAptNzBWaVd5ckdVTGJJWWwvd2hsdjFsZ2EzSjhjeDhLU29QejhTd05MMnF3VWoydG8vQWhnNGtjSmxxT3MyNVlNCk5YL3dhSW53NkRSN05HQ0pvRStaWlNwcEh3d1FtNnYrOUhZOUU4NnNlQkFBUHhJOU0xako0WldiMzI5akZ0aUEKcXZiOHM2anhyMmxsOHVWYWdxWENZaFg5K1dOUXdheXFZTCtPdzhPcGxVem9OMVRpS2hSbVFLWkl3S1lDMVo4eQpLK3ZqQWxRTzJhT05zNEhVaG9SNmQyNmUvTVUxZmJlWEhxVHpyZmI5R1hXSHl0dFRkanhiemtaQTFGODJsUUZvCjUrVnpjTUhRUmc3c0RKODY1Wk1zM3BwY2VoLzlaU2ZvT2Y1SFlEUFl1V2VjT0RpZ1pRWVh0TVlwdVBRVGsrQ20KczlaSkd6QlYybGVtZk5DOVFVNzh0Zm42cDFVWnJTTG5zWGFYbVVjOEVjNTNQaUhBT3Z6blh0QjVjRW5hV2daMgp1TGVGOEtTUmw2SjBlTlE5SkRQZ1NOMHNmYWxiVkNkaENUTlFtclJ0T2pVZjNlN3UzeElNelJ1Zm4wb2o2SHRwCnQzaEVESFhuSS9kTk1scHBSSXl4cGQxbFo5bXJYZklLcnJMZVdxdGd3cFB1OTRoVUhRL2VKejFrMy9IM0h6M2QKWkR4dkFFYzNTRERkb1FXeS9HUGZpcXNwRWZjbGd0SkNKQ2E4L2t2dTdSVT08L2RzaWc6U2lnbmF0dXJlVmFsdWU+PGRzaWc6S2V5SW5mbz48ZHNpZzpYNTA5RGF0YT48ZHNpZzpYNTA5Q2VydGlmaWNhdGU+TUlJRlpEQ0NBMHlnQXdJQkFnSUpBSmF2K3plcVUvRE1NQTBHQ1NxR1NJYjNEUUVCQ3dVQU1Gd3hDekFKQmdOVgpCQVlUQWtGVU1RMHdDd1lEVlFRS0V3UkZSMGxhTVJZd0ZBWURWUVFMRXcxVGIyWjBkMkZ5WlVOaGNtUnpNU1l3CkpBWURWUVFERkIxVVpYTjBYMU52Wm5SM1lYSmxZMkZ5WkhOZlNVUk1YMU5wWjI1bGNqQWVGdzB4TmpFd01UZ3gKTURNNU1EZGFGdzB4T1RBM01UUXhNRE01TURkYU1Gd3hDekFKQmdOVkJBWVRBa0ZVTVEwd0N3WURWUVFLRXdSRgpSMGxhTVJZd0ZBWURWUVFMRXcxVGIyWjBkMkZ5WlVOaGNtUnpNU1l3SkFZRFZRUURGQjFVWlhOMFgxTnZablIzCllYSmxZMkZ5WkhOZlNVUk1YMU5wWjI1bGNqQ0NBaUl3RFFZSktvWklodmNOQVFFQkJRQURnZ0lQQURDQ0Fnb0MKZ2dJQkFMa0xndCtNRlR4TGZSemNFSVowYnljSUZnN2cvSFBON1FXSVo2N2JIenJiNmVoZWJ6RjlWaW56RFpYQwprZktXZFVKYmtOU3VXS1dycDJYNjJmN29HaGRxSzB5RmMrRGxvK09wSURnUWlXQ3BCZktKbzhjUFdzaUFtTnVUCnhXVmFnVTVmYUkxaDd4dnZPVk15YldlOTJuaXZmcUxPdUV4Nld2WC9Vb0lhd1JIVjJWbVBHRmdab2NNNUcwWDYKYlVWRXBxeEFhM3FPSWxScjBwb0IrUkEwUEE4NmhScFJZYWwvT3I5M0Q4QmZRSDVsOHpWOVFjdlBlL0tlSlNwSgpIZ0dXbUVzNTkzTHROdUExUnYxaURwdXUxMHk3QzJGZU1CdmNVcFJrUjdXQWo3dklZVnRRSUxYQ2gxRmhmTjFiCkhnNnhMVlR5c2hsZ1VuN0FSUUpZb0ozdG9nZEdhbURSbG5LVTJyWE45ajg4VHc2ZkFkY0N2V2JXVnRqeThwTmoKV0xrVkpNbEZXZGZPNi81TEF2YTFIeFJPTWhGeDdRT1BoT3plbWV0Q3RUMmZJNEZUQWs5VnlmOXdUVVFPTDhzcQpLNzN0MUE0MTlsWVM4V3VVQ3pIRHhMdWpMaVR1d29JVWd6TU4vYnFNRVpyb2dQTFkyS2o0dm1aTVo0Z1UyUFU3Cll3K1hmYW5nMysveUsxZ1lORWVicGR2UGk4U1ZVQW51cy9DZm1kd2RuOU8vbmFXaUJwamMwNkdKdk1iZWdqeHcKb1BCTTVjMFNrQ1I1eENheWdaTDJPQnBSTUtnZGZyazRrMHBqNVpVbSttdHJPR29qdFJaSkVaUUNCcFZQazF5RAozTDQvWjRBWm9mT284ZFNrVVIreEpOMG9LbklkZm5kdkJ4TkY0c3hZNEl3T3ZGUnJBZ01CQUFHaktUQW5NQWtHCkExVWRFd1FDTUFBd0N3WURWUjBQQkFRREFnV2dNQTBHQnlvb0FBb0JCd0VFQWdVQU1BMEdDU3FHU0liM0RRRUIKQ3dVQUE0SUNBUUJjRUQ3dEU4cW1Bd0ZCZGh5b3oxRDh5b2RFWm1tZFhad2tzQS9rSStvKzV3UXM2WS9xdnc3agorZUJ2bGN0eVhDWFdoMWVGZWIvRmFpQTVDcG9hazhOYy9vWTdUL3lCajVnZktIbE5xVlQxb3dhQmtIc0VZTUJ2CmFVWHh5RENibkZNem5KZmt4amJ2RmJRZGQxaGNlSmh0OER4K2lrcEI2TUpIcUhJRXJ5MFdXZ2YzSmRONVBFcnIKQVRuZGpCRTRCYVRaMnE2c0N2K1NkSzYwTWswbVlBNmw2blNDOWVCOEc5QzRiQTFjUUVPdTYrRlBtRnpTa2lJRgp0ZW1BMXRqUW5oeEtaWmlnenhJTjNFUUFucS8yM2pmK0NreEF0NUdrcFVqcUY1YnFLSTFuZXJKT2duNEptNWo2CnNQWkdwR2xsekhMQmF5YmZZNjNBejRzRVJDMjhPbHFGdzF2eFFzNGhXSVdOV0VBTUYzT3o0K3BZZzRPSUloNUMKTnIxYXFKZ3NzV2ZPWnJYMktTejJ2cXJab1U2N3pxODRNUWNKVFNtZ0tWQmI5T25yQzV0WW41WVZVbHlkUFBqcgpVbTBpSGxXQzBNRmlJZ1N6eDZUaTJIblBnYzBVSHNBNklwU1RvK1V1ZllZTkRpRkNzc1JidTRyMC9TeXE0TVAzCmdoWVhkUDlUajBGSVN6MlR2TTZZUWZ6SGVqOTRiWmNWTnduRjRwV0VuR1p0QmJOVnZKUnc5aUpISGtEV0xpWU0KMUI3M3pzNytwQThZZ0txRXhESFhjMVNob3U1SHZTdVRYU21hVE1VSHJDa2hvdEhmcHFZaHJKaUFtSitPZnROdgo2b3hNUGZOaFpnMDFlT290bTFKK1dWMm1KYmdjUFROU0MxT05jU0ZkUTV2WlpMTDI0SjJIY3c9PTwvZHNpZzpYNTA5Q2VydGlmaWNhdGU+PC9kc2lnOlg1MDlEYXRhPjwvZHNpZzpLZXlJbmZvPjxkc2lnOk9iamVjdD48ZHNpZzpNYW5pZmVzdCBJZD0ibWFuaWZlc3QiPjxkc2lnOlJlZmVyZW5jZSBVUkk9IiI+PGRzaWc6VHJhbnNmb3Jtcz48ZHNpZzpUcmFuc2Zvcm0gQWxnb3JpdGhtPSJodHRwOi8vd3d3LnczLm9yZy9UUi8xOTk5L1JFQy14cGF0aC0xOTk5MTExNiI+PGRzaWc6WFBhdGggeG1sbnM6ZHNpZz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC8wOS94bWxkc2lnIyI+bm90KGFuY2VzdG9yLW9yLXNlbGY6OmRzaWc6U2lnbmF0dXJlKTwvZHNpZzpYUGF0aD48L2RzaWc6VHJhbnNmb3JtPjwvZHNpZzpUcmFuc2Zvcm1zPjxkc2lnOkRpZ2VzdE1ldGhvZCBBbGdvcml0aG09Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyNzaGExIi8+PGRzaWc6RGlnZXN0VmFsdWU+QXN4VHprWmRBWUM0U0s1cTh5c0pLVDd5ZHVRPTwvZHNpZzpEaWdlc3RWYWx1ZT48L2RzaWc6UmVmZXJlbmNlPjwvZHNpZzpNYW5pZmVzdD48L2RzaWc6T2JqZWN0PjwvZHNpZzpTaWduYXR1cmU+PC9zYW1sOkFzc2VydGlvbj4="; - - @Test - public void dummyTest() throws Exception { - - - } - - - - @Test - public void buildAuthDataWithIDLOnly_2_without_flag() throws Exception { - buildAuthDataWithIDLOnly_2(null, "XXXŐz'gür", "XXXTüzekçi"); - System.out.println("IDPParser and AuthDataBuilder without escape config --> Successfull"); - - } - - - @Test - public void buildAuthDataWithIDLOnly_2_with_flag_true() throws Exception { - buildAuthDataWithIDLOnly_2(true, "XXXŐz'gür", "XXXTüzekçi"); - System.out.println("IDPParser and AuthDataBuilder with escape config 'true' --> Successfull"); - - } - - @Test - public void buildAuthDataWithIDLOnly_2_with_flag_false() throws Exception { - buildAuthDataWithIDLOnly_2(false, "XXXŐz'gür", "XXXTüzekçi"); - System.out.println("IDPParser and AuthDataBuilder with escape config 'false' --> Successfull"); - - } - - private void buildAuthDataWithIDLOnly_2(Boolean idlEscaptionFlag, String givenName, String familyName) throws Exception { - IAuthData authData = null; - - try { - authConfig.setIsIDLEscapingEnabled(idlEscaptionFlag); - - TestRequestImpl pendingReq = new TestRequestImpl(); - Map spConfigMap = new HashMap(); - spConfigMap.put("target", "urn:publicid:gv.at:cdid+ZP-MH"); - - DummySPConfiguration spConfig = new DummySPConfiguration(spConfigMap , authConfig); - pendingReq.setSpConfig(spConfig); - - HashMap sessionStore = new HashMap(); - AuthProcessDataWrapper wrapper = new AuthProcessDataWrapper(sessionStore); - wrapper.setIdentityLink(new SimpleIdentityLinkAssertionParser(new ByteArrayInputStream(Base64Utils.decode(DUMMY_IDL_2.getBytes()))).parseIdentityLink()); - pendingReq.setRawDataToTransaction(sessionStore); - - authData = authBuilder.buildAuthenticationData(pendingReq); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - - } - - if (authData == null) - throw new Exception("AuthenticationData is 'null'"); - - if (!authData.getFamilyName().equals(familyName)) - throw new Exception("Familyname wrong"); - - if (!authData.getGivenName().equals(givenName)) - throw new Exception("GivenName wrong"); - - if (!authData.getFormatedDateOfBirth().equals("1973-06-04")) - throw new Exception("DateOfBirth wrong"); - - - if (!authData.getIdentificationValue().equals("RUxHQVRlc3RQQjBYWFjFkHpnw7xyX1hYWFTDvHpla8OnaQ==")) - throw new Exception("baseId wrong"); - - if (!authData.getIdentificationType().equals("urn:publicid:gv.at:baseid")) - throw new Exception("baseIdType wrong"); - - } - + @Autowired + private TestAuthenticationDataBuilder authBuilder; + @Autowired + private DummyConfiguration authConfig; + + private static final String DUMMY_IDL_2 = + "PHNhbWw6QXNzZXJ0aW9uIEFzc2VydGlvbklEPSJlbGdhdGVzdC5lZ2l6Lmd2LmF0LUFzc2VydGlvbklEWFhYxZB6Z8O8" + + "cl9YWFhUw7x6ZWvDp2kiIElzc3VlSW5zdGFudD0iMjAxOS0wMy0wNFQxNTo1MzowNCswMTowMCIgSXNzdWVyPSJodH" + + "RwOi8vcG9ydGFsLmJtaS5ndi5hdC9yZWYvc3pyL2lzc3VlciIgTWFqb3JWZXJzaW9uPSIxIiBNaW5vclZlcnNpb249" + + "IjAiIHhtbG5zOmRzaWc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyMiIHhtbG5zOmVjZHNhPSJodH" + + "RwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSMiIHhtbG5zOnByPSJodHRwOi8vcmVmZXJlbmNlLmUt" + + "Z292ZXJubWVudC5ndi5hdC9uYW1lc3BhY2UvcGVyc29uZGF0YS8yMDAyMDIyOCMiIHhtbG5zOnNhbWw9InVybjpvYX" + + "NpczpuYW1lczp0YzpTQU1MOjEuMDphc3NlcnRpb24iIHhtbG5zOnNpPSJodHRwOi8vd3d3LnczLm9yZy8yMDAxL1hN" + + "TFNjaGVtYS1pbnN0YW5jZSI+Cgk8c2FtbDpBdHRyaWJ1dGVTdGF0ZW1lbnQ+CgkJPHNhbWw6U3ViamVjdD4KCQkJPH" + + "NhbWw6U3ViamVjdENvbmZpcm1hdGlvbj4KCQkJCTxzYW1sOkNvbmZpcm1hdGlvbk1ldGhvZD51cm46b2FzaXM6bmFt" + + "ZXM6dGM6U0FNTDoxLjA6Y206c2VuZGVyLXZvdWNoZXM8L3NhbWw6Q29uZmlybWF0aW9uTWV0aG9kPgoJCQkJPHNhbW" + + "w6U3ViamVjdENvbmZpcm1hdGlvbkRhdGE+CgkJCQkJPHByOlBlcnNvbiBzaTp0eXBlPSJwcjpQaHlzaWNhbFBlcnNv" + + "blR5cGUiPjxwcjpJZGVudGlmaWNhdGlvbj48cHI6VmFsdWU+UlV4SFFWUmxjM1JRUWpCWVdGakZrSHBudzd4eVgxaF" + + "lXRlREdkhwbGE4T25hUT09PC9wcjpWYWx1ZT48cHI6VHlwZT51cm46cHVibGljaWQ6Z3YuYXQ6YmFzZWlkPC9wcjpU" + + "eXBlPjwvcHI6SWRlbnRpZmljYXRpb24+PHByOk5hbWU+PHByOkdpdmVuTmFtZT5YWFjFkHonZ8O8cjwvcHI6R2l2ZW" + + "5OYW1lPjxwcjpGYW1pbHlOYW1lIHByaW1hcnk9InVuZGVmaW5lZCI+WFhYVMO8emVrw6dpPC9wcjpGYW1pbHlOYW1l" + + "PjwvcHI6TmFtZT48cHI6RGF0ZU9mQmlydGg+MTk3My0wNi0wNDwvcHI6RGF0ZU9mQmlydGg+PC9wcjpQZXJzb24+Cg" + + "kJCQk8L3NhbWw6U3ViamVjdENvbmZpcm1hdGlvbkRhdGE+CgkJCTwvc2FtbDpTdWJqZWN0Q29uZmlybWF0aW9uPgoJ" + + "CTwvc2FtbDpTdWJqZWN0PgoJCTxzYW1sOkF0dHJpYnV0ZSBBdHRyaWJ1dGVOYW1lPSJDaXRpemVuUHVibGljS2V5Ii" + + "BBdHRyaWJ1dGVOYW1lc3BhY2U9InVybjpwdWJsaWNpZDpndi5hdDpuYW1lc3BhY2VzOmlkZW50aXR5bGluazoxLjIi" + + "PjxzYW1sOkF0dHJpYnV0ZVZhbHVlPjxkc2lnOlJTQUtleVZhbHVlPjxkc2lnOk1vZHVsdXM+L1VLUkZIYkFhRWtnVm" + + "RnTTFTRE9KaldIcUszN3JKWVN0UHF0VVh6bzlWTm9yTzgzWW95emE5YjBkcDdtdVM4b2paMjRZRVBMUUZ3WQpCSVpk" + + "bTROSHJBNXZsVlZrRGV1Qng2bVRwRXBldTdkMkUzd3VZbVFXTjQxUXhWajZPcFhvSHRzek9jajd1Rm9mem1SR09PVU" + + "IzNUxDCkg2QzBMTFpJNTU5a3BPbmFxa2RLbU83dnduYVE0eTEwcHpCdjJ3U3BTZnY0djlIV3NCYUYxUWtYNmlmQ3lB" + + "bklLS3FKczR6S1RuK2EKR0kvS0FKOXdoam9GQk9yd1MzTlFpK1ZSVGxPYTdKdHdxeHBJZUYrT3c0R2wzaWdVb2szaG" + + "tsYlUyeElYcG5VeXNQYWhqUTBMNm5ORApZVHVmUC9jRmxrNWkvR1BZdmtONjJHd0Z4Rko1bDBoL1A3QWtJaCtWZmRC" + + "L0Q3SFVYaC9PV2dmek9MK2ZFRGdiL1dHM1BNenlObVFNCm5QQkdQb21hdGFOREtla0hhNUYwOUxFUHR5L0ZwMDUxLz" + + "FEUTZUMXhzamZ5ZG11aVZsWDZIRUZqZjFkYmQ4cUtGRm5TQ3NxRHBQdUQKR0hNcStKS0lmN25HQWtYSWxraTA1Nzd1" + + "bzM0MmxaeHBUVlRGVkFGdkJHS0Z6azNlQzMyT0NwOUo8L2RzaWc6TW9kdWx1cz48ZHNpZzpFeHBvbmVudD5BUUFCPC" + + "9kc2lnOkV4cG9uZW50PjwvZHNpZzpSU0FLZXlWYWx1ZT48L3NhbWw6QXR0cmlidXRlVmFsdWU+PC9zYW1sOkF0dHJp" + + "YnV0ZT48c2FtbDpBdHRyaWJ1dGUgQXR0cmlidXRlTmFtZT0iQ2l0aXplblB1YmxpY0tleSIgQXR0cmlidXRlTmFtZX" + + "NwYWNlPSJ1cm46cHVibGljaWQ6Z3YuYXQ6bmFtZXNwYWNlczppZGVudGl0eWxpbms6MS4yIj48c2FtbDpBdHRyaWJ1" + + "dGVWYWx1ZT48ZHNpZzpSU0FLZXlWYWx1ZT48ZHNpZzpNb2R1bHVzPnlQWGJhcEZhYXBycWlmVXVJaUxzR0FMaVdTTG" + + "RsUGNRN0VGZGZ5UzM0RVNJNGEyQnMwbUxTbm5FY1djeHJjWlgzcmxJUXBKaklwb1UKQStSRG9sNVBrU3BoSENMNkl2" + + "SVFNZmtreEg1Z0s2akN6VFNWOVJFVm1xUlRFMXNxUmNCUUduRFlwMjZwSFFoYzBHSG13NnVqeCtQTwp1dlE2Mm9hUU" + + "lxUXZ0T2ZLWFBReXlXTDE5clhXOTcrRUcweTBLd2VpOHRWY01uamJ5ZEtNL3Z5d01Fb3FFcU1mMEYrR0tjd3A3ZW50" + + "ClpzcnVEVEgrY0tJYnBXdUpLZzAwVUhraG45QWZkYlBXdzZWOWUrQmhxU0lYcTBoaEhmSkNBdzZwWXVYaVY2dE9ESl" + + "BGdnUxN1diQnQKV3B1ejJOR1RMU3Y3NXJlaklCa09TMk5MS0FmV3JhVmhUaDY3Vnc9PTwvZHNpZzpNb2R1bHVzPjxk" + + "c2lnOkV4cG9uZW50PkFRQUI8L2RzaWc6RXhwb25lbnQ+PC9kc2lnOlJTQUtleVZhbHVlPjwvc2FtbDpBdHRyaWJ1dG" + + "VWYWx1ZT48L3NhbWw6QXR0cmlidXRlPgoJPC9zYW1sOkF0dHJpYnV0ZVN0YXRlbWVudD4KPGRzaWc6U2lnbmF0dXJl" + + "IHhtbG5zOmRzaWc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyMiPjxkc2lnOlNpZ25lZEluZm8+PG" + + "RzaWc6Q2Fub25pY2FsaXphdGlvbk1ldGhvZCBBbGdvcml0aG09Imh0dHA6Ly93d3cudzMub3JnLzIwMDEvMTAveG1s" + + "LWV4Yy1jMTRuIyIvPjxkc2lnOlNpZ25hdHVyZU1ldGhvZCBBbGdvcml0aG09Imh0dHA6Ly93d3cudzMub3JnLzIwMD" + + "AvMDkveG1sZHNpZyNyc2Etc2hhMSIvPjxkc2lnOlJlZmVyZW5jZSBVUkk9IiI+PGRzaWc6VHJhbnNmb3Jtcz48ZHNp" + + "ZzpUcmFuc2Zvcm0gQWxnb3JpdGhtPSJodHRwOi8vd3d3LnczLm9yZy9UUi8xOTk5L1JFQy14cGF0aC0xOTk5MTExNi" + + "I+PGRzaWc6WFBhdGg+bm90KGFuY2VzdG9yLW9yLXNlbGY6OnByOklkZW50aWZpY2F0aW9uKTwvZHNpZzpYUGF0aD48" + + "L2RzaWc6VHJhbnNmb3JtPjxkc2lnOlRyYW5zZm9ybSBBbGdvcml0aG09Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMD" + + "kveG1sZHNpZyNlbnZlbG9wZWQtc2lnbmF0dXJlIi8+PC9kc2lnOlRyYW5zZm9ybXM+PGRzaWc6RGlnZXN0TWV0aG9k" + + "IEFsZ29yaXRobT0iaHR0cDovL3d3dy53My5vcmcvMjAwMC8wOS94bWxkc2lnI3NoYTEiLz48ZHNpZzpEaWdlc3RWYW" + + "x1ZT43TmZyRUJKZGw4NTRyZG1BaDFjdFEyWDdXTWM9PC9kc2lnOkRpZ2VzdFZhbHVlPjwvZHNpZzpSZWZlcmVuY2U+" + + "PGRzaWc6UmVmZXJlbmNlIFR5cGU9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyNNYW5pZmVzdCIgVV" + + "JJPSIjbWFuaWZlc3QiPjxkc2lnOkRpZ2VzdE1ldGhvZCBBbGdvcml0aG09Imh0dHA6Ly93d3cudzMub3JnLzIwMDAv" + + "MDkveG1sZHNpZyNzaGExIi8+PGRzaWc6RGlnZXN0VmFsdWU+aGZnOHphM21ZcXU1UVNiVXpYSHhEZTUvU05FPTwvZH" + + "NpZzpEaWdlc3RWYWx1ZT48L2RzaWc6UmVmZXJlbmNlPjwvZHNpZzpTaWduZWRJbmZvPjxkc2lnOlNpZ25hdHVyZVZh" + + "bHVlPm11V2IzOVRhZ0NkM053V2N1NWlrRUp1SnBaZG5lZFJEY2RtMTdJWnYrT0VWRXRxeWxSdXIvd1g2QUdVQ1UvUF" + + "UKWm5DdWROR1ZwQ0hMWXpIaXBONWM4b2JtbmhsbElOb1NFTk81b3Y1amlNb05Lb2RBZXhKSU42bVpPREJkL1RtVApt" + + "NzBWaVd5ckdVTGJJWWwvd2hsdjFsZ2EzSjhjeDhLU29QejhTd05MMnF3VWoydG8vQWhnNGtjSmxxT3MyNVlNCk5YL3" + + "dhSW53NkRSN05HQ0pvRStaWlNwcEh3d1FtNnYrOUhZOUU4NnNlQkFBUHhJOU0xako0WldiMzI5akZ0aUEKcXZiOHM2" + + "anhyMmxsOHVWYWdxWENZaFg5K1dOUXdheXFZTCtPdzhPcGxVem9OMVRpS2hSbVFLWkl3S1lDMVo4eQpLK3ZqQWxRTz" + + "JhT05zNEhVaG9SNmQyNmUvTVUxZmJlWEhxVHpyZmI5R1hXSHl0dFRkanhiemtaQTFGODJsUUZvCjUrVnpjTUhRUmc3" + + "c0RKODY1Wk1zM3BwY2VoLzlaU2ZvT2Y1SFlEUFl1V2VjT0RpZ1pRWVh0TVlwdVBRVGsrQ20KczlaSkd6QlYybGVtZk" + + "5DOVFVNzh0Zm42cDFVWnJTTG5zWGFYbVVjOEVjNTNQaUhBT3Z6blh0QjVjRW5hV2daMgp1TGVGOEtTUmw2SjBlTlE5" + + "SkRQZ1NOMHNmYWxiVkNkaENUTlFtclJ0T2pVZjNlN3UzeElNelJ1Zm4wb2o2SHRwCnQzaEVESFhuSS9kTk1scHBSSX" + + "l4cGQxbFo5bXJYZklLcnJMZVdxdGd3cFB1OTRoVUhRL2VKejFrMy9IM0h6M2QKWkR4dkFFYzNTRERkb1FXeS9HUGZp" + + "cXNwRWZjbGd0SkNKQ2E4L2t2dTdSVT08L2RzaWc6U2lnbmF0dXJlVmFsdWU+PGRzaWc6S2V5SW5mbz48ZHNpZzpYNT" + + "A5RGF0YT48ZHNpZzpYNTA5Q2VydGlmaWNhdGU+TUlJRlpEQ0NBMHlnQXdJQkFnSUpBSmF2K3plcVUvRE1NQTBHQ1Nx" + + "R1NJYjNEUUVCQ3dVQU1Gd3hDekFKQmdOVgpCQVlUQWtGVU1RMHdDd1lEVlFRS0V3UkZSMGxhTVJZd0ZBWURWUVFMRX" + + "cxVGIyWjBkMkZ5WlVOaGNtUnpNU1l3CkpBWURWUVFERkIxVVpYTjBYMU52Wm5SM1lYSmxZMkZ5WkhOZlNVUk1YMU5w" + + "WjI1bGNqQWVGdzB4TmpFd01UZ3gKTURNNU1EZGFGdzB4T1RBM01UUXhNRE01TURkYU1Gd3hDekFKQmdOVkJBWVRBa0" + + "ZVTVEwd0N3WURWUVFLRXdSRgpSMGxhTVJZd0ZBWURWUVFMRXcxVGIyWjBkMkZ5WlVOaGNtUnpNU1l3SkFZRFZRUURG" + + "QjFVWlhOMFgxTnZablIzCllYSmxZMkZ5WkhOZlNVUk1YMU5wWjI1bGNqQ0NBaUl3RFFZSktvWklodmNOQVFFQkJRQU" + + "RnZ0lQQURDQ0Fnb0MKZ2dJQkFMa0xndCtNRlR4TGZSemNFSVowYnljSUZnN2cvSFBON1FXSVo2N2JIenJiNmVoZWJ6" + + "RjlWaW56RFpYQwprZktXZFVKYmtOU3VXS1dycDJYNjJmN29HaGRxSzB5RmMrRGxvK09wSURnUWlXQ3BCZktKbzhjUF" + + "dzaUFtTnVUCnhXVmFnVTVmYUkxaDd4dnZPVk15YldlOTJuaXZmcUxPdUV4Nld2WC9Vb0lhd1JIVjJWbVBHRmdab2NN" + + "NUcwWDYKYlVWRXBxeEFhM3FPSWxScjBwb0IrUkEwUEE4NmhScFJZYWwvT3I5M0Q4QmZRSDVsOHpWOVFjdlBlL0tlSl" + + "NwSgpIZ0dXbUVzNTkzTHROdUExUnYxaURwdXUxMHk3QzJGZU1CdmNVcFJrUjdXQWo3dklZVnRRSUxYQ2gxRmhmTjFi" + + "CkhnNnhMVlR5c2hsZ1VuN0FSUUpZb0ozdG9nZEdhbURSbG5LVTJyWE45ajg4VHc2ZkFkY0N2V2JXVnRqeThwTmoKV0" + + "xrVkpNbEZXZGZPNi81TEF2YTFIeFJPTWhGeDdRT1BoT3plbWV0Q3RUMmZJNEZUQWs5VnlmOXdUVVFPTDhzcQpLNzN0" + + "MUE0MTlsWVM4V3VVQ3pIRHhMdWpMaVR1d29JVWd6TU4vYnFNRVpyb2dQTFkyS2o0dm1aTVo0Z1UyUFU3Cll3K1hmYW" + + "5nMysveUsxZ1lORWVicGR2UGk4U1ZVQW51cy9DZm1kd2RuOU8vbmFXaUJwamMwNkdKdk1iZWdqeHcKb1BCTTVjMFNr" + + "Q1I1eENheWdaTDJPQnBSTUtnZGZyazRrMHBqNVpVbSttdHJPR29qdFJaSkVaUUNCcFZQazF5RAozTDQvWjRBWm9mT2" + + "84ZFNrVVIreEpOMG9LbklkZm5kdkJ4TkY0c3hZNEl3T3ZGUnJBZ01CQUFHaktUQW5NQWtHCkExVWRFd1FDTUFBd0N3" + + "WURWUjBQQkFRREFnV2dNQTBHQnlvb0FBb0JCd0VFQWdVQU1BMEdDU3FHU0liM0RRRUIKQ3dVQUE0SUNBUUJjRUQ3dE" + + "U4cW1Bd0ZCZGh5b3oxRDh5b2RFWm1tZFhad2tzQS9rSStvKzV3UXM2WS9xdnc3agorZUJ2bGN0eVhDWFdoMWVGZWIv" + + "RmFpQTVDcG9hazhOYy9vWTdUL3lCajVnZktIbE5xVlQxb3dhQmtIc0VZTUJ2CmFVWHh5RENibkZNem5KZmt4amJ2Rm" + + "JRZGQxaGNlSmh0OER4K2lrcEI2TUpIcUhJRXJ5MFdXZ2YzSmRONVBFcnIKQVRuZGpCRTRCYVRaMnE2c0N2K1NkSzYw" + + "TWswbVlBNmw2blNDOWVCOEc5QzRiQTFjUUVPdTYrRlBtRnpTa2lJRgp0ZW1BMXRqUW5oeEtaWmlnenhJTjNFUUFucS" + + "8yM2pmK0NreEF0NUdrcFVqcUY1YnFLSTFuZXJKT2duNEptNWo2CnNQWkdwR2xsekhMQmF5YmZZNjNBejRzRVJDMjhP" + + "bHFGdzF2eFFzNGhXSVdOV0VBTUYzT3o0K3BZZzRPSUloNUMKTnIxYXFKZ3NzV2ZPWnJYMktTejJ2cXJab1U2N3pxOD" + + "RNUWNKVFNtZ0tWQmI5T25yQzV0WW41WVZVbHlkUFBqcgpVbTBpSGxXQzBNRmlJZ1N6eDZUaTJIblBnYzBVSHNBNklw" + + "U1RvK1V1ZllZTkRpRkNzc1JidTRyMC9TeXE0TVAzCmdoWVhkUDlUajBGSVN6MlR2TTZZUWZ6SGVqOTRiWmNWTnduRj" + + "RwV0VuR1p0QmJOVnZKUnc5aUpISGtEV0xpWU0KMUI3M3pzNytwQThZZ0txRXhESFhjMVNob3U1SHZTdVRYU21hVE1V" + + "SHJDa2hvdEhmcHFZaHJKaUFtSitPZnROdgo2b3hNUGZOaFpnMDFlT290bTFKK1dWMm1KYmdjUFROU0MxT05jU0ZkUT" + + "V2WlpMTDI0SjJIY3c9PTwvZHNpZzpYNTA5Q2VydGlmaWNhdGU+PC9kc2lnOlg1MDlEYXRhPjwvZHNpZzpLZXlJbmZv" + + "Pjxkc2lnOk9iamVjdD48ZHNpZzpNYW5pZmVzdCBJZD0ibWFuaWZlc3QiPjxkc2lnOlJlZmVyZW5jZSBVUkk9IiI+PG" + + "RzaWc6VHJhbnNmb3Jtcz48ZHNpZzpUcmFuc2Zvcm0gQWxnb3JpdGhtPSJodHRwOi8vd3d3LnczLm9yZy9UUi8xOTk5" + + "L1JFQy14cGF0aC0xOTk5MTExNiI+PGRzaWc6WFBhdGggeG1sbnM6ZHNpZz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC" + + "8wOS94bWxkc2lnIyI+bm90KGFuY2VzdG9yLW9yLXNlbGY6OmRzaWc6U2lnbmF0dXJlKTwvZHNpZzpYUGF0aD48L2Rz" + + "aWc6VHJhbnNmb3JtPjwvZHNpZzpUcmFuc2Zvcm1zPjxkc2lnOkRpZ2VzdE1ldGhvZCBBbGdvcml0aG09Imh0dHA6Ly" + + "93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyNzaGExIi8+PGRzaWc6RGlnZXN0VmFsdWU+QXN4VHprWmRBWUM0U0s1" + + "cTh5c0pLVDd5ZHVRPTwvZHNpZzpEaWdlc3RWYWx1ZT48L2RzaWc6UmVmZXJlbmNlPjwvZHNpZzpNYW5pZmVzdD48L2" + + "RzaWc6T2JqZWN0PjwvZHNpZzpTaWduYXR1cmU+PC9zYW1sOkFzc2VydGlvbj4="; + + @Test + public void dummyTest() throws Exception { + + + } + + + + @Test + public void buildAuthDataWithIdlOnly_2_without_flag() throws Exception { + buildAuthDataWithIdlOnly_2(null, "XXXŐz'gür", "XXXTüzekçi"); + System.out.println("IDPParser and AuthDataBuilder without escape config --> Successfull"); + + } + + + @Test + public void buildAuthDataWithIdlOnly_2_with_flag_true() throws Exception { + buildAuthDataWithIdlOnly_2(true, "XXXŐz'gür", "XXXTüzekçi"); + System.out.println("IDPParser and AuthDataBuilder with escape config 'true' --> Successfull"); + + } + + @Test + public void buildAuthDataWithIdlOnly_2_with_flag_false() throws Exception { + buildAuthDataWithIdlOnly_2(false, "XXXŐz'gür", "XXXTüzekçi"); + System.out.println("IDPParser and AuthDataBuilder with escape config 'false' --> Successfull"); + + } + + private void buildAuthDataWithIdlOnly_2(final Boolean idlEscaptionFlag, final String givenName, + final String familyName) throws Exception { + IAuthData authData = null; + + try { + authConfig.setIsIdlEscapingEnabled(idlEscaptionFlag); + + final TestRequestImpl pendingReq = new TestRequestImpl(); + final Map spConfigMap = new HashMap<>(); + spConfigMap.put("target", "urn:publicid:gv.at:cdid+ZP-MH"); + + final DummySpConfiguration spConfig = new DummySpConfiguration(spConfigMap, authConfig); + pendingReq.setSpConfig(spConfig); + + final HashMap sessionStore = new HashMap<>(); + final AuthProcessDataWrapper wrapper = new AuthProcessDataWrapper(sessionStore); + wrapper.setIdentityLink(new SimpleIdentityLinkAssertionParser( + new ByteArrayInputStream(Base64Utils.decode(DUMMY_IDL_2.getBytes()))) + .parseIdentityLink()); + pendingReq.setRawDataToTransaction(sessionStore); + + authData = authBuilder.buildAuthenticationData(pendingReq); + + } catch (final Exception e) { + e.printStackTrace(); + throw e; + + } + + if (authData == null) { + throw new Exception("AuthenticationData is 'null'"); + } + + if (!authData.getFamilyName().equals(familyName)) { + throw new Exception("Familyname wrong"); + } + + if (!authData.getGivenName().equals(givenName)) { + throw new Exception("GivenName wrong"); + } + + if (!authData.getFormatedDateOfBirth().equals("1973-06-04")) { + throw new Exception("DateOfBirth wrong"); + } + + + if (!authData.getIdentificationValue() + .equals("RUxHQVRlc3RQQjBYWFjFkHpnw7xyX1hYWFTDvHpla8OnaQ==")) { + throw new Exception("baseId wrong"); + } + + if (!authData.getIdentificationType().equals("urn:publicid:gv.at:baseid")) { + throw new Exception("baseIdType wrong"); + } + + } + } diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/DummyAuthManager.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/DummyAuthManager.java index 368a1915..6d2ca67e 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/DummyAuthManager.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/DummyAuthManager.java @@ -5,22 +5,23 @@ import javax.servlet.http.HttpServletResponse; import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; -import at.gv.egiz.eaaf.core.api.idp.slo.ISLOInformationContainer; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.api.idp.slo.ISloInformationContainer; +import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.impl.idp.controller.protocols.RequestImpl; public class DummyAuthManager extends AbstractAuthenticationManager { - @Override - public ISLOInformationContainer performSingleLogOut(HttpServletRequest httpReq, HttpServletResponse httpResp, - IRequest pendingReq, String internalSSOId) throws EAAFException { - return null; - } + @Override + public ISloInformationContainer performSingleLogOut(final HttpServletRequest httpReq, + final HttpServletResponse httpResp, final IRequest pendingReq, final String internalSsoId) + throws EaafException { + return null; + } - @Override - protected void populateExecutionContext(ExecutionContext executionContext, RequestImpl pendingReq, - HttpServletRequest httpReq) throws EAAFException { + @Override + protected void populateExecutionContext(final ExecutionContext executionContext, + final RequestImpl pendingReq, final HttpServletRequest httpReq) throws EaafException { - } + } } diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/DummyHttpClientFactory.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/DummyHttpClientFactory.java index 752932ce..9a924f83 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/DummyHttpClientFactory.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/DummyHttpClientFactory.java @@ -6,16 +6,16 @@ import at.gv.egiz.eaaf.core.impl.utils.IHttpClientFactory; public class DummyHttpClientFactory implements IHttpClientFactory { - @Override - public CloseableHttpClient getHttpClient() { - // TODO Auto-generated method stub - return null; - } + @Override + public CloseableHttpClient getHttpClient() { + // TODO Auto-generated method stub + return null; + } - @Override - public CloseableHttpClient getHttpClient(boolean followRedirects) { - // TODO Auto-generated method stub - return null; - } + @Override + public CloseableHttpClient getHttpClient(final boolean followRedirects) { + // TODO Auto-generated method stub + return null; + } } diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/TestAuthenticationDataBuilder.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/TestAuthenticationDataBuilder.java index c5610bc9..3e21c211 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/TestAuthenticationDataBuilder.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/TestAuthenticationDataBuilder.java @@ -2,11 +2,11 @@ package at.gv.egiz.eaaf.core.impl.idp.auth; import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; import at.gv.egiz.eaaf.core.api.idp.auth.data.IAuthProcessDataContainer; -import at.gv.egiz.eaaf.core.exceptions.EAAFAuthenticationException; -import at.gv.egiz.eaaf.core.exceptions.EAAFBuilderException; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.EaafAuthenticationException; +import at.gv.egiz.eaaf.core.exceptions.EaafBuilderException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.impl.data.Pair; import at.gv.egiz.eaaf.core.impl.idp.AuthenticationData; import at.gv.egiz.eaaf.core.impl.idp.auth.builder.AbstractAuthenticationDataBuilder; @@ -14,46 +14,48 @@ import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; public class TestAuthenticationDataBuilder extends AbstractAuthenticationDataBuilder { - @Override - protected IAuthData getAuthDataInstance(IRequest pendingReq) throws EAAFException { - throw new EAAFException("Not supported yet"); - } - - @Override - protected void buildServiceSpecificAuthenticationData(IAuthData authData, IRequest pendingReq) - throws EAAFException { - throw new EAAFException("Not supported yet"); - - } - - @Override - @Deprecated - protected IAuthData buildDeprecatedAuthData(IRequest pendingReq) throws EAAFException { - final AuthenticationData authData = new AuthenticationData(); - try { - generateDeprecatedBasicAuthData(authData, pendingReq, pendingReq.getSessionData(AuthProcessDataWrapper.class)); - - } catch (final Exception e) { - e.printStackTrace(); - throw new EAAFAuthenticationException("AuthDataGeneration FAILED", null, e); - - } - return authData; - } - - @Override - protected Pair getEncryptedbPKFromPVPAttribute(IAuthProcessDataContainer authProcessDataContainer, - AuthenticationData authData, ISPConfiguration spConfig) throws EAAFBuilderException { - // TODO Auto-generated method stub - return null; - } - - @Override - protected Pair getbaseIDFromSZR(AuthenticationData authData, String notValidbPK, - String notValidbPKType) { - // TODO Auto-generated method stub - return null; - } + @Override + protected IAuthData getAuthDataInstance(final IRequest pendingReq) throws EaafException { + throw new EaafException("Not supported yet"); + } + + @Override + protected void buildServiceSpecificAuthenticationData(final IAuthData authData, + final IRequest pendingReq) throws EaafException { + throw new EaafException("Not supported yet"); + + } + + @Override + @Deprecated + protected IAuthData buildDeprecatedAuthData(final IRequest pendingReq) throws EaafException { + final AuthenticationData authData = new AuthenticationData(); + try { + generateDeprecatedBasicAuthData(authData, pendingReq, + pendingReq.getSessionData(AuthProcessDataWrapper.class)); + + } catch (final Exception e) { + e.printStackTrace(); + throw new EaafAuthenticationException("AuthDataGeneration FAILED", null, e); + + } + return authData; + } + + @Override + protected Pair getEncryptedBpkFromPvpAttribute( + final IAuthProcessDataContainer authProcessDataContainer, final AuthenticationData authData, + final IspConfiguration spConfig) throws EaafBuilderException { + // TODO Auto-generated method stub + return null; + } + + @Override + protected Pair getbaseIdFromSzr(final AuthenticationData authData, + final String notValidBpk, final String notValidBpkType) { + // TODO Auto-generated method stub + return null; + } } diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/attributes/AbstractAttributeBuilderTest.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/attributes/AbstractAttributeBuilderTest.java index 68cc16ed..8619b58f 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/attributes/AbstractAttributeBuilderTest.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/attributes/AbstractAttributeBuilderTest.java @@ -3,67 +3,174 @@ package at.gv.egiz.eaaf.core.impl.idp.auth.attributes; import java.io.ByteArrayInputStream; import java.util.HashMap; import java.util.Map; - -import org.junit.BeforeClass; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.util.Base64Utils; - import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.exceptions.EAAFParserException; -import at.gv.egiz.eaaf.core.exceptions.EAAFStorageException; +import at.gv.egiz.eaaf.core.exceptions.EaafParserException; +import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; import at.gv.egiz.eaaf.core.impl.idp.auth.TestAuthenticationDataBuilder; import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; import at.gv.egiz.eaaf.core.impl.idp.auth.data.SimpleIdentityLinkAssertionParser; import at.gv.egiz.eaaf.core.impl.idp.builder.SimpleStringAttributeGenerator; import at.gv.egiz.eaaf.core.impl.idp.module.test.DummyConfiguration; -import at.gv.egiz.eaaf.core.impl.idp.module.test.DummySPConfiguration; +import at.gv.egiz.eaaf.core.impl.idp.module.test.DummySpConfiguration; import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl; +import org.junit.BeforeClass; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.Base64Utils; public abstract class AbstractAttributeBuilderTest { - @Autowired private TestAuthenticationDataBuilder authBuilder; - private static final String DUMMY_IDL_2 = "PHNhbWw6QXNzZXJ0aW9uIEFzc2VydGlvbklEPSJlbGdhdGVzdC5lZ2l6Lmd2LmF0LUFzc2VydGlvbklEWFhYxZB6Z8O8cl9YWFhUw7x6ZWvDp2kiIElzc3VlSW5zdGFudD0iMjAxOS0wMy0wNFQxNTo1MzowNCswMTowMCIgSXNzdWVyPSJodHRwOi8vcG9ydGFsLmJtaS5ndi5hdC9yZWYvc3pyL2lzc3VlciIgTWFqb3JWZXJzaW9uPSIxIiBNaW5vclZlcnNpb249IjAiIHhtbG5zOmRzaWc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyMiIHhtbG5zOmVjZHNhPSJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSMiIHhtbG5zOnByPSJodHRwOi8vcmVmZXJlbmNlLmUtZ292ZXJubWVudC5ndi5hdC9uYW1lc3BhY2UvcGVyc29uZGF0YS8yMDAyMDIyOCMiIHhtbG5zOnNhbWw9InVybjpvYXNpczpuYW1lczp0YzpTQU1MOjEuMDphc3NlcnRpb24iIHhtbG5zOnNpPSJodHRwOi8vd3d3LnczLm9yZy8yMDAxL1hNTFNjaGVtYS1pbnN0YW5jZSI+Cgk8c2FtbDpBdHRyaWJ1dGVTdGF0ZW1lbnQ+CgkJPHNhbWw6U3ViamVjdD4KCQkJPHNhbWw6U3ViamVjdENvbmZpcm1hdGlvbj4KCQkJCTxzYW1sOkNvbmZpcm1hdGlvbk1ldGhvZD51cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoxLjA6Y206c2VuZGVyLXZvdWNoZXM8L3NhbWw6Q29uZmlybWF0aW9uTWV0aG9kPgoJCQkJPHNhbWw6U3ViamVjdENvbmZpcm1hdGlvbkRhdGE+CgkJCQkJPHByOlBlcnNvbiBzaTp0eXBlPSJwcjpQaHlzaWNhbFBlcnNvblR5cGUiPjxwcjpJZGVudGlmaWNhdGlvbj48cHI6VmFsdWU+UlV4SFFWUmxjM1JRUWpCWVdGakZrSHBudzd4eVgxaFlXRlREdkhwbGE4T25hUT09PC9wcjpWYWx1ZT48cHI6VHlwZT51cm46cHVibGljaWQ6Z3YuYXQ6YmFzZWlkPC9wcjpUeXBlPjwvcHI6SWRlbnRpZmljYXRpb24+PHByOk5hbWU+PHByOkdpdmVuTmFtZT5YWFjFkHonZ8O8cjwvcHI6R2l2ZW5OYW1lPjxwcjpGYW1pbHlOYW1lIHByaW1hcnk9InVuZGVmaW5lZCI+WFhYVMO8emVrw6dpPC9wcjpGYW1pbHlOYW1lPjwvcHI6TmFtZT48cHI6RGF0ZU9mQmlydGg+MTk3My0wNi0wNDwvcHI6RGF0ZU9mQmlydGg+PC9wcjpQZXJzb24+CgkJCQk8L3NhbWw6U3ViamVjdENvbmZpcm1hdGlvbkRhdGE+CgkJCTwvc2FtbDpTdWJqZWN0Q29uZmlybWF0aW9uPgoJCTwvc2FtbDpTdWJqZWN0PgoJCTxzYW1sOkF0dHJpYnV0ZSBBdHRyaWJ1dGVOYW1lPSJDaXRpemVuUHVibGljS2V5IiBBdHRyaWJ1dGVOYW1lc3BhY2U9InVybjpwdWJsaWNpZDpndi5hdDpuYW1lc3BhY2VzOmlkZW50aXR5bGluazoxLjIiPjxzYW1sOkF0dHJpYnV0ZVZhbHVlPjxkc2lnOlJTQUtleVZhbHVlPjxkc2lnOk1vZHVsdXM+L1VLUkZIYkFhRWtnVmRnTTFTRE9KaldIcUszN3JKWVN0UHF0VVh6bzlWTm9yTzgzWW95emE5YjBkcDdtdVM4b2paMjRZRVBMUUZ3WQpCSVpkbTROSHJBNXZsVlZrRGV1Qng2bVRwRXBldTdkMkUzd3VZbVFXTjQxUXhWajZPcFhvSHRzek9jajd1Rm9mem1SR09PVUIzNUxDCkg2QzBMTFpJNTU5a3BPbmFxa2RLbU83dnduYVE0eTEwcHpCdjJ3U3BTZnY0djlIV3NCYUYxUWtYNmlmQ3lBbklLS3FKczR6S1RuK2EKR0kvS0FKOXdoam9GQk9yd1MzTlFpK1ZSVGxPYTdKdHdxeHBJZUYrT3c0R2wzaWdVb2szaGtsYlUyeElYcG5VeXNQYWhqUTBMNm5ORApZVHVmUC9jRmxrNWkvR1BZdmtONjJHd0Z4Rko1bDBoL1A3QWtJaCtWZmRCL0Q3SFVYaC9PV2dmek9MK2ZFRGdiL1dHM1BNenlObVFNCm5QQkdQb21hdGFOREtla0hhNUYwOUxFUHR5L0ZwMDUxLzFEUTZUMXhzamZ5ZG11aVZsWDZIRUZqZjFkYmQ4cUtGRm5TQ3NxRHBQdUQKR0hNcStKS0lmN25HQWtYSWxraTA1Nzd1bzM0MmxaeHBUVlRGVkFGdkJHS0Z6azNlQzMyT0NwOUo8L2RzaWc6TW9kdWx1cz48ZHNpZzpFeHBvbmVudD5BUUFCPC9kc2lnOkV4cG9uZW50PjwvZHNpZzpSU0FLZXlWYWx1ZT48L3NhbWw6QXR0cmlidXRlVmFsdWU+PC9zYW1sOkF0dHJpYnV0ZT48c2FtbDpBdHRyaWJ1dGUgQXR0cmlidXRlTmFtZT0iQ2l0aXplblB1YmxpY0tleSIgQXR0cmlidXRlTmFtZXNwYWNlPSJ1cm46cHVibGljaWQ6Z3YuYXQ6bmFtZXNwYWNlczppZGVudGl0eWxpbms6MS4yIj48c2FtbDpBdHRyaWJ1dGVWYWx1ZT48ZHNpZzpSU0FLZXlWYWx1ZT48ZHNpZzpNb2R1bHVzPnlQWGJhcEZhYXBycWlmVXVJaUxzR0FMaVdTTGRsUGNRN0VGZGZ5UzM0RVNJNGEyQnMwbUxTbm5FY1djeHJjWlgzcmxJUXBKaklwb1UKQStSRG9sNVBrU3BoSENMNkl2SVFNZmtreEg1Z0s2akN6VFNWOVJFVm1xUlRFMXNxUmNCUUduRFlwMjZwSFFoYzBHSG13NnVqeCtQTwp1dlE2Mm9hUUlxUXZ0T2ZLWFBReXlXTDE5clhXOTcrRUcweTBLd2VpOHRWY01uamJ5ZEtNL3Z5d01Fb3FFcU1mMEYrR0tjd3A3ZW50ClpzcnVEVEgrY0tJYnBXdUpLZzAwVUhraG45QWZkYlBXdzZWOWUrQmhxU0lYcTBoaEhmSkNBdzZwWXVYaVY2dE9ESlBGdnUxN1diQnQKV3B1ejJOR1RMU3Y3NXJlaklCa09TMk5MS0FmV3JhVmhUaDY3Vnc9PTwvZHNpZzpNb2R1bHVzPjxkc2lnOkV4cG9uZW50PkFRQUI8L2RzaWc6RXhwb25lbnQ+PC9kc2lnOlJTQUtleVZhbHVlPjwvc2FtbDpBdHRyaWJ1dGVWYWx1ZT48L3NhbWw6QXR0cmlidXRlPgoJPC9zYW1sOkF0dHJpYnV0ZVN0YXRlbWVudD4KPGRzaWc6U2lnbmF0dXJlIHhtbG5zOmRzaWc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyMiPjxkc2lnOlNpZ25lZEluZm8+PGRzaWc6Q2Fub25pY2FsaXphdGlvbk1ldGhvZCBBbGdvcml0aG09Imh0dHA6Ly93d3cudzMub3JnLzIwMDEvMTAveG1sLWV4Yy1jMTRuIyIvPjxkc2lnOlNpZ25hdHVyZU1ldGhvZCBBbGdvcml0aG09Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyNyc2Etc2hhMSIvPjxkc2lnOlJlZmVyZW5jZSBVUkk9IiI+PGRzaWc6VHJhbnNmb3Jtcz48ZHNpZzpUcmFuc2Zvcm0gQWxnb3JpdGhtPSJodHRwOi8vd3d3LnczLm9yZy9UUi8xOTk5L1JFQy14cGF0aC0xOTk5MTExNiI+PGRzaWc6WFBhdGg+bm90KGFuY2VzdG9yLW9yLXNlbGY6OnByOklkZW50aWZpY2F0aW9uKTwvZHNpZzpYUGF0aD48L2RzaWc6VHJhbnNmb3JtPjxkc2lnOlRyYW5zZm9ybSBBbGdvcml0aG09Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyNlbnZlbG9wZWQtc2lnbmF0dXJlIi8+PC9kc2lnOlRyYW5zZm9ybXM+PGRzaWc6RGlnZXN0TWV0aG9kIEFsZ29yaXRobT0iaHR0cDovL3d3dy53My5vcmcvMjAwMC8wOS94bWxkc2lnI3NoYTEiLz48ZHNpZzpEaWdlc3RWYWx1ZT43TmZyRUJKZGw4NTRyZG1BaDFjdFEyWDdXTWM9PC9kc2lnOkRpZ2VzdFZhbHVlPjwvZHNpZzpSZWZlcmVuY2U+PGRzaWc6UmVmZXJlbmNlIFR5cGU9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyNNYW5pZmVzdCIgVVJJPSIjbWFuaWZlc3QiPjxkc2lnOkRpZ2VzdE1ldGhvZCBBbGdvcml0aG09Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyNzaGExIi8+PGRzaWc6RGlnZXN0VmFsdWU+aGZnOHphM21ZcXU1UVNiVXpYSHhEZTUvU05FPTwvZHNpZzpEaWdlc3RWYWx1ZT48L2RzaWc6UmVmZXJlbmNlPjwvZHNpZzpTaWduZWRJbmZvPjxkc2lnOlNpZ25hdHVyZVZhbHVlPm11V2IzOVRhZ0NkM053V2N1NWlrRUp1SnBaZG5lZFJEY2RtMTdJWnYrT0VWRXRxeWxSdXIvd1g2QUdVQ1UvUFUKWm5DdWROR1ZwQ0hMWXpIaXBONWM4b2JtbmhsbElOb1NFTk81b3Y1amlNb05Lb2RBZXhKSU42bVpPREJkL1RtVAptNzBWaVd5ckdVTGJJWWwvd2hsdjFsZ2EzSjhjeDhLU29QejhTd05MMnF3VWoydG8vQWhnNGtjSmxxT3MyNVlNCk5YL3dhSW53NkRSN05HQ0pvRStaWlNwcEh3d1FtNnYrOUhZOUU4NnNlQkFBUHhJOU0xako0WldiMzI5akZ0aUEKcXZiOHM2anhyMmxsOHVWYWdxWENZaFg5K1dOUXdheXFZTCtPdzhPcGxVem9OMVRpS2hSbVFLWkl3S1lDMVo4eQpLK3ZqQWxRTzJhT05zNEhVaG9SNmQyNmUvTVUxZmJlWEhxVHpyZmI5R1hXSHl0dFRkanhiemtaQTFGODJsUUZvCjUrVnpjTUhRUmc3c0RKODY1Wk1zM3BwY2VoLzlaU2ZvT2Y1SFlEUFl1V2VjT0RpZ1pRWVh0TVlwdVBRVGsrQ20KczlaSkd6QlYybGVtZk5DOVFVNzh0Zm42cDFVWnJTTG5zWGFYbVVjOEVjNTNQaUhBT3Z6blh0QjVjRW5hV2daMgp1TGVGOEtTUmw2SjBlTlE5SkRQZ1NOMHNmYWxiVkNkaENUTlFtclJ0T2pVZjNlN3UzeElNelJ1Zm4wb2o2SHRwCnQzaEVESFhuSS9kTk1scHBSSXl4cGQxbFo5bXJYZklLcnJMZVdxdGd3cFB1OTRoVUhRL2VKejFrMy9IM0h6M2QKWkR4dkFFYzNTRERkb1FXeS9HUGZpcXNwRWZjbGd0SkNKQ2E4L2t2dTdSVT08L2RzaWc6U2lnbmF0dXJlVmFsdWU+PGRzaWc6S2V5SW5mbz48ZHNpZzpYNTA5RGF0YT48ZHNpZzpYNTA5Q2VydGlmaWNhdGU+TUlJRlpEQ0NBMHlnQXdJQkFnSUpBSmF2K3plcVUvRE1NQTBHQ1NxR1NJYjNEUUVCQ3dVQU1Gd3hDekFKQmdOVgpCQVlUQWtGVU1RMHdDd1lEVlFRS0V3UkZSMGxhTVJZd0ZBWURWUVFMRXcxVGIyWjBkMkZ5WlVOaGNtUnpNU1l3CkpBWURWUVFERkIxVVpYTjBYMU52Wm5SM1lYSmxZMkZ5WkhOZlNVUk1YMU5wWjI1bGNqQWVGdzB4TmpFd01UZ3gKTURNNU1EZGFGdzB4T1RBM01UUXhNRE01TURkYU1Gd3hDekFKQmdOVkJBWVRBa0ZVTVEwd0N3WURWUVFLRXdSRgpSMGxhTVJZd0ZBWURWUVFMRXcxVGIyWjBkMkZ5WlVOaGNtUnpNU1l3SkFZRFZRUURGQjFVWlhOMFgxTnZablIzCllYSmxZMkZ5WkhOZlNVUk1YMU5wWjI1bGNqQ0NBaUl3RFFZSktvWklodmNOQVFFQkJRQURnZ0lQQURDQ0Fnb0MKZ2dJQkFMa0xndCtNRlR4TGZSemNFSVowYnljSUZnN2cvSFBON1FXSVo2N2JIenJiNmVoZWJ6RjlWaW56RFpYQwprZktXZFVKYmtOU3VXS1dycDJYNjJmN29HaGRxSzB5RmMrRGxvK09wSURnUWlXQ3BCZktKbzhjUFdzaUFtTnVUCnhXVmFnVTVmYUkxaDd4dnZPVk15YldlOTJuaXZmcUxPdUV4Nld2WC9Vb0lhd1JIVjJWbVBHRmdab2NNNUcwWDYKYlVWRXBxeEFhM3FPSWxScjBwb0IrUkEwUEE4NmhScFJZYWwvT3I5M0Q4QmZRSDVsOHpWOVFjdlBlL0tlSlNwSgpIZ0dXbUVzNTkzTHROdUExUnYxaURwdXUxMHk3QzJGZU1CdmNVcFJrUjdXQWo3dklZVnRRSUxYQ2gxRmhmTjFiCkhnNnhMVlR5c2hsZ1VuN0FSUUpZb0ozdG9nZEdhbURSbG5LVTJyWE45ajg4VHc2ZkFkY0N2V2JXVnRqeThwTmoKV0xrVkpNbEZXZGZPNi81TEF2YTFIeFJPTWhGeDdRT1BoT3plbWV0Q3RUMmZJNEZUQWs5VnlmOXdUVVFPTDhzcQpLNzN0MUE0MTlsWVM4V3VVQ3pIRHhMdWpMaVR1d29JVWd6TU4vYnFNRVpyb2dQTFkyS2o0dm1aTVo0Z1UyUFU3Cll3K1hmYW5nMysveUsxZ1lORWVicGR2UGk4U1ZVQW51cy9DZm1kd2RuOU8vbmFXaUJwamMwNkdKdk1iZWdqeHcKb1BCTTVjMFNrQ1I1eENheWdaTDJPQnBSTUtnZGZyazRrMHBqNVpVbSttdHJPR29qdFJaSkVaUUNCcFZQazF5RAozTDQvWjRBWm9mT284ZFNrVVIreEpOMG9LbklkZm5kdkJ4TkY0c3hZNEl3T3ZGUnJBZ01CQUFHaktUQW5NQWtHCkExVWRFd1FDTUFBd0N3WURWUjBQQkFRREFnV2dNQTBHQnlvb0FBb0JCd0VFQWdVQU1BMEdDU3FHU0liM0RRRUIKQ3dVQUE0SUNBUUJjRUQ3dEU4cW1Bd0ZCZGh5b3oxRDh5b2RFWm1tZFhad2tzQS9rSStvKzV3UXM2WS9xdnc3agorZUJ2bGN0eVhDWFdoMWVGZWIvRmFpQTVDcG9hazhOYy9vWTdUL3lCajVnZktIbE5xVlQxb3dhQmtIc0VZTUJ2CmFVWHh5RENibkZNem5KZmt4amJ2RmJRZGQxaGNlSmh0OER4K2lrcEI2TUpIcUhJRXJ5MFdXZ2YzSmRONVBFcnIKQVRuZGpCRTRCYVRaMnE2c0N2K1NkSzYwTWswbVlBNmw2blNDOWVCOEc5QzRiQTFjUUVPdTYrRlBtRnpTa2lJRgp0ZW1BMXRqUW5oeEtaWmlnenhJTjNFUUFucS8yM2pmK0NreEF0NUdrcFVqcUY1YnFLSTFuZXJKT2duNEptNWo2CnNQWkdwR2xsekhMQmF5YmZZNjNBejRzRVJDMjhPbHFGdzF2eFFzNGhXSVdOV0VBTUYzT3o0K3BZZzRPSUloNUMKTnIxYXFKZ3NzV2ZPWnJYMktTejJ2cXJab1U2N3pxODRNUWNKVFNtZ0tWQmI5T25yQzV0WW41WVZVbHlkUFBqcgpVbTBpSGxXQzBNRmlJZ1N6eDZUaTJIblBnYzBVSHNBNklwU1RvK1V1ZllZTkRpRkNzc1JidTRyMC9TeXE0TVAzCmdoWVhkUDlUajBGSVN6MlR2TTZZUWZ6SGVqOTRiWmNWTnduRjRwV0VuR1p0QmJOVnZKUnc5aUpISGtEV0xpWU0KMUI3M3pzNytwQThZZ0txRXhESFhjMVNob3U1SHZTdVRYU21hVE1VSHJDa2hvdEhmcHFZaHJKaUFtSitPZnROdgo2b3hNUGZOaFpnMDFlT290bTFKK1dWMm1KYmdjUFROU0MxT05jU0ZkUTV2WlpMTDI0SjJIY3c9PTwvZHNpZzpYNTA5Q2VydGlmaWNhdGU+PC9kc2lnOlg1MDlEYXRhPjwvZHNpZzpLZXlJbmZvPjxkc2lnOk9iamVjdD48ZHNpZzpNYW5pZmVzdCBJZD0ibWFuaWZlc3QiPjxkc2lnOlJlZmVyZW5jZSBVUkk9IiI+PGRzaWc6VHJhbnNmb3Jtcz48ZHNpZzpUcmFuc2Zvcm0gQWxnb3JpdGhtPSJodHRwOi8vd3d3LnczLm9yZy9UUi8xOTk5L1JFQy14cGF0aC0xOTk5MTExNiI+PGRzaWc6WFBhdGggeG1sbnM6ZHNpZz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC8wOS94bWxkc2lnIyI+bm90KGFuY2VzdG9yLW9yLXNlbGY6OmRzaWc6U2lnbmF0dXJlKTwvZHNpZzpYUGF0aD48L2RzaWc6VHJhbnNmb3JtPjwvZHNpZzpUcmFuc2Zvcm1zPjxkc2lnOkRpZ2VzdE1ldGhvZCBBbGdvcml0aG09Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyNzaGExIi8+PGRzaWc6RGlnZXN0VmFsdWU+QXN4VHprWmRBWUM0U0s1cTh5c0pLVDd5ZHVRPTwvZHNpZzpEaWdlc3RWYWx1ZT48L2RzaWc6UmVmZXJlbmNlPjwvZHNpZzpNYW5pZmVzdD48L2RzaWc6T2JqZWN0PjwvZHNpZzpTaWduYXR1cmU+PC9zYW1sOkFzc2VydGlvbj4="; - - protected IAttributeGenerator g = new SimpleStringAttributeGenerator(); - protected static DummySPConfiguration spConfig = null; - - private final static Map spConfigMap = new HashMap(); - private final static TestRequestImpl pendingReq = new TestRequestImpl(); - - - - @BeforeClass - public static void intialize() throws EAAFParserException, EAAFStorageException { - spConfigMap.put("target", "urn:publicid:gv.at:cdid+ZP-MH"); - - spConfig = new DummySPConfiguration(spConfigMap, new DummyConfiguration()); - pendingReq.setSpConfig(spConfig); - - final HashMap sessionStore = new HashMap(); - final AuthProcessDataWrapper wrapper = new AuthProcessDataWrapper(sessionStore); - wrapper.setIdentityLink(new SimpleIdentityLinkAssertionParser(new ByteArrayInputStream(Base64Utils.decode(DUMMY_IDL_2.getBytes()))).parseIdentityLink()); - pendingReq.setRawDataToTransaction(sessionStore); - - - } - - protected void putIntoSPConfigMap(String key, String value) { - spConfigMap.put(key, value); - - } - - protected IAuthData buildAuthData() throws Exception { - try { - return authBuilder.buildAuthenticationData(pendingReq); - - } catch (final Exception e) { - e.printStackTrace(); - throw e; - - } - - } - + @Autowired + private TestAuthenticationDataBuilder authBuilder; + private static final String DUMMY_IDL_2 = + "PHNhbWw6QXNzZXJ0aW9uIEFzc2VydGlvbklEPSJlbGdhdGVzdC5lZ2l6Lmd2LmF0LUFzc2VydGlvbklEWFhYxZB6Z8O8" + + "cl9YWFhUw7x6ZWvDp2kiIElzc3VlSW5zdGFudD0iMjAxOS0wMy0wNFQxNTo1MzowNCswMTowMCIgSXNzdWVyPSJodH" + + "RwOi8vcG9ydGFsLmJtaS5ndi5hdC9yZWYvc3pyL2lzc3VlciIgTWFqb3JWZXJzaW9uPSIxIiBNaW5vclZlcnNpb249" + + "IjAiIHhtbG5zOmRzaWc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyMiIHhtbG5zOmVjZHNhPSJodH" + + "RwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSMiIHhtbG5zOnByPSJodHRwOi8vcmVmZXJlbmNlLmUt" + + "Z292ZXJubWVudC5ndi5hdC9uYW1lc3BhY2UvcGVyc29uZGF0YS8yMDAyMDIyOCMiIHhtbG5zOnNhbWw9InVybjpvYX" + + "NpczpuYW1lczp0YzpTQU1MOjEuMDphc3NlcnRpb24iIHhtbG5zOnNpPSJodHRwOi8vd3d3LnczLm9yZy8yMDAxL1hN" + + "TFNjaGVtYS1pbnN0YW5jZSI+Cgk8c2FtbDpBdHRyaWJ1dGVTdGF0ZW1lbnQ+CgkJPHNhbWw6U3ViamVjdD4KCQkJPH" + + "NhbWw6U3ViamVjdENvbmZpcm1hdGlvbj4KCQkJCTxzYW1sOkNvbmZpcm1hdGlvbk1ldGhvZD51cm46b2FzaXM6bmFt" + + "ZXM6dGM6U0FNTDoxLjA6Y206c2VuZGVyLXZvdWNoZXM8L3NhbWw6Q29uZmlybWF0aW9uTWV0aG9kPgoJCQkJPHNhbW" + + "w6U3ViamVjdENvbmZpcm1hdGlvbkRhdGE+CgkJCQkJPHByOlBlcnNvbiBzaTp0eXBlPSJwcjpQaHlzaWNhbFBlcnNv" + + "blR5cGUiPjxwcjpJZGVudGlmaWNhdGlvbj48cHI6VmFsdWU+UlV4SFFWUmxjM1JRUWpCWVdGakZrSHBudzd4eVgxaF" + + "lXRlREdkhwbGE4T25hUT09PC9wcjpWYWx1ZT48cHI6VHlwZT51cm46cHVibGljaWQ6Z3YuYXQ6YmFzZWlkPC9wcjpU" + + "eXBlPjwvcHI6SWRlbnRpZmljYXRpb24+PHByOk5hbWU+PHByOkdpdmVuTmFtZT5YWFjFkHonZ8O8cjwvcHI6R2l2ZW" + + "5OYW1lPjxwcjpGYW1pbHlOYW1lIHByaW1hcnk9InVuZGVmaW5lZCI+WFhYVMO8emVrw6dpPC9wcjpGYW1pbHlOYW1l" + + "PjwvcHI6TmFtZT48cHI6RGF0ZU9mQmlydGg+MTk3My0wNi0wNDwvcHI6RGF0ZU9mQmlydGg+PC9wcjpQZXJzb24+Cg" + + "kJCQk8L3NhbWw6U3ViamVjdENvbmZpcm1hdGlvbkRhdGE+CgkJCTwvc2FtbDpTdWJqZWN0Q29uZmlybWF0aW9uPgoJ" + + "CTwvc2FtbDpTdWJqZWN0PgoJCTxzYW1sOkF0dHJpYnV0ZSBBdHRyaWJ1dGVOYW1lPSJDaXRpemVuUHVibGljS2V5Ii" + + "BBdHRyaWJ1dGVOYW1lc3BhY2U9InVybjpwdWJsaWNpZDpndi5hdDpuYW1lc3BhY2VzOmlkZW50aXR5bGluazoxLjIi" + + "PjxzYW1sOkF0dHJpYnV0ZVZhbHVlPjxkc2lnOlJTQUtleVZhbHVlPjxkc2lnOk1vZHVsdXM+L1VLUkZIYkFhRWtnVm" + + "RnTTFTRE9KaldIcUszN3JKWVN0UHF0VVh6bzlWTm9yTzgzWW95emE5YjBkcDdtdVM4b2paMjRZRVBMUUZ3WQpCSVpk" + + "bTROSHJBNXZsVlZrRGV1Qng2bVRwRXBldTdkMkUzd3VZbVFXTjQxUXhWajZPcFhvSHRzek9jajd1Rm9mem1SR09PVU" + + "IzNUxDCkg2QzBMTFpJNTU5a3BPbmFxa2RLbU83dnduYVE0eTEwcHpCdjJ3U3BTZnY0djlIV3NCYUYxUWtYNmlmQ3lB" + + "bklLS3FKczR6S1RuK2EKR0kvS0FKOXdoam9GQk9yd1MzTlFpK1ZSVGxPYTdKdHdxeHBJZUYrT3c0R2wzaWdVb2szaG" + + "tsYlUyeElYcG5VeXNQYWhqUTBMNm5ORApZVHVmUC9jRmxrNWkvR1BZdmtONjJHd0Z4Rko1bDBoL1A3QWtJaCtWZmRC" + + "L0Q3SFVYaC9PV2dmek9MK2ZFRGdiL1dHM1BNenlObVFNCm5QQkdQb21hdGFOREtla0hhNUYwOUxFUHR5L0ZwMDUxLz" + + "FEUTZUMXhzamZ5ZG11aVZsWDZIRUZqZjFkYmQ4cUtGRm5TQ3NxRHBQdUQKR0hNcStKS0lmN25HQWtYSWxraTA1Nzd1" + + "bzM0MmxaeHBUVlRGVkFGdkJHS0Z6azNlQzMyT0NwOUo8L2RzaWc6TW9kdWx1cz48ZHNpZzpFeHBvbmVudD5BUUFCPC" + + "9kc2lnOkV4cG9uZW50PjwvZHNpZzpSU0FLZXlWYWx1ZT48L3NhbWw6QXR0cmlidXRlVmFsdWU+PC9zYW1sOkF0dHJp" + + "YnV0ZT48c2FtbDpBdHRyaWJ1dGUgQXR0cmlidXRlTmFtZT0iQ2l0aXplblB1YmxpY0tleSIgQXR0cmlidXRlTmFtZX" + + "NwYWNlPSJ1cm46cHVibGljaWQ6Z3YuYXQ6bmFtZXNwYWNlczppZGVudGl0eWxpbms6MS4yIj48c2FtbDpBdHRyaWJ1" + + "dGVWYWx1ZT48ZHNpZzpSU0FLZXlWYWx1ZT48ZHNpZzpNb2R1bHVzPnlQWGJhcEZhYXBycWlmVXVJaUxzR0FMaVdTTG" + + "RsUGNRN0VGZGZ5UzM0RVNJNGEyQnMwbUxTbm5FY1djeHJjWlgzcmxJUXBKaklwb1UKQStSRG9sNVBrU3BoSENMNkl2" + + "SVFNZmtreEg1Z0s2akN6VFNWOVJFVm1xUlRFMXNxUmNCUUduRFlwMjZwSFFoYzBHSG13NnVqeCtQTwp1dlE2Mm9hUU" + + "lxUXZ0T2ZLWFBReXlXTDE5clhXOTcrRUcweTBLd2VpOHRWY01uamJ5ZEtNL3Z5d01Fb3FFcU1mMEYrR0tjd3A3ZW50" + + "ClpzcnVEVEgrY0tJYnBXdUpLZzAwVUhraG45QWZkYlBXdzZWOWUrQmhxU0lYcTBoaEhmSkNBdzZwWXVYaVY2dE9ESl" + + "BGdnUxN1diQnQKV3B1ejJOR1RMU3Y3NXJlaklCa09TMk5MS0FmV3JhVmhUaDY3Vnc9PTwvZHNpZzpNb2R1bHVzPjxk" + + "c2lnOkV4cG9uZW50PkFRQUI8L2RzaWc6RXhwb25lbnQ+PC9kc2lnOlJTQUtleVZhbHVlPjwvc2FtbDpBdHRyaWJ1dG" + + "VWYWx1ZT48L3NhbWw6QXR0cmlidXRlPgoJPC9zYW1sOkF0dHJpYnV0ZVN0YXRlbWVudD4KPGRzaWc6U2lnbmF0dXJl" + + "IHhtbG5zOmRzaWc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyMiPjxkc2lnOlNpZ25lZEluZm8+PG" + + "RzaWc6Q2Fub25pY2FsaXphdGlvbk1ldGhvZCBBbGdvcml0aG09Imh0dHA6Ly93d3cudzMub3JnLzIwMDEvMTAveG1s" + + "LWV4Yy1jMTRuIyIvPjxkc2lnOlNpZ25hdHVyZU1ldGhvZCBBbGdvcml0aG09Imh0dHA6Ly93d3cudzMub3JnLzIwMD" + + "AvMDkveG1sZHNpZyNyc2Etc2hhMSIvPjxkc2lnOlJlZmVyZW5jZSBVUkk9IiI+PGRzaWc6VHJhbnNmb3Jtcz48ZHNp" + + "ZzpUcmFuc2Zvcm0gQWxnb3JpdGhtPSJodHRwOi8vd3d3LnczLm9yZy9UUi8xOTk5L1JFQy14cGF0aC0xOTk5MTExNi" + + "I+PGRzaWc6WFBhdGg+bm90KGFuY2VzdG9yLW9yLXNlbGY6OnByOklkZW50aWZpY2F0aW9uKTwvZHNpZzpYUGF0aD48" + + "L2RzaWc6VHJhbnNmb3JtPjxkc2lnOlRyYW5zZm9ybSBBbGdvcml0aG09Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMD" + + "kveG1sZHNpZyNlbnZlbG9wZWQtc2lnbmF0dXJlIi8+PC9kc2lnOlRyYW5zZm9ybXM+PGRzaWc6RGlnZXN0TWV0aG9k" + + "IEFsZ29yaXRobT0iaHR0cDovL3d3dy53My5vcmcvMjAwMC8wOS94bWxkc2lnI3NoYTEiLz48ZHNpZzpEaWdlc3RWYW" + + "x1ZT43TmZyRUJKZGw4NTRyZG1BaDFjdFEyWDdXTWM9PC9kc2lnOkRpZ2VzdFZhbHVlPjwvZHNpZzpSZWZlcmVuY2U+" + + "PGRzaWc6UmVmZXJlbmNlIFR5cGU9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyNNYW5pZmVzdCIgVV" + + "JJPSIjbWFuaWZlc3QiPjxkc2lnOkRpZ2VzdE1ldGhvZCBBbGdvcml0aG09Imh0dHA6Ly93d3cudzMub3JnLzIwMDAv" + + "MDkveG1sZHNpZyNzaGExIi8+PGRzaWc6RGlnZXN0VmFsdWU+aGZnOHphM21ZcXU1UVNiVXpYSHhEZTUvU05FPTwvZH" + + "NpZzpEaWdlc3RWYWx1ZT48L2RzaWc6UmVmZXJlbmNlPjwvZHNpZzpTaWduZWRJbmZvPjxkc2lnOlNpZ25hdHVyZVZh" + + "bHVlPm11V2IzOVRhZ0NkM053V2N1NWlrRUp1SnBaZG5lZFJEY2RtMTdJWnYrT0VWRXRxeWxSdXIvd1g2QUdVQ1UvUF" + + "UKWm5DdWROR1ZwQ0hMWXpIaXBONWM4b2JtbmhsbElOb1NFTk81b3Y1amlNb05Lb2RBZXhKSU42bVpPREJkL1RtVApt" + + "NzBWaVd5ckdVTGJJWWwvd2hsdjFsZ2EzSjhjeDhLU29QejhTd05MMnF3VWoydG8vQWhnNGtjSmxxT3MyNVlNCk5YL3" + + "dhSW53NkRSN05HQ0pvRStaWlNwcEh3d1FtNnYrOUhZOUU4NnNlQkFBUHhJOU0xako0WldiMzI5akZ0aUEKcXZiOHM2" + + "anhyMmxsOHVWYWdxWENZaFg5K1dOUXdheXFZTCtPdzhPcGxVem9OMVRpS2hSbVFLWkl3S1lDMVo4eQpLK3ZqQWxRTz" + + "JhT05zNEhVaG9SNmQyNmUvTVUxZmJlWEhxVHpyZmI5R1hXSHl0dFRkanhiemtaQTFGODJsUUZvCjUrVnpjTUhRUmc3" + + "c0RKODY1Wk1zM3BwY2VoLzlaU2ZvT2Y1SFlEUFl1V2VjT0RpZ1pRWVh0TVlwdVBRVGsrQ20KczlaSkd6QlYybGVtZk" + + "5DOVFVNzh0Zm42cDFVWnJTTG5zWGFYbVVjOEVjNTNQaUhBT3Z6blh0QjVjRW5hV2daMgp1TGVGOEtTUmw2SjBlTlE5" + + "SkRQZ1NOMHNmYWxiVkNkaENUTlFtclJ0T2pVZjNlN3UzeElNelJ1Zm4wb2o2SHRwCnQzaEVESFhuSS9kTk1scHBSSX" + + "l4cGQxbFo5bXJYZklLcnJMZVdxdGd3cFB1OTRoVUhRL2VKejFrMy9IM0h6M2QKWkR4dkFFYzNTRERkb1FXeS9HUGZp" + + "cXNwRWZjbGd0SkNKQ2E4L2t2dTdSVT08L2RzaWc6U2lnbmF0dXJlVmFsdWU+PGRzaWc6S2V5SW5mbz48ZHNpZzpYNT" + + "A5RGF0YT48ZHNpZzpYNTA5Q2VydGlmaWNhdGU+TUlJRlpEQ0NBMHlnQXdJQkFnSUpBSmF2K3plcVUvRE1NQTBHQ1Nx" + + "R1NJYjNEUUVCQ3dVQU1Gd3hDekFKQmdOVgpCQVlUQWtGVU1RMHdDd1lEVlFRS0V3UkZSMGxhTVJZd0ZBWURWUVFMRX" + + "cxVGIyWjBkMkZ5WlVOaGNtUnpNU1l3CkpBWURWUVFERkIxVVpYTjBYMU52Wm5SM1lYSmxZMkZ5WkhOZlNVUk1YMU5w" + + "WjI1bGNqQWVGdzB4TmpFd01UZ3gKTURNNU1EZGFGdzB4T1RBM01UUXhNRE01TURkYU1Gd3hDekFKQmdOVkJBWVRBa0" + + "ZVTVEwd0N3WURWUVFLRXdSRgpSMGxhTVJZd0ZBWURWUVFMRXcxVGIyWjBkMkZ5WlVOaGNtUnpNU1l3SkFZRFZRUURG" + + "QjFVWlhOMFgxTnZablIzCllYSmxZMkZ5WkhOZlNVUk1YMU5wWjI1bGNqQ0NBaUl3RFFZSktvWklodmNOQVFFQkJRQU" + + "RnZ0lQQURDQ0Fnb0MKZ2dJQkFMa0xndCtNRlR4TGZSemNFSVowYnljSUZnN2cvSFBON1FXSVo2N2JIenJiNmVoZWJ6" + + "RjlWaW56RFpYQwprZktXZFVKYmtOU3VXS1dycDJYNjJmN29HaGRxSzB5RmMrRGxvK09wSURnUWlXQ3BCZktKbzhjUF" + + "dzaUFtTnVUCnhXVmFnVTVmYUkxaDd4dnZPVk15YldlOTJuaXZmcUxPdUV4Nld2WC9Vb0lhd1JIVjJWbVBHRmdab2NN" + + "NUcwWDYKYlVWRXBxeEFhM3FPSWxScjBwb0IrUkEwUEE4NmhScFJZYWwvT3I5M0Q4QmZRSDVsOHpWOVFjdlBlL0tlSl" + + "NwSgpIZ0dXbUVzNTkzTHROdUExUnYxaURwdXUxMHk3QzJGZU1CdmNVcFJrUjdXQWo3dklZVnRRSUxYQ2gxRmhmTjFi" + + "CkhnNnhMVlR5c2hsZ1VuN0FSUUpZb0ozdG9nZEdhbURSbG5LVTJyWE45ajg4VHc2ZkFkY0N2V2JXVnRqeThwTmoKV0" + + "xrVkpNbEZXZGZPNi81TEF2YTFIeFJPTWhGeDdRT1BoT3plbWV0Q3RUMmZJNEZUQWs5VnlmOXdUVVFPTDhzcQpLNzN0" + + "MUE0MTlsWVM4V3VVQ3pIRHhMdWpMaVR1d29JVWd6TU4vYnFNRVpyb2dQTFkyS2o0dm1aTVo0Z1UyUFU3Cll3K1hmYW" + + "5nMysveUsxZ1lORWVicGR2UGk4U1ZVQW51cy9DZm1kd2RuOU8vbmFXaUJwamMwNkdKdk1iZWdqeHcKb1BCTTVjMFNr" + + "Q1I1eENheWdaTDJPQnBSTUtnZGZyazRrMHBqNVpVbSttdHJPR29qdFJaSkVaUUNCcFZQazF5RAozTDQvWjRBWm9mT2" + + "84ZFNrVVIreEpOMG9LbklkZm5kdkJ4TkY0c3hZNEl3T3ZGUnJBZ01CQUFHaktUQW5NQWtHCkExVWRFd1FDTUFBd0N3" + + "WURWUjBQQkFRREFnV2dNQTBHQnlvb0FBb0JCd0VFQWdVQU1BMEdDU3FHU0liM0RRRUIKQ3dVQUE0SUNBUUJjRUQ3dE" + + "U4cW1Bd0ZCZGh5b3oxRDh5b2RFWm1tZFhad2tzQS9rSStvKzV3UXM2WS9xdnc3agorZUJ2bGN0eVhDWFdoMWVGZWIv" + + "RmFpQTVDcG9hazhOYy9vWTdUL3lCajVnZktIbE5xVlQxb3dhQmtIc0VZTUJ2CmFVWHh5RENibkZNem5KZmt4amJ2Rm" + + "JRZGQxaGNlSmh0OER4K2lrcEI2TUpIcUhJRXJ5MFdXZ2YzSmRONVBFcnIKQVRuZGpCRTRCYVRaMnE2c0N2K1NkSzYw" + + "TWswbVlBNmw2blNDOWVCOEc5QzRiQTFjUUVPdTYrRlBtRnpTa2lJRgp0ZW1BMXRqUW5oeEtaWmlnenhJTjNFUUFucS" + + "8yM2pmK0NreEF0NUdrcFVqcUY1YnFLSTFuZXJKT2duNEptNWo2CnNQWkdwR2xsekhMQmF5YmZZNjNBejRzRVJDMjhP" + + "bHFGdzF2eFFzNGhXSVdOV0VBTUYzT3o0K3BZZzRPSUloNUMKTnIxYXFKZ3NzV2ZPWnJYMktTejJ2cXJab1U2N3pxOD" + + "RNUWNKVFNtZ0tWQmI5T25yQzV0WW41WVZVbHlkUFBqcgpVbTBpSGxXQzBNRmlJZ1N6eDZUaTJIblBnYzBVSHNBNklw" + + "U1RvK1V1ZllZTkRpRkNzc1JidTRyMC9TeXE0TVAzCmdoWVhkUDlUajBGSVN6MlR2TTZZUWZ6SGVqOTRiWmNWTnduRj" + + "RwV0VuR1p0QmJOVnZKUnc5aUpISGtEV0xpWU0KMUI3M3pzNytwQThZZ0txRXhESFhjMVNob3U1SHZTdVRYU21hVE1V" + + "SHJDa2hvdEhmcHFZaHJKaUFtSitPZnROdgo2b3hNUGZOaFpnMDFlT290bTFKK1dWMm1KYmdjUFROU0MxT05jU0ZkUT" + + "V2WlpMTDI0SjJIY3c9PTwvZHNpZzpYNTA5Q2VydGlmaWNhdGU+PC9kc2lnOlg1MDlEYXRhPjwvZHNpZzpLZXlJbmZv" + + "Pjxkc2lnOk9iamVjdD48ZHNpZzpNYW5pZmVzdCBJZD0ibWFuaWZlc3QiPjxkc2lnOlJlZmVyZW5jZSBVUkk9IiI+PG" + + "RzaWc6VHJhbnNmb3Jtcz48ZHNpZzpUcmFuc2Zvcm0gQWxnb3JpdGhtPSJodHRwOi8vd3d3LnczLm9yZy9UUi8xOTk5" + + "L1JFQy14cGF0aC0xOTk5MTExNiI+PGRzaWc6WFBhdGggeG1sbnM6ZHNpZz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC" + + "8wOS94bWxkc2lnIyI+bm90KGFuY2VzdG9yLW9yLXNlbGY6OmRzaWc6U2lnbmF0dXJlKTwvZHNpZzpYUGF0aD48L2Rz" + + "aWc6VHJhbnNmb3JtPjwvZHNpZzpUcmFuc2Zvcm1zPjxkc2lnOkRpZ2VzdE1ldGhvZCBBbGdvcml0aG09Imh0dHA6Ly" + + "93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyNzaGExIi8+PGRzaWc6RGlnZXN0VmFsdWU+QXN4VHprWmRBWUM0U0s1" + + "cTh5c0pLVDd5ZHVRPTwvZHNpZzpEaWdlc3RWYWx1ZT48L2RzaWc6UmVmZXJlbmNlPjwvZHNpZzpNYW5pZmVzdD48L2" + + "RzaWc6T2JqZWN0PjwvZHNpZzpTaWduYXR1cmU+PC9zYW1sOkFzc2VydGlvbj4="; + + protected IAttributeGenerator gen = new SimpleStringAttributeGenerator(); + protected static DummySpConfiguration spConfig = null; + + private static final Map spConfigMap = new HashMap<>(); + private static final TestRequestImpl pendingReq = new TestRequestImpl(); + + + + /** + * jUnit class initializer. + * + * @throws EaafParserException In case of an error + * @throws EaafStorageException In case of an error + */ + @BeforeClass + public static void intialize() throws EaafParserException, EaafStorageException { + spConfigMap.put("target", "urn:publicid:gv.at:cdid+ZP-MH"); + + spConfig = new DummySpConfiguration(spConfigMap, new DummyConfiguration()); + pendingReq.setSpConfig(spConfig); + + final HashMap sessionStore = new HashMap<>(); + final AuthProcessDataWrapper wrapper = new AuthProcessDataWrapper(sessionStore); + wrapper.setIdentityLink(new SimpleIdentityLinkAssertionParser( + new ByteArrayInputStream(Base64Utils.decode(DUMMY_IDL_2.getBytes()))).parseIdentityLink()); + pendingReq.setRawDataToTransaction(sessionStore); + + + } + + protected void putIntoSpConfigMap(final String key, final String value) { + spConfigMap.put(key, value); + + } + + protected IAuthData buildAuthData() throws Exception { + try { + return authBuilder.buildAuthenticationData(pendingReq); + + } catch (final Exception e) { + e.printStackTrace(); + throw e; + + } + + } + } diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/attributes/BirthdayAttrBuilderTest.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/attributes/BirthdayAttrBuilderTest.java index 5f1913a3..7be691d2 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/attributes/BirthdayAttrBuilderTest.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/attributes/BirthdayAttrBuilderTest.java @@ -16,24 +16,26 @@ import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.BirthdateAttributeBuilde @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/SpringTest-context_eaaf_core.xml") -public class BirthdayAttrBuilderTest extends AbstractAttributeBuilderTest{ - - private final IAttributeBuilder attrBuilde = new BirthdateAttributeBuilder(); - - @Test - public void performTest_ok() { - try { - final IAuthData authData = buildAuthData(); - final String value = attrBuilde.build(spConfig, authData, g); - - final DateFormat format = new SimpleDateFormat(PVPAttributeDefinitions.BIRTHDATE_FORMAT_PATTERN); - Assert.assertEquals("Birthday does NOT match", authData.getDateOfBirth(), format.parse(value)); - - } catch (final Exception e) { - Assert.assertTrue("Attr. builder has an exception", e == null); - - } - - } +public class BirthdayAttrBuilderTest extends AbstractAttributeBuilderTest { + + private final IAttributeBuilder attrBuilde = new BirthdateAttributeBuilder(); + + @Test + public void performTest_ok() { + try { + final IAuthData authData = buildAuthData(); + final String value = attrBuilde.build(spConfig, authData, gen); + + final DateFormat format = + new SimpleDateFormat(PVPAttributeDefinitions.BIRTHDATE_FORMAT_PATTERN); + Assert.assertEquals("Birthday does NOT match", authData.getDateOfBirth(), + format.parse(value)); + + } catch (final Exception e) { + Assert.assertTrue("Attr. builder has an exception", e == null); + + } + + } } diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/attributes/FamilyNameAttrBuilderTest.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/attributes/FamilyNameAttrBuilderTest.java index 51a6a2c2..ea3c12dd 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/attributes/FamilyNameAttrBuilderTest.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/attributes/FamilyNameAttrBuilderTest.java @@ -16,57 +16,61 @@ import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PrincipalNameAttributeBu @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/SpringTest-context_eaaf_core.xml") -public class FamilyNameAttrBuilderTest extends AbstractAttributeBuilderTest{ - - private final IAttributeBuilder attrBuilde = new PrincipalNameAttributeBuilder(); - - @Test - public void performTest_ok() { - try { - final IAuthData authData = buildAuthData(); - final String value = attrBuilde.build(spConfig, authData, g); - Assert.assertEquals("FamilyName does NOT match", authData.getFamilyName(), value); - - } catch (final Exception e) { - Assert.assertTrue("Attr. builder has an exception", e == null); - - } - - } - - @Test - public void performTest_null() { - try { - final AuthenticationData authData = (AuthenticationData) buildAuthData(); - authData.setFamilyName(null); - - attrBuilde.build(spConfig, authData, g); - Assert.assertTrue("Attr. Builder provide no 'UnavailableAttributeException'", false); - - } catch (final Exception e) { - Assert.assertTrue("Attr. builder provide wrong exception", e instanceof UnavailableAttributeException); - Assert.assertEquals("Attr. name in exception does NOT match", - PVPAttributeDefinitions.PRINCIPAL_NAME_NAME, ((UnavailableAttributeException) e).getAttributeName()); - - } - - } - - @Test - public void performTest_emtpty() { - try { - final AuthenticationData authData = (AuthenticationData) buildAuthData(); - authData.setFamilyName(StringUtils.EMPTY); - - attrBuilde.build(spConfig, authData, g); - Assert.assertTrue("Attr. Builder provide no 'UnavailableAttributeException'", false); - - } catch (final Exception e) { - Assert.assertTrue("Attr. builder provide wrong exception", e instanceof UnavailableAttributeException); - Assert.assertEquals("Attr. name in exception does NOT match", - PVPAttributeDefinitions.PRINCIPAL_NAME_NAME, ((UnavailableAttributeException) e).getAttributeName()); - - } - - } +public class FamilyNameAttrBuilderTest extends AbstractAttributeBuilderTest { + + private final IAttributeBuilder attrBuilde = new PrincipalNameAttributeBuilder(); + + @Test + public void performTest_ok() { + try { + final IAuthData authData = buildAuthData(); + final String value = attrBuilde.build(spConfig, authData, gen); + Assert.assertEquals("FamilyName does NOT match", authData.getFamilyName(), value); + + } catch (final Exception e) { + Assert.assertTrue("Attr. builder has an exception", e == null); + + } + + } + + @Test + public void performTest_null() { + try { + final AuthenticationData authData = (AuthenticationData) buildAuthData(); + authData.setFamilyName(null); + + attrBuilde.build(spConfig, authData, gen); + Assert.assertTrue("Attr. Builder provide no 'UnavailableAttributeException'", false); + + } catch (final Exception e) { + Assert.assertTrue("Attr. builder provide wrong exception", + e instanceof UnavailableAttributeException); + Assert.assertEquals("Attr. name in exception does NOT match", + PVPAttributeDefinitions.PRINCIPAL_NAME_NAME, + ((UnavailableAttributeException) e).getAttributeName()); + + } + + } + + @Test + public void performTest_emtpty() { + try { + final AuthenticationData authData = (AuthenticationData) buildAuthData(); + authData.setFamilyName(StringUtils.EMPTY); + + attrBuilde.build(spConfig, authData, gen); + Assert.assertTrue("Attr. Builder provide no 'UnavailableAttributeException'", false); + + } catch (final Exception e) { + Assert.assertTrue("Attr. builder provide wrong exception", + e instanceof UnavailableAttributeException); + Assert.assertEquals("Attr. name in exception does NOT match", + PVPAttributeDefinitions.PRINCIPAL_NAME_NAME, + ((UnavailableAttributeException) e).getAttributeName()); + + } + + } } diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/attributes/GivenNameAttrBuilderTest.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/attributes/GivenNameAttrBuilderTest.java index dd1dfa5e..62324491 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/attributes/GivenNameAttrBuilderTest.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/auth/attributes/GivenNameAttrBuilderTest.java @@ -16,57 +16,61 @@ import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.GivenNameAttributeBuilde @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/SpringTest-context_eaaf_core.xml") -public class GivenNameAttrBuilderTest extends AbstractAttributeBuilderTest{ - - private final IAttributeBuilder attrBuilde = new GivenNameAttributeBuilder(); - - @Test - public void performTest_ok() { - try { - final IAuthData authData = buildAuthData(); - final String value = attrBuilde.build(spConfig, authData, g); - Assert.assertEquals("GivenName does NOT match", authData.getGivenName(), value); - - } catch (final Exception e) { - Assert.assertTrue("Attr. builder has an exception", e == null); - - } - - } - - @Test - public void performTest_null() { - try { - final AuthenticationData authData = (AuthenticationData) buildAuthData(); - authData.setGivenName(null); - - attrBuilde.build(spConfig, authData, g); - Assert.assertTrue("Attr. Builder provide no 'UnavailableAttributeException'", false); - - } catch (final Exception e) { - Assert.assertTrue("Attr. builder provide wrong exception", e instanceof UnavailableAttributeException); - Assert.assertEquals("Attr. name in exception does NOT match", - PVPAttributeDefinitions.GIVEN_NAME_NAME, ((UnavailableAttributeException) e).getAttributeName()); - - } - - } - - @Test - public void performTest_emtpty() { - try { - final AuthenticationData authData = (AuthenticationData) buildAuthData(); - authData.setGivenName(StringUtils.EMPTY); - - attrBuilde.build(spConfig, authData, g); - Assert.assertTrue("Attr. Builder provide no 'UnavailableAttributeException'", false); - - } catch (final Exception e) { - Assert.assertTrue("Attr. builder provide wrong exception", e instanceof UnavailableAttributeException); - Assert.assertEquals("Attr. name in exception does NOT match", - PVPAttributeDefinitions.GIVEN_NAME_NAME, ((UnavailableAttributeException) e).getAttributeName()); - - } - - } +public class GivenNameAttrBuilderTest extends AbstractAttributeBuilderTest { + + private final IAttributeBuilder attrBuilde = new GivenNameAttributeBuilder(); + + @Test + public void performTest_ok() { + try { + final IAuthData authData = buildAuthData(); + final String value = attrBuilde.build(spConfig, authData, gen); + Assert.assertEquals("GivenName does NOT match", authData.getGivenName(), value); + + } catch (final Exception e) { + Assert.assertTrue("Attr. builder has an exception", e == null); + + } + + } + + @Test + public void performTest_null() { + try { + final AuthenticationData authData = (AuthenticationData) buildAuthData(); + authData.setGivenName(null); + + attrBuilde.build(spConfig, authData, gen); + Assert.assertTrue("Attr. Builder provide no 'UnavailableAttributeException'", false); + + } catch (final Exception e) { + Assert.assertTrue("Attr. builder provide wrong exception", + e instanceof UnavailableAttributeException); + Assert.assertEquals("Attr. name in exception does NOT match", + PVPAttributeDefinitions.GIVEN_NAME_NAME, + ((UnavailableAttributeException) e).getAttributeName()); + + } + + } + + @Test + public void performTest_emtpty() { + try { + final AuthenticationData authData = (AuthenticationData) buildAuthData(); + authData.setGivenName(StringUtils.EMPTY); + + attrBuilde.build(spConfig, authData, gen); + Assert.assertTrue("Attr. Builder provide no 'UnavailableAttributeException'", false); + + } catch (final Exception e) { + Assert.assertTrue("Attr. builder provide wrong exception", + e instanceof UnavailableAttributeException); + Assert.assertEquals("Attr. name in exception does NOT match", + PVPAttributeDefinitions.GIVEN_NAME_NAME, + ((UnavailableAttributeException) e).getAttributeName()); + + } + + } } diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/module/test/DummyConfiguration.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/module/test/DummyConfiguration.java index 816f6871..185e1d27 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/module/test/DummyConfiguration.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/module/test/DummyConfiguration.java @@ -3,82 +3,83 @@ package at.gv.egiz.eaaf.core.impl.idp.module.test; import java.net.URI; import java.net.URL; import java.util.Map; - import at.gv.egiz.eaaf.core.api.idp.IConfigurationWithSP; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.impl.idp.auth.builder.AbstractAuthenticationDataBuilder; public class DummyConfiguration implements IConfigurationWithSP { - private Boolean isIDLEscapingEnabled = null; - - @Override - public String getBasicConfiguration(String key) { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getBasicConfiguration(String key, String defaultValue) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Map getBasicConfigurationWithPrefix(String prefix) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ISPConfiguration getServiceProviderConfiguration(String uniqueID) throws EAAFConfigurationException { - // TODO Auto-generated method stub - return null; - } - - @Override - public T getServiceProviderConfiguration(String spIdentifier, Class decorator) - throws EAAFConfigurationException { - // TODO Auto-generated method stub - return null; - } - - @Override - public URI getConfigurationRootDirectory() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String validateIDPURL(URL authReqUrl) throws EAAFException { - // TODO Auto-generated method stub - return null; - } - - public void setIsIDLEscapingEnabled(Boolean isIDLEscapingEnabled) { - this.isIDLEscapingEnabled = isIDLEscapingEnabled; - } - - @Override - public Boolean getBasicConfigurationBoolean(String key) { - return null; - - } - - @Override - public boolean getBasicConfigurationBoolean(String key, boolean defaultValue) { - if (AbstractAuthenticationDataBuilder.CONFIG_PROP_ENABLE_IDL_ATTRIBUTE_ESCAPEING.equals(key)) { - if (isIDLEscapingEnabled == null) - return defaultValue; - else - return isIDLEscapingEnabled; - - } - - - return false; - - } + private Boolean isIdlEscapingEnabled = null; + + @Override + public String getBasicConfiguration(final String key) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getBasicConfiguration(final String key, final String defaultValue) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Map getBasicConfigurationWithPrefix(final String prefix) { + // TODO Auto-generated method stub + return null; + } + + @Override + public IspConfiguration getServiceProviderConfiguration(final String uniqueID) + throws EaafConfigurationException { + // TODO Auto-generated method stub + return null; + } + + @Override + public T getServiceProviderConfiguration(final String spIdentifier, final Class decorator) + throws EaafConfigurationException { + // TODO Auto-generated method stub + return null; + } + + @Override + public URI getConfigurationRootDirectory() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String validateIdpUrl(final URL authReqUrl) throws EaafException { + // TODO Auto-generated method stub + return null; + } + + public void setIsIdlEscapingEnabled(final Boolean isIdlEscapingEnabled) { + this.isIdlEscapingEnabled = isIdlEscapingEnabled; + } + + @Override + public boolean getBasicConfigurationBoolean(final String key) { + return false; + + } + + @Override + public boolean getBasicConfigurationBoolean(final String key, final boolean defaultValue) { + if (AbstractAuthenticationDataBuilder.CONFIG_PROP_ENABLE_IDL_ATTRIBUTE_ESCAPEING.equals(key)) { + if (isIdlEscapingEnabled == null) { + return defaultValue; + } else { + return isIdlEscapingEnabled; + } + + } + + + return false; + + } } diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/module/test/DummyProtocolAuthService.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/module/test/DummyProtocolAuthService.java index 94209dd6..87f2bcb6 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/module/test/DummyProtocolAuthService.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/module/test/DummyProtocolAuthService.java @@ -7,75 +7,77 @@ import javax.servlet.http.HttpServletResponse; import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.idp.auth.services.IProtocolAuthenticationService; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; public class DummyProtocolAuthService implements IProtocolAuthenticationService { - - private IRequest pendingReq; - private HttpServletRequest httpReq; - private HttpServletResponse httpResp; - private Throwable exception; - private boolean writeToStatisticLog; - - - @Override - public void performAuthentication(HttpServletRequest req, HttpServletResponse resp, IRequest pendingReq) - throws IOException, EAAFException { - this.pendingReq = pendingReq; - this.httpReq = req; - this.httpResp = resp; - - } - - @Override - public void finalizeAuthentication(HttpServletRequest req, HttpServletResponse resp, IRequest pendingReq) - throws EAAFException, IOException { - this.pendingReq = pendingReq; - this.httpReq = req; - this.httpResp = resp; - - } - - @Override - public void buildProtocolSpecificErrorResponse(Throwable throwable, HttpServletRequest req, - HttpServletResponse resp, IRequest pendingReq) throws IOException, EAAFException { - this.pendingReq = pendingReq; - this.httpReq = req; - this.httpResp = resp; - this.exception = throwable; - - } - - @Override - public void handleErrorNoRedirect(Throwable throwable, HttpServletRequest req, HttpServletResponse resp, - boolean writeExceptionToStatisticLog) throws IOException, EAAFException { - this.httpReq = req; - this.httpResp = resp; - this.exception = throwable; - this.writeToStatisticLog = writeExceptionToStatisticLog; - - } - - public IRequest getPendingReq() { - return pendingReq; - } - - public HttpServletRequest getHttpReq() { - return httpReq; - } - - public HttpServletResponse getHttpResp() { - return httpResp; - } - - public Throwable getException() { - return exception; - } - - public boolean isWriteToStatisticLog() { - return writeToStatisticLog; - } - - + + private IRequest pendingReq; + private HttpServletRequest httpReq; + private HttpServletResponse httpResp; + private Throwable exception; + private boolean writeToStatisticLog; + + + @Override + public void performAuthentication(final HttpServletRequest req, final HttpServletResponse resp, + final IRequest pendingReq) throws IOException, EaafException { + this.pendingReq = pendingReq; + this.httpReq = req; + this.httpResp = resp; + + } + + @Override + public void finalizeAuthentication(final HttpServletRequest req, final HttpServletResponse resp, + final IRequest pendingReq) throws EaafException, IOException { + this.pendingReq = pendingReq; + this.httpReq = req; + this.httpResp = resp; + + } + + @Override + public void buildProtocolSpecificErrorResponse(final Throwable throwable, + final HttpServletRequest req, final HttpServletResponse resp, final IRequest pendingReq) + throws IOException, EaafException { + this.pendingReq = pendingReq; + this.httpReq = req; + this.httpResp = resp; + this.exception = throwable; + + } + + @Override + public void handleErrorNoRedirect(final Throwable throwable, final HttpServletRequest req, + final HttpServletResponse resp, final boolean writeExceptionToStatisticLog) + throws IOException, EaafException { + this.httpReq = req; + this.httpResp = resp; + this.exception = throwable; + this.writeToStatisticLog = writeExceptionToStatisticLog; + + } + + public IRequest getPendingReq() { + return pendingReq; + } + + public HttpServletRequest getHttpReq() { + return httpReq; + } + + public HttpServletResponse getHttpResp() { + return httpResp; + } + + public Throwable getException() { + return exception; + } + + public boolean isWriteToStatisticLog() { + return writeToStatisticLog; + } + + } diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/module/test/DummySPConfiguration.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/module/test/DummySPConfiguration.java deleted file mode 100644 index f51c95ab..00000000 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/module/test/DummySPConfiguration.java +++ /dev/null @@ -1,21 +0,0 @@ -package at.gv.egiz.eaaf.core.impl.idp.module.test; - -import java.util.Map; - -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.impl.idp.conf.SPConfigurationImpl; - -public class DummySPConfiguration extends SPConfigurationImpl { - - public DummySPConfiguration(Map spConfig, IConfiguration authConfig) { - super(spConfig, authConfig); - - } - - @Override - public String getAreaSpecificTargetIdentifier() { - return getConfigurationValue("target"); - - } - -} diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/module/test/DummySpConfiguration.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/module/test/DummySpConfiguration.java new file mode 100644 index 00000000..87e91609 --- /dev/null +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/module/test/DummySpConfiguration.java @@ -0,0 +1,23 @@ +package at.gv.egiz.eaaf.core.impl.idp.module.test; + +import java.util.Map; + +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.impl.idp.conf.SpConfigurationImpl; + +public class DummySpConfiguration extends SpConfigurationImpl { + + private static final long serialVersionUID = 3837138426712775909L; + + public DummySpConfiguration(final Map spConfig, final IConfiguration authConfig) { + super(spConfig, authConfig); + + } + + @Override + public String getAreaSpecificTargetIdentifier() { + return getConfigurationValue("target"); + + } + +} diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/module/test/TestRequestImpl.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/module/test/TestRequestImpl.java index 80451399..ad80d3ad 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/module/test/TestRequestImpl.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/module/test/TestRequestImpl.java @@ -1,343 +1,376 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.module.test; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; - -import org.apache.commons.lang3.StringUtils; - import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.exceptions.EAAFStorageException; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; +import org.apache.commons.lang3.StringUtils; /** + * Test pending-request for jUnit tests. + * * @author tlenz * */ public class TestRequestImpl implements IRequest { - private String processInstanceID = null; - private ISPConfiguration spConfig = null; - private final Map storage = new HashMap(); - private String transactionId = null; - private String pendingReqId = null; - private String authURL = null; - private boolean authenticated; - private boolean needAuthentication = false; - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#requestedModule() - */ - @Override - public String requestedModule() { - // TODO Auto-generated method stub - return null; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#requestedAction() - */ - @Override - public String requestedAction() { - // TODO Auto-generated method stub - return null; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#isPassiv() - */ - @Override - public boolean isPassiv() { - // TODO Auto-generated method stub - return false; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#forceAuth() - */ - @Override - public boolean forceAuth() { - // TODO Auto-generated method stub - return false; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#getGenericData(java.lang.String) - */ - @Override - public Object getRawData(String key) { - return storage.get(key); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#getGenericData(java.lang.String, java.lang.Class) - */ - @Override - public T getRawData(String key, Class clazz) { - return (T)storage.get(key); - } - - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#getUniqueTransactionIdentifier() - */ - @Override - public String getUniqueTransactionIdentifier() { - return this.transactionId; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#getUniqueSessionIdentifier() - */ - @Override - public String getUniqueSessionIdentifier() { - // TODO Auto-generated method stub - return null; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#getProcessInstanceId() - */ - @Override - public String getProcessInstanceId() { - return processInstanceID; - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#getAuthURL() - */ - @Override - public String getAuthURL() { - return this.authURL; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#getAuthURLWithOutSlash() - */ - @Override - public String getAuthURLWithOutSlash() { - if (this.authURL != null && this.authURL.endsWith("/")) - return this.authURL.substring(0, this.authURL.length()-1); - else - return this.authURL; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#isNeedAuthentication() - */ - @Override - public boolean isNeedAuthentication() { - return this.needAuthentication; - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#needSingleSignOnFunctionality() - */ - @Override - public boolean needSingleSignOnFunctionality() { - // TODO Auto-generated method stub - return false; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#setNeedSingleSignOnFunctionality(boolean) - */ - @Override - public void setNeedSingleSignOnFunctionality(boolean needSSO) { - // TODO Auto-generated method stub - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#isAuthenticated() - */ - @Override - public boolean isAuthenticated() { - return this.authenticated; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#setAuthenticated(boolean) - */ - @Override - public void setAuthenticated(boolean isAuthenticated) { - this.authenticated = isAuthenticated; - - } - - /** - * @param processInstanceID the processInstanceID to set - */ - public void setProcessInstanceID(String processInstanceID) { - this.processInstanceID = processInstanceID; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#isAbortedByUser() - */ - @Override - public boolean isAbortedByUser() { - // TODO Auto-generated method stub - return false; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#setAbortedByUser(boolean) - */ - @Override - public void setAbortedByUser(boolean isAborted) { - // TODO Auto-generated method stub - - } - - @Override - public String getSPEntityId() { - // TODO Auto-generated method stub - return null; - } - - @Override - public void setRawDataToTransaction(Map map) throws EAAFStorageException { - storage.putAll(map); - - } - - @Override - public String getPendingRequestId() { - return this.pendingReqId; - } - - @Override - public String getInternalSSOSessionIdentifier() { - // TODO Auto-generated method stub - return null; - } - - @Override - public void setInternalSSOSessionIdentifier(String internalSSOSessionId) { - // TODO Auto-generated method stub - - } - - @Override - public boolean isNeedUserConsent() { - // TODO Auto-generated method stub - return false; - } - - @Override - public void setNeedUserConsent(boolean needConsent) { - // TODO Auto-generated method stub - - } - - @Override - public ISPConfiguration getServiceProviderConfiguration() { - return spConfig; - - } - - @Override - public T getServiceProviderConfiguration(Class decorator) { - return (T)spConfig; - } - - @Override - public void setRawDataToTransaction(String key, Object object) throws EAAFStorageException { - if (StringUtils.isEmpty(key)) { - throw new EAAFStorageException("Generic request-data can not be stored with a 'null' key", null); - - } - - if (object != null) { - if (!Serializable.class.isInstance(object)) { - throw new EAAFStorageException("Generic request-data can only store objects which implements the 'Seralizable' interface", null); - - } - } - - storage.put(key, object); - - } - - public void setSpConfig(ISPConfiguration spConfig) { - this.spConfig = spConfig; - } - - @Override - public T getSessionData(Class wrapper) { - if (wrapper != null) { - if (AuthProcessDataWrapper.class.isAssignableFrom(wrapper)) { - try { - return wrapper.getConstructor(Map.class).newInstance(this.storage); - - } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException - | IllegalArgumentException | InvocationTargetException e) { - throw new RuntimeException("Can NOT instance wrapper: " + wrapper.getName(), e); - - } - - } - - throw new RuntimeException("Can NOT wrap generic data into session data. " - + "Reason: Wrapper " + wrapper.getName() + " is NOT a valid wrapper"); - - } - - return null; - } - - public void setTransactionId(String transactionId) { - this.transactionId = transactionId; - } - - public void setPendingReqId(String pendingReqId) { - this.pendingReqId = pendingReqId; - } - - public void setAuthURL(String authURL) { - this.authURL = authURL; - } - - public void setNeedAuthentication(boolean needAuthentication) { - this.needAuthentication = needAuthentication; - } - - - - - - - + private String processInstanceID = null; + private IspConfiguration spConfig = null; + private final Map storage = new HashMap<>(); + private String transactionId = null; + private String pendingReqId = null; + private String authUrl = null; + private boolean authenticated; + private boolean needAuthentication = false; + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.moduls.IRequest#requestedModule() + */ + @Override + public String requestedModule() { + // TODO Auto-generated method stub + return null; + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.moduls.IRequest#requestedAction() + */ + @Override + public String requestedAction() { + // TODO Auto-generated method stub + return null; + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.moduls.IRequest#isPassiv() + */ + @Override + public boolean isPassiv() { + // TODO Auto-generated method stub + return false; + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.moduls.IRequest#forceAuth() + */ + @Override + public boolean forceAuth() { + // TODO Auto-generated method stub + return false; + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.moduls.IRequest#getGenericData(java.lang.String) + */ + @Override + public Object getRawData(final String key) { + return storage.get(key); + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.moduls.IRequest#getGenericData(java.lang.String, java.lang.Class) + */ + @Override + public T getRawData(final String key, final Class clazz) { + return (T) storage.get(key); + } + + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.moduls.IRequest#getUniqueTransactionIdentifier() + */ + @Override + public String getUniqueTransactionIdentifier() { + return this.transactionId; + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.moduls.IRequest#getUniqueSessionIdentifier() + */ + @Override + public String getUniqueSessionIdentifier() { + // TODO Auto-generated method stub + return null; + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.moduls.IRequest#getProcessInstanceId() + */ + @Override + public String getProcessInstanceId() { + return processInstanceID; + + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.moduls.IRequest#getAuthURL() + */ + @Override + public String getAuthUrl() { + return this.authUrl; + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.moduls.IRequest#getAuthURLWithOutSlash() + */ + @Override + public String getAuthUrlWithOutSlash() { + if (this.authUrl != null && this.authUrl.endsWith("/")) { + return this.authUrl.substring(0, this.authUrl.length() - 1); + } else { + return this.authUrl; + } + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.moduls.IRequest#isNeedAuthentication() + */ + @Override + public boolean isNeedAuthentication() { + return this.needAuthentication; + + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.moduls.IRequest#needSingleSignOnFunctionality() + */ + @Override + public boolean needSingleSignOnFunctionality() { + // TODO Auto-generated method stub + return false; + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.moduls.IRequest#setNeedSingleSignOnFunctionality(boolean) + */ + @Override + public void setNeedSingleSignOnFunctionality(final boolean needSso) { + // TODO Auto-generated method stub + + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.moduls.IRequest#isAuthenticated() + */ + @Override + public boolean isAuthenticated() { + return this.authenticated; + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.moduls.IRequest#setAuthenticated(boolean) + */ + @Override + public void setAuthenticated(final boolean isAuthenticated) { + this.authenticated = isAuthenticated; + + } + + /** + * Set process-instance id. + * + * @param processInstanceID the processInstanceID to set + */ + public void setProcessInstanceID(final String processInstanceID) { + this.processInstanceID = processInstanceID; + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.moduls.IRequest#isAbortedByUser() + */ + @Override + public boolean isAbortedByUser() { + // TODO Auto-generated method stub + return false; + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.moduls.IRequest#setAbortedByUser(boolean) + */ + @Override + public void setAbortedByUser(final boolean isAborted) { + // TODO Auto-generated method stub + + } + + @Override + public String getSpEntityId() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setRawDataToTransaction(final String key, final Object object) + throws EaafStorageException { + if (StringUtils.isEmpty(key)) { + throw new EaafStorageException("Generic request-data can not be stored with a 'null' key", + null); + + } + + if (object != null) { + if (!Serializable.class.isInstance(object)) { + throw new EaafStorageException( + "Generic request-data can only store objects which implements the 'Seralizable' interface", + null); + + } + } + + storage.put(key, object); + + } + + @Override + public void setRawDataToTransaction(final Map map) throws EaafStorageException { + storage.putAll(map); + + } + + @Override + public String getPendingRequestId() { + return this.pendingReqId; + } + + @Override + public String getInternalSsoSessionIdentifier() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setInternalSsoSessionIdentifier(final String internalSsoSessionId) { + // TODO Auto-generated method stub + + } + + @Override + public boolean isNeedUserConsent() { + // TODO Auto-generated method stub + return false; + } + + @Override + public void setNeedUserConsent(final boolean needConsent) { + // TODO Auto-generated method stub + + } + + @Override + public IspConfiguration getServiceProviderConfiguration() { + return spConfig; + + } + + @Override + public T getServiceProviderConfiguration(final Class decorator) { + return (T) spConfig; + } + + + + public void setSpConfig(final IspConfiguration spConfig) { + this.spConfig = spConfig; + } + + @Override + public T getSessionData(final Class wrapper) { + if (wrapper != null) { + if (AuthProcessDataWrapper.class.isAssignableFrom(wrapper)) { + try { + return wrapper.getConstructor(Map.class).newInstance(this.storage); + + } catch (NoSuchMethodException | SecurityException | InstantiationException + | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + throw new RuntimeException("Can NOT instance wrapper: " + wrapper.getName(), e); + + } + + } + + throw new RuntimeException("Can NOT wrap generic data into session data. " + + "Reason: Wrapper " + wrapper.getName() + " is NOT a valid wrapper"); + + } + + return null; + } + + public void setTransactionId(final String transactionId) { + this.transactionId = transactionId; + } + + public void setPendingReqId(final String pendingReqId) { + this.pendingReqId = pendingReqId; + } + + public void setAuthUrl(final String authUrl) { + this.authUrl = authUrl; + } + + public void setNeedAuthentication(final boolean needAuthentication) { + this.needAuthentication = needAuthentication; + } + + } diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/DummyTransactionStorage.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/DummyTransactionStorage.java index 4795fdf4..cc1d57cd 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/DummyTransactionStorage.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/DummyTransactionStorage.java @@ -1,189 +1,186 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process.spring.test; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; - import javax.sql.DataSource; - +import at.gv.egiz.eaaf.core.api.storage.ITransactionStorage; +import at.gv.egiz.eaaf.core.exceptions.EaafException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import at.gv.egiz.eaaf.core.api.storage.ITransactionStorage; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; - /** - * Dummy DataSource implementation for convenience in test cases where a - * database connection will never actually be acquired. + * Dummy DataSource implementation for convenience in test cases where a database connection will + * never actually be acquired. * * @see DataSource * @author Chris Beams */ public class DummyTransactionStorage implements ITransactionStorage { - private static final Logger log = LoggerFactory.getLogger(DummyTransactionStorage.class); - - - public class DummyDBEntry{ - public DummyDBEntry(String key, Object value){ - this.obj =value; - this.key = key; - } - public String getKey() { - return key; - } - public void setKey(String key) { - this.key = key; - } - public Object getObj() { - return obj; - } - public void setObj(Object obj) { - this.obj = obj; - } - private String key; - private Object obj; - } - - private ArrayList ds = new ArrayList(); - - - - @Override - public boolean containsKey(String key) { - // TODO Auto-generated method stub - Iterator it = ds.iterator(); - while(it.hasNext()){ - DummyDBEntry t = it.next(); - if(t.getKey().equals(key)) - return true; - } - return false; - } - - @Override - public void put(String key, Object value, int timeout) - throws EAAFException { - // TODO Auto-generated method stub - this.remove(key); - this.ds.add(new DummyDBEntry(key, value)); - - } - - @Override - public Object get(String key) throws EAAFException { - // TODO Auto-generated method stub - Iterator it = ds.iterator(); - while(it.hasNext()){ - DummyDBEntry t = it.next(); - if(t.getKey().equals(key)) - return t; - } - return null; - } - - @Override - public T get(String key, Class clazz) throws EAAFException { - - DummyDBEntry o = (DummyDBEntry) get(key); - if(o == null) - return null; - try { - @SuppressWarnings("unchecked") - T test = (T) (clazz.cast(o.getObj())); - return test; - - } catch (Exception e) { - log.warn("Sessioninformation Cast-Exception by using Artifact=" + key); - throw new EAAFException("Sessioninformation Cast-Exception"); - - } - } - - @Override - public T get(String key, Class clazz, long dataTimeOut) - throws EAAFException { - // TODO Auto-generated method stub - return get(key,clazz); - } - - @Override - public void changeKey(String oldKey, String newKey, Object value) - throws EAAFException { - this.remove(oldKey); - this.put(newKey, value, -1); - - } - - @Override - public void remove(String key) { - Iterator it = ds.iterator(); - while(it.hasNext()){ - DummyDBEntry t = it.next(); - if(t.getKey().equals(key)){ - this.ds.remove(t); - return; - } - } - - } - - @Override - public List clean(Date now, long dataTimeOut) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Object getRaw(String key) throws EAAFException { - // TODO Auto-generated method stub - return null; - } - - @Override - public void putRaw(String key, Object element) throws EAAFException { - // TODO Auto-generated method stub - - } - -// @Override -// public Object getAssertionStore(String key) throwsEAAFException { -// // TODO Auto-generated method stub -// return null; -// } -// -// @Override -// public void putAssertionStore(Object element) throws EAAFException { -// // TODO Auto-generated method stub -// -// } - - -} \ No newline at end of file + private static final Logger log = LoggerFactory.getLogger(DummyTransactionStorage.class); + + + public class DummyDbEntry { + public DummyDbEntry(final String key, final Object value) { + this.obj = value; + this.key = key; + } + + public String getKey() { + return key; + } + + public void setKey(final String key) { + this.key = key; + } + + public Object getObj() { + return obj; + } + + public void setObj(final Object obj) { + this.obj = obj; + } + + private String key; + private Object obj; + } + + private final ArrayList ds = new ArrayList<>(); + + + + @Override + public boolean containsKey(final String key) { + // TODO Auto-generated method stub + final Iterator it = ds.iterator(); + while (it.hasNext()) { + final DummyDbEntry t = it.next(); + if (t.getKey().equals(key)) { + return true; + } + } + return false; + } + + @Override + public void put(final String key, final Object value, final int timeout) throws EaafException { + // TODO Auto-generated method stub + this.remove(key); + this.ds.add(new DummyDbEntry(key, value)); + + } + + @Override + public Object get(final String key) throws EaafException { + // TODO Auto-generated method stub + final Iterator it = ds.iterator(); + while (it.hasNext()) { + final DummyDbEntry t = it.next(); + if (t.getKey().equals(key)) { + return t; + } + } + return null; + } + + @Override + public T get(final String key, final Class clazz) throws EaafException { + + final DummyDbEntry o = (DummyDbEntry) get(key); + if (o == null) { + return null; + } + try { + @SuppressWarnings("unchecked") + final T test = (clazz.cast(o.getObj())); + return test; + + } catch (final Exception e) { + log.warn("Sessioninformation Cast-Exception by using Artifact=" + key); + throw new EaafException("Sessioninformation Cast-Exception"); + + } + } + + @Override + public T get(final String key, final Class clazz, final long dataTimeOut) + throws EaafException { + // TODO Auto-generated method stub + return get(key, clazz); + } + + @Override + public void changeKey(final String oldKey, final String newKey, final Object value) + throws EaafException { + this.remove(oldKey); + this.put(newKey, value, -1); + + } + + @Override + public void remove(final String key) { + final Iterator it = ds.iterator(); + while (it.hasNext()) { + final DummyDbEntry t = it.next(); + if (t.getKey().equals(key)) { + this.ds.remove(t); + return; + } + } + + } + + @Override + public List clean(final Date now, final long dataTimeOut) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Object getRaw(final String key) throws EaafException { + // TODO Auto-generated method stub + return null; + } + + @Override + public void putRaw(final String key, final Object element) throws EaafException { + // TODO Auto-generated method stub + + } + + // @Override + // public Object getAssertionStore(String key) throwsEAAFException { + // // TODO Auto-generated method stub + // return null; + // } + // + // @Override + // public void putAssertionStore(Object element) throws EAAFException { + // // TODO Auto-generated method stub + // + // } + + +} diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/ExpressionContextAdapter.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/ExpressionContextAdapter.java index 9a05f905..c00cc628 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/ExpressionContextAdapter.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/ExpressionContextAdapter.java @@ -1,29 +1,22 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process.spring.test; @@ -31,48 +24,45 @@ import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.Map; - import at.gv.egiz.eaaf.core.api.idp.process.ExpressionEvaluationContext; /** * Adapter class for {@link ExpressionEvaluationContext}. Intended to be used for testing purposes. - * + * * @author tknall - * + * */ public class ExpressionContextAdapter implements ExpressionEvaluationContext { - - private static final long serialVersionUID = 1L; - private Map ctxData = Collections.synchronizedMap(new HashMap()); + private static final long serialVersionUID = 1L; + + private final Map ctxData = + Collections.synchronizedMap(new HashMap()); - /** - * Returns a certain {@link Serializable} object associated with a certain {@code key}. - * - * @param key - * The key. - * @return The object or {@code null} if no object was found stored with that key or if a {@code null} value was - * stored. - */ - Serializable get(String key) { - return ctxData.get(key); - } + /** + * Returns a certain {@link Serializable} object associated with a certain {@code key}. + * + * @param key The key. + * @return The object or {@code null} if no object was found stored with that key or if a + * {@code null} value was stored. + */ + Serializable get(final String key) { + return ctxData.get(key); + } - /** - * Stores a {@link Serializable} with a certain {@code key}. - * - * @param key - * The key. - * @param object - * The object. - */ - void put(String key, Serializable object) { - ctxData.put(key, object); - } + /** + * Stores a {@link Serializable} with a certain {@code key}. + * + * @param key The key. + * @param object The object. + */ + void put(final String key, final Serializable object) { + ctxData.put(key, object); + } - @Override - public Map getCtx() { - return Collections.unmodifiableMap(ctxData); - } + @Override + public Map getCtx() { + return Collections.unmodifiableMap(ctxData); + } } diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/SimplePojo.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/SimplePojo.java index fa6a9f10..28dc57b4 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/SimplePojo.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/SimplePojo.java @@ -1,67 +1,60 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process.spring.test; import at.gv.egiz.eaaf.core.api.idp.process.ExpressionEvaluator; /** * A dummy pojo used to test {@link ExpressionEvaluator} with Spring EL referencing Spring beans. - * + * * @author tknall - * + * */ public class SimplePojo { - private Boolean booleanValue; - private String stringValue; - private Integer integerValue; + private Boolean booleanValue; + private String stringValue; + private Integer integerValue; - public Boolean getBooleanValue() { - return booleanValue; - } + public Boolean getBooleanValue() { + return booleanValue; + } - public void setBooleanValue(Boolean booleanValue) { - this.booleanValue = booleanValue; - } + public void setBooleanValue(final Boolean booleanValue) { + this.booleanValue = booleanValue; + } - public String getStringValue() { - return stringValue; - } + public String getStringValue() { + return stringValue; + } - public void setStringValue(String stringValue) { - this.stringValue = stringValue; - } + public void setStringValue(final String stringValue) { + this.stringValue = stringValue; + } - public Integer getIntegerValue() { - return integerValue; - } + public Integer getIntegerValue() { + return integerValue; + } - public void setIntegerValue(Integer integerValue) { - this.integerValue = integerValue; - } + public void setIntegerValue(final Integer integerValue) { + this.integerValue = integerValue; + } } diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/SpringExpressionAwareProcessEngineTest.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/SpringExpressionAwareProcessEngineTest.java index 67675ff9..1d139b5e 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/SpringExpressionAwareProcessEngineTest.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/SpringExpressionAwareProcessEngineTest.java @@ -1,47 +1,30 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process.spring.test; import static at.gv.egiz.eaaf.core.impl.idp.process.ProcessInstanceState.NOT_STARTED; import static at.gv.egiz.eaaf.core.impl.idp.process.ProcessInstanceState.SUSPENDED; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; - import java.io.IOException; import java.io.InputStream; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; import at.gv.egiz.eaaf.core.api.idp.process.ProcessEngine; import at.gv.egiz.eaaf.core.exceptions.ProcessExecutionException; @@ -50,128 +33,132 @@ import at.gv.egiz.eaaf.core.impl.idp.process.ProcessDefinitionParserException; import at.gv.egiz.eaaf.core.impl.idp.process.ProcessEngineImpl; import at.gv.egiz.eaaf.core.impl.idp.process.ProcessInstance; import at.gv.egiz.eaaf.core.impl.idp.process.spring.SpringExpressionEvaluator; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** - * Tests the process engine using processes based on Spring EL referencing the process context and further Spring beans. - * + * Tests the process engine using processes based on Spring EL referencing the process context and + * further Spring beans. + * * @author tknall - * + * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/process/spring/test/SpringExpressionAwareProcessEngineTest-context.xml") public class SpringExpressionAwareProcessEngineTest { - @Autowired private static ProcessEngine pe; - @Autowired private ApplicationContext applicationContext; - - private boolean isInitialized = false; - - @Before - public void init() throws IOException, ProcessDefinitionParserException { - - if (!isInitialized) { - - if (pe == null) { - pe = applicationContext.getBean("processEngine", ProcessEngine.class); - - } - - ((ProcessEngineImpl) pe).setTransitionConditionExpressionEvaluator(new SpringExpressionEvaluator()); - try (InputStream in = SpringExpressionAwareProcessEngineTest.class.getResourceAsStream("/process/spring/test/SampleProcessDefinitionWithExpression1.xml")) { - ((ProcessEngineImpl) pe).registerProcessDefinition(in); - } - try (InputStream in = SpringExpressionAwareProcessEngineTest.class.getResourceAsStream("/process/spring/test/SampleProcessDefinitionForSAML1Authentication.xml")) { - ((ProcessEngineImpl) pe).registerProcessDefinition(in); - } - - //initHibernateForTesting(); - } - } - - private static void initHibernateForTesting() throws IOException{ - -// InputStream in = SpringExpressionAwareProcessEngineTest.class.getResourceAsStream("/at/gv/egovernment/moa/id/process/hibernate.configuration.test.properties"); -// Properties props = new Properties(); -// props.load(in); -// -// try { -// //ConfigurationDBUtils.initHibernate(props); -// Configuration config = new Configuration(); -// config.addProperties(props); -// //config.addAnnotatedClass(ProcessInstanceStore.class); -// config.addAnnotatedClass(AssertionStore.class); -// //MOASessionDBUtils.initHibernate(config, props); -// } catch (Exception e) { -// e.printStackTrace(); -// } - } - - - @Test - public void testSampleProcessDefinitionWithExpression1() throws IOException, ProcessDefinitionParserException, ProcessExecutionException { - - TestRequestImpl req = new TestRequestImpl(); - - String piId = pe.createProcessInstance("SampleProcessWithExpression1"); - ProcessInstance pi = pe.getProcessInstance(piId); - assertEquals(NOT_STARTED, pi.getState()); - - - // start process - req.setProcessInstanceID(piId); - pe.start(req); - - //processInstance should be removed when it ends - try { - pi = pe.getProcessInstance(piId); - throw new ProcessExecutionException("ProcessInstance should be removed already, but it was found."); - //assertEquals(ENDED, pi.getState()); - - } catch (IllegalArgumentException e) { - // do nothing because processInstance should be already removed - - } - } - - @Test - public void testSampleProcessDefinitionForSAML1Authentication() throws IOException, ProcessDefinitionParserException, ProcessExecutionException { - - TestRequestImpl req = new TestRequestImpl(); - - String piId = pe.createProcessInstance("SampleProcessDefinitionForSAML1Authentication"); - ProcessInstance pi = pe.getProcessInstance(piId); - assertEquals(NOT_STARTED, pi.getState()); - - // start process - req.setProcessInstanceID(piId); - pe.start(req); - pi = pe.getProcessInstance(piId); - assertEquals(SUSPENDED, pi.getState()); - - ExecutionContext ec = pi.getExecutionContext(); - assertNotNull(ec); - System.out.println(ec.keySet()); - - assertNotNull(ec.get("bkuURL")); - assertNotNull(ec.get("IdentityLink")); - assertNotNull(ec.get("isIdentityLinkValidated")); - assertNotNull(ec.get("SignedAuthBlock")); - assertNotNull(ec.get("isSignedAuthBlockValidated")); - assertNotNull(ec.get("SAML1Assertion")); - - pe.signal(req); - try { - pi = pe.getProcessInstance(piId); - throw new ProcessExecutionException("ProcessInstance should be removed already, but it was found."); - //assertEquals(ENDED, pi.getState()); - - } catch (IllegalArgumentException e) { - // do nothing because processInstance should be already removed - - } - - - - } + @Autowired + private static ProcessEngine pe; + @Autowired + private ApplicationContext applicationContext; + + private final boolean isInitialized = false; + + /** + * jUnit test set-up. + * + * @throws IOException in case of an error + * @throws ProcessDefinitionParserException in case of an error + */ + @Before + public void init() throws IOException, ProcessDefinitionParserException { + + if (!isInitialized) { + + if (pe == null) { + pe = applicationContext.getBean("processEngine", ProcessEngine.class); + + } + + ((ProcessEngineImpl) pe) + .setTransitionConditionExpressionEvaluator(new SpringExpressionEvaluator()); + try (InputStream in = SpringExpressionAwareProcessEngineTest.class + .getResourceAsStream("/process/spring/test/SampleProcessDefinitionWithExpression1.xml")) { + ((ProcessEngineImpl) pe).registerProcessDefinition(in); + } + try (InputStream in = SpringExpressionAwareProcessEngineTest.class.getResourceAsStream( + "/process/spring/test/SampleProcessDefinitionForSAML1Authentication.xml")) { + ((ProcessEngineImpl) pe).registerProcessDefinition(in); + } + + // initHibernateForTesting(); + } + } + + @Test + public void testSampleProcessDefinitionWithExpression1() + throws IOException, ProcessDefinitionParserException, ProcessExecutionException { + + final TestRequestImpl req = new TestRequestImpl(); + + final String piId = pe.createProcessInstance("SampleProcessWithExpression1"); + ProcessInstance pi = pe.getProcessInstance(piId); + assertEquals(NOT_STARTED, pi.getState()); + + + // start process + req.setProcessInstanceID(piId); + pe.start(req); + + // processInstance should be removed when it ends + try { + pi = pe.getProcessInstance(piId); + throw new ProcessExecutionException( + "ProcessInstance should be removed already, but it was found."); + // assertEquals(ENDED, pi.getState()); + + } catch (final IllegalArgumentException e) { + // do nothing because processInstance should be already removed + + } + } + + @Test + public void testSampleProcessDefinitionForSaml1Authentication() + throws IOException, ProcessDefinitionParserException, ProcessExecutionException { + + final TestRequestImpl req = new TestRequestImpl(); + + final String piId = pe.createProcessInstance("SampleProcessDefinitionForSAML1Authentication"); + ProcessInstance pi = pe.getProcessInstance(piId); + assertEquals(NOT_STARTED, pi.getState()); + + // start process + req.setProcessInstanceID(piId); + pe.start(req); + pi = pe.getProcessInstance(piId); + assertEquals(SUSPENDED, pi.getState()); + + final ExecutionContext ec = pi.getExecutionContext(); + assertNotNull(ec); + System.out.println(ec.keySet()); + + assertNotNull(ec.get("bkuURL")); + assertNotNull(ec.get("IdentityLink")); + assertNotNull(ec.get("isIdentityLinkValidated")); + assertNotNull(ec.get("SignedAuthBlock")); + assertNotNull(ec.get("isSignedAuthBlockValidated")); + assertNotNull(ec.get("SAML1Assertion")); + + pe.signal(req); + try { + pi = pe.getProcessInstance(piId); + throw new ProcessExecutionException( + "ProcessInstance should be removed already, but it was found."); + // assertEquals(ENDED, pi.getState()); + + } catch (final IllegalArgumentException e) { + // do nothing because processInstance should be already removed + + } + + + + } } diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/SpringExpressionEvaluatorTest.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/SpringExpressionEvaluatorTest.java index bde24824..5697365e 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/SpringExpressionEvaluatorTest.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/SpringExpressionEvaluatorTest.java @@ -1,34 +1,27 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process.spring.test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; - +import at.gv.egiz.eaaf.core.api.idp.process.ExpressionEvaluator; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -36,45 +29,44 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import at.gv.egiz.eaaf.core.api.idp.process.ExpressionEvaluator; - /** - * Tests the {@link ExpressionEvaluator} using a Spring EL based implementation capable of dereferencing Spring beans. - * + * Tests the {@link ExpressionEvaluator} using a Spring EL based implementation capable of + * dereferencing Spring beans. + * * @author tknall - * + * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/process/spring/test/SpringExpressionEvaluatorTest-context.xml") public class SpringExpressionEvaluatorTest { - private ExpressionContextAdapter ctx; + private ExpressionContextAdapter ctx; - @Autowired - private ExpressionEvaluator expressionEvaluator; + @Autowired + private ExpressionEvaluator expressionEvaluator; - @Before - public void prepareTest() { - ctx = new ExpressionContextAdapter(); - } + @Before + public void prepareTest() { + ctx = new ExpressionContextAdapter(); + } - @Test - public void testEvaluateSimpleExpression() { - assertTrue(expressionEvaluator.evaluate(ctx, "'true'")); - } + @Test + public void testEvaluateSimpleExpression() { + assertTrue(expressionEvaluator.evaluate(ctx, "'true'")); + } - @Test - public void testEvaluateExpressionWithCtx() { - ctx.put("myProperty", false); - assertFalse(expressionEvaluator.evaluate(ctx, "ctx['myProperty']")); - } + @Test + public void testEvaluateExpressionWithCtx() { + ctx.put("myProperty", false); + assertFalse(expressionEvaluator.evaluate(ctx, "ctx['myProperty']")); + } -// @Test - public void testEvaluateExpressionWithBeanReference() { - assertTrue(expressionEvaluator.evaluate(ctx, "@simplePojo.booleanValue")); - assertTrue(expressionEvaluator.evaluate(ctx, "'HelloWorld'.equals(@simplePojo.stringValue)")); - assertTrue(expressionEvaluator.evaluate(ctx, "@simplePojo.integerValue == 42")); - assertTrue(expressionEvaluator.evaluate(ctx, "@simplePojo.stringValue.length() == 10")); - } + @Test + public void testEvaluateExpressionWithBeanReference() { + assertTrue(expressionEvaluator.evaluate(ctx, "@simplePojo.booleanValue")); + assertTrue(expressionEvaluator.evaluate(ctx, "'HelloWorld'.equals(@simplePojo.stringValue)")); + assertTrue(expressionEvaluator.evaluate(ctx, "@simplePojo.integerValue == 42")); + assertTrue(expressionEvaluator.evaluate(ctx, "@simplePojo.stringValue.length() == 10")); + } } diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/CreateSAML1AssertionTask.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/CreateSAML1AssertionTask.java deleted file mode 100644 index 9caba080..00000000 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/CreateSAML1AssertionTask.java +++ /dev/null @@ -1,87 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.process.spring.test.task; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Objects; - -import org.apache.commons.io.IOUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - -import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; -import at.gv.egiz.eaaf.core.api.idp.process.Task; -import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; - -/** - * A dummy task simulating the creation of a SAML1 assertion. - *

- * Requires context data: - *

    - *
  • {@code IdentityLink}
  • - *
  • {@code isIdentityLinkValidated}
  • - *
  • {@code SignedAuthBlock}
  • - *
  • {@code isSignedAuthBlockValidated}
  • - *
- *

- *

- * Enriches context data with: - *

    - *
  • {@code SAML1Assertion}
  • - *
- *

- * - * @author tknall - * - */ -@Service("CreateSAML1AssertionTask") -public class CreateSAML1AssertionTask implements Task { - - private Logger log = LoggerFactory.getLogger(getClass()); - - @Override - public IRequest execute(IRequest penReq, ExecutionContext executionContext) throws TaskExecutionException { - Objects.requireNonNull(executionContext.get("IdentityLink")); - assert (Boolean.TRUE.equals(Objects.requireNonNull(executionContext.get("isIdentityLinkValidated")))); - Objects.requireNonNull(executionContext.get("SignedAuthBlock")); - assert (Boolean.TRUE.equals(Objects.requireNonNull(executionContext.get("isSignedAuthBlockValidated")))); - - log.debug("Using IdentityLink and signed auth block in order to create SAML1 assertion."); - - try (InputStream in = getClass().getResourceAsStream("/process/spring/test/task/SAML1Assertion.xml")) { - executionContext.put("SAML1Assertion", IOUtils.toString(in, "UTF-8")); - } catch (IOException e) { - throw new TaskExecutionException(null, "", e); - } - - return null; - } - -} diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/CreateSaml1AssertionTask.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/CreateSaml1AssertionTask.java new file mode 100644 index 00000000..c699f093 --- /dev/null +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/CreateSaml1AssertionTask.java @@ -0,0 +1,82 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.impl.idp.process.spring.test.task; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Objects; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.api.idp.process.Task; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +/** + * A dummy task simulating the creation of a SAML1 assertion. + *

+ * Requires context data: + *

    + *
  • {@code IdentityLink}
  • + *
  • {@code isIdentityLinkValidated}
  • + *
  • {@code SignedAuthBlock}
  • + *
  • {@code isSignedAuthBlockValidated}
  • + *
+ *

+ *

+ * Enriches context data with: + *

    + *
  • {@code SAML1Assertion}
  • + *
+ *

+ * + * @author tknall + * + */ +@Service("CreateSAML1AssertionTask") +public class CreateSaml1AssertionTask implements Task { + + private final Logger log = LoggerFactory.getLogger(getClass()); + + @Override + public IRequest execute(final IRequest penReq, final ExecutionContext executionContext) + throws TaskExecutionException { + Objects.requireNonNull(executionContext.get("IdentityLink")); + assert (Boolean.TRUE + .equals(Objects.requireNonNull(executionContext.get("isIdentityLinkValidated")))); + Objects.requireNonNull(executionContext.get("SignedAuthBlock")); + assert (Boolean.TRUE + .equals(Objects.requireNonNull(executionContext.get("isSignedAuthBlockValidated")))); + + log.debug("Using IdentityLink and signed auth block in order to create SAML1 assertion."); + + try (InputStream in = + getClass().getResourceAsStream("/process/spring/test/task/SAML1Assertion.xml")) { + executionContext.put("SAML1Assertion", IOUtils.toString(in, "UTF-8")); + } catch (final IOException e) { + throw new TaskExecutionException(null, "", e); + } + + return null; + } + +} diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/GetIdentityLinkTask.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/GetIdentityLinkTask.java index e6f12d1e..93fcf6db 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/GetIdentityLinkTask.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/GetIdentityLinkTask.java @@ -1,44 +1,35 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process.spring.test.task; import java.io.IOException; import java.io.InputStream; import java.util.Objects; - -import org.apache.commons.io.IOUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; import at.gv.egiz.eaaf.core.api.idp.process.Task; import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; /** * A dummy task simulating the retrieval of an IdentityLink. @@ -56,29 +47,31 @@ import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; *
  • {@code IdentityLink}
  • * *

    - * + * * @author tknall - * + * */ @Service("GetIdentityLinkTask") -public class GetIdentityLinkTask implements Task { +public class GetIdentityLinkTask implements Task { + + private final Logger log = LoggerFactory.getLogger(getClass()); + + @Override + public IRequest execute(final IRequest penReq, final ExecutionContext executionContext) + throws TaskExecutionException { + Objects.requireNonNull(executionContext.get("bkuURL")); - private Logger log = LoggerFactory.getLogger(getClass()); + log.debug("Using bkuURL in order to retrieve IdentityLink."); - @Override - public IRequest execute(IRequest penReq, ExecutionContext executionContext) throws TaskExecutionException { - Objects.requireNonNull(executionContext.get("bkuURL")); + try (InputStream in = getClass() + .getResourceAsStream("/process/spring/test/task/IdentityLink_Max_Mustermann.xml")) { + executionContext.put("IdentityLink", IOUtils.toString(in, "UTF-8")); - log.debug("Using bkuURL in order to retrieve IdentityLink."); + } catch (final IOException e) { + throw new TaskExecutionException(null, "", e); + } - try (InputStream in = getClass().getResourceAsStream("/process/spring/test/task/IdentityLink_Max_Mustermann.xml")) { - executionContext.put("IdentityLink", IOUtils.toString(in, "UTF-8")); - - } catch (IOException e) { - throw new TaskExecutionException(null, "", e); - } - - return null; - } + return null; + } } diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/SelectBKUTask.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/SelectBKUTask.java deleted file mode 100644 index 4cff97c6..00000000 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/SelectBKUTask.java +++ /dev/null @@ -1,63 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.process.spring.test.task; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - -import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; -import at.gv.egiz.eaaf.core.api.idp.process.Task; - -/** - * A dummy task simulating a bku selection. - *

    - * Asynchonous - *

    - * Enriches context data with: - *

      - *
    • {@code bkuURL}
    • - *
    - *

    - * - * @author tknall - * - */ -@Service("SelectBKUTask") -public class SelectBKUTask implements Task { - - private Logger log = LoggerFactory.getLogger(getClass()); - - @Override - public IRequest execute(IRequest penReq, ExecutionContext executionContext) { - log.debug("Providing BKU selection."); - executionContext.put("bkuURL", "https://127.0.0.1:3496/https-security-layer-request"); - return null; - } - -} diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/SelectBkuTask.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/SelectBkuTask.java new file mode 100644 index 00000000..a6e2ac2c --- /dev/null +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/SelectBkuTask.java @@ -0,0 +1,55 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.impl.idp.process.spring.test.task; + +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.api.idp.process.Task; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +/** + * A dummy task simulating a bku selection. + *

    + * Asynchonous + *

    + * Enriches context data with: + *

      + *
    • {@code bkuURL}
    • + *
    + *

    + * + * @author tknall + * + */ +@Service("SelectBKUTask") +public class SelectBkuTask implements Task { + + private final Logger log = LoggerFactory.getLogger(getClass()); + + @Override + public IRequest execute(final IRequest penReq, final ExecutionContext executionContext) { + log.debug("Providing BKU selection."); + executionContext.put("bkuURL", "https://127.0.0.1:3496/https-security-layer-request"); + return null; + } + +} diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/SignAuthBlockTask.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/SignAuthBlockTask.java index a2203676..41beefc8 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/SignAuthBlockTask.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/SignAuthBlockTask.java @@ -1,44 +1,35 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process.spring.test.task; import java.io.IOException; import java.io.InputStream; import java.util.Objects; - -import org.apache.commons.io.IOUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; import at.gv.egiz.eaaf.core.api.idp.process.Task; import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; /** * A dummy task simulating the signature of an auth block. @@ -58,29 +49,32 @@ import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; *
  • {@code SignedAuthBlock}
  • * *

    - * + * * @author tknall - * + * */ @Service("SignAuthBlockTask") -public class SignAuthBlockTask implements Task { +public class SignAuthBlockTask implements Task { + + private final Logger log = LoggerFactory.getLogger(getClass()); - private Logger log = LoggerFactory.getLogger(getClass()); + @Override + public IRequest execute(final IRequest penReq, final ExecutionContext executionContext) + throws TaskExecutionException { + Objects.requireNonNull(executionContext.get("IdentityLink")); + assert (Boolean.TRUE + .equals(Objects.requireNonNull(executionContext.get("isIdentityLinkValidated")))); + Objects.requireNonNull(executionContext.get("bkuURL")); - @Override - public IRequest execute(IRequest penReq, ExecutionContext executionContext) throws TaskExecutionException { - Objects.requireNonNull(executionContext.get("IdentityLink")); - assert (Boolean.TRUE.equals(Objects.requireNonNull(executionContext.get("isIdentityLinkValidated")))); - Objects.requireNonNull(executionContext.get("bkuURL")); + log.debug("Using validated IdentityLink and bkuURL in order to sign auth block."); + try (InputStream in = + getClass().getResourceAsStream("/process/spring/test/task/SignedAuthBlock.xml")) { + executionContext.put("SignedAuthBlock", IOUtils.toString(in, "UTF-8")); + } catch (final IOException e) { + throw new TaskExecutionException(null, "", e); - log.debug("Using validated IdentityLink and bkuURL in order to sign auth block."); - try (InputStream in = getClass().getResourceAsStream("/process/spring/test/task/SignedAuthBlock.xml")) { - executionContext.put("SignedAuthBlock", IOUtils.toString(in, "UTF-8")); - } catch (IOException e) { - throw new TaskExecutionException(null, "", e); - - } - return null; - } + } + return null; + } } diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/ValidateIdentityLinkTask.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/ValidateIdentityLinkTask.java index 7a1ba734..1a2cf5ee 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/ValidateIdentityLinkTask.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/ValidateIdentityLinkTask.java @@ -1,40 +1,31 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process.spring.test.task; import java.util.Objects; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; import at.gv.egiz.eaaf.core.api.idp.process.Task; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; /** * Dummy task simulating the validation of an IdentityLink. @@ -50,23 +41,23 @@ import at.gv.egiz.eaaf.core.api.idp.process.Task; *
  • {@code isIdentityLinkValidated}
  • * *

    - * - * @author tknall - * + * + * @author tknall + * */ @Service("ValidateIdentityLinkTask") public class ValidateIdentityLinkTask implements Task { - private Logger log = LoggerFactory.getLogger(getClass()); + private final Logger log = LoggerFactory.getLogger(getClass()); - @Override - public IRequest execute(IRequest penReq, ExecutionContext executionContext) { - Objects.requireNonNull(executionContext.get("IdentityLink")); + @Override + public IRequest execute(final IRequest penReq, final ExecutionContext executionContext) { + Objects.requireNonNull(executionContext.get("IdentityLink")); - log.debug("Validating IdentityLink."); + log.debug("Validating IdentityLink."); - executionContext.put("isIdentityLinkValidated", true); - return null; - } + executionContext.put("isIdentityLinkValidated", true); + return null; + } } diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/ValidateSignedAuthBlockTask.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/ValidateSignedAuthBlockTask.java index 1509033f..f07920cd 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/ValidateSignedAuthBlockTask.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/spring/test/task/ValidateSignedAuthBlockTask.java @@ -1,41 +1,32 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process.spring.test.task; import java.util.Objects; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; import at.gv.egiz.eaaf.core.api.idp.process.Task; import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; /** * A dummy task simulating the validation of an auth block. @@ -53,25 +44,28 @@ import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; *
  • {@code isSignedAuthBlockValidated}
  • * *

    - * + * * @author tknall - * + * */ @Service("ValidateSignedAuthBlockTask") public class ValidateSignedAuthBlockTask implements Task { - private Logger log = LoggerFactory.getLogger(getClass()); + private final Logger log = LoggerFactory.getLogger(getClass()); - @Override - public IRequest execute(IRequest penReq, ExecutionContext executionContext) throws TaskExecutionException { - Objects.requireNonNull(executionContext.get("IdentityLink")); - assert (Boolean.TRUE.equals(Objects.requireNonNull(executionContext.get("isIdentityLinkValidated")))); - Objects.requireNonNull(executionContext.get("SignedAuthBlock")); + @Override + public IRequest execute(final IRequest penReq, final ExecutionContext executionContext) + throws TaskExecutionException { + Objects.requireNonNull(executionContext.get("IdentityLink")); + assert (Boolean.TRUE + .equals(Objects.requireNonNull(executionContext.get("isIdentityLinkValidated")))); + Objects.requireNonNull(executionContext.get("SignedAuthBlock")); - log.debug("Using validated IdentityLink and signed auth block in order to validate signed auth block."); + log.debug( + "Using validated IdentityLink and signed auth block in order to validate signed auth block."); - executionContext.put("isSignedAuthBlockValidated", true); - return null; - } + executionContext.put("isSignedAuthBlockValidated", true); + return null; + } } diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/BooleanStringExpressionEvaluator.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/BooleanStringExpressionEvaluator.java index 517e7ce7..aa079f86 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/BooleanStringExpressionEvaluator.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/BooleanStringExpressionEvaluator.java @@ -1,50 +1,42 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process.test; import java.util.Objects; - -import org.apache.commons.lang3.BooleanUtils; - import at.gv.egiz.eaaf.core.api.idp.process.ExpressionEvaluationContext; import at.gv.egiz.eaaf.core.api.idp.process.ExpressionEvaluator; +import org.apache.commons.lang3.BooleanUtils; /** - * Expression evaluator that guesses the boolean value from a String. Refer to {@link BooleanUtils#toBoolean(String)} - * for further information. - * + * Expression evaluator that guesses the boolean value from a String. Refer to + * {@link BooleanUtils#toBoolean(String)} for further information. + * * @author tknall - * + * */ public class BooleanStringExpressionEvaluator implements ExpressionEvaluator { - @Override - public boolean evaluate(ExpressionEvaluationContext expressionContext, String expression) { - return BooleanUtils.toBoolean(Objects.requireNonNull(expression, "Expression must not be null.")); - } + @Override + public boolean evaluate(final ExpressionEvaluationContext expressionContext, final String expression) { + return BooleanUtils + .toBoolean(Objects.requireNonNull(expression, "Expression must not be null.")); + } } diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/HalloWeltTask.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/HalloWeltTask.java index 743a61da..40892476 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/HalloWeltTask.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/HalloWeltTask.java @@ -1,50 +1,42 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.process.test; + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ -import org.springframework.stereotype.Service; +package at.gv.egiz.eaaf.core.impl.idp.process.test; import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; import at.gv.egiz.eaaf.core.api.idp.process.Task; +import org.springframework.stereotype.Service; /** * Simple task that just outputs a "Hallo World" text to the console. - * + * * @author tknall - * + * */ @Service("HalloWeltTask") public class HalloWeltTask implements Task { - - @Override - public IRequest execute(IRequest pendingReq, ExecutionContext executionContext) { - System.out.println("Hallo Welt"); - return pendingReq; - } + + @Override + public IRequest execute(final IRequest pendingReq, final ExecutionContext executionContext) { + System.out.println("Hallo Welt"); + return pendingReq; + } } diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/HelloWorldTask.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/HelloWorldTask.java index c6da16b4..ce49e33d 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/HelloWorldTask.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/HelloWorldTask.java @@ -1,50 +1,42 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.process.test; + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ -import org.springframework.stereotype.Service; +package at.gv.egiz.eaaf.core.impl.idp.process.test; import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; import at.gv.egiz.eaaf.core.api.idp.process.Task; +import org.springframework.stereotype.Service; /** * Simple task that just outputs a "Hello World" text to the console. - * + * * @author tknall - * + * */ @Service("HelloWorldTask") public class HelloWorldTask implements Task { - - @Override - public IRequest execute(IRequest pendingReq, ExecutionContext executionContext) { - System.out.println("Hello World"); - return pendingReq; - } + + @Override + public IRequest execute(final IRequest pendingReq, final ExecutionContext executionContext) { + System.out.println("Hello World"); + return pendingReq; + } } diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/ProcessDefinitionParserTest.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/ProcessDefinitionParserTest.java index 90c8ce6f..2238ad09 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/ProcessDefinitionParserTest.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/ProcessDefinitionParserTest.java @@ -1,29 +1,22 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process.test; import static org.junit.Assert.assertEquals; @@ -31,12 +24,8 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.InputStream; - -import org.junit.Test; - import at.gv.egiz.eaaf.core.impl.idp.process.ProcessDefinitionParser; import at.gv.egiz.eaaf.core.impl.idp.process.ProcessDefinitionParserException; import at.gv.egiz.eaaf.core.impl.idp.process.model.EndEvent; @@ -45,119 +34,132 @@ import at.gv.egiz.eaaf.core.impl.idp.process.model.ProcessNode; import at.gv.egiz.eaaf.core.impl.idp.process.model.StartEvent; import at.gv.egiz.eaaf.core.impl.idp.process.model.TaskInfo; import at.gv.egiz.eaaf.core.impl.idp.process.model.Transition; +import org.junit.Test; public class ProcessDefinitionParserTest { - - @Test(expected = ProcessDefinitionParserException.class) - public void testParseInvalidProcessDefinition_MultipleStartEvents() throws IOException, ProcessDefinitionParserException { - try (InputStream in = getClass().getResourceAsStream("InvalidProcessDefinition_MultipleStartEvents.xml")) { - new ProcessDefinitionParser().parse(in); - } - } - - @Test(expected = ProcessDefinitionParserException.class) - public void testParseInvalidProcessDefinition_TransitionLoop() throws IOException, ProcessDefinitionParserException { - try (InputStream in = getClass().getResourceAsStream("InvalidProcessDefinition_TransitionLoop.xml")) { - new ProcessDefinitionParser().parse(in); - } - } - - @Test(expected = ProcessDefinitionParserException.class) - public void testParseInvalidProcessDefinition_TransitionStartsFromEndEvent() throws IOException, ProcessDefinitionParserException { - try (InputStream in = getClass().getResourceAsStream("InvalidProcessDefinition_TransitionStartsFromEndEvent.xml")) { - new ProcessDefinitionParser().parse(in); - } - } - - @Test(expected = ProcessDefinitionParserException.class) - public void testParseInvalidProcessDefinition_TransitionRefsTransition() throws IOException, ProcessDefinitionParserException { - try (InputStream in = getClass().getResourceAsStream("InvalidProcessDefinition_TransitionRefsTransition.xml")) { - new ProcessDefinitionParser().parse(in); - } - } - - @Test(expected = ProcessDefinitionParserException.class) - public void testParseInvalidProcessDefinition_NoStartEvents() throws IOException, ProcessDefinitionParserException { - try (InputStream in = getClass().getResourceAsStream("InvalidProcessDefinition_NoStartEvents.xml")) { - new ProcessDefinitionParser().parse(in); - } - } - - @Test - public void testParseSampleProcessDefinition() throws IOException, ProcessDefinitionParserException { - try (InputStream in = getClass().getResourceAsStream("/process/test/SampleProcessDefinition1.xml")) { - - ProcessDefinitionParser parser = new ProcessDefinitionParser(); - ProcessDefinition pd = parser.parse(in); - - assertNotNull(pd); - assertEquals("SampleProcess1", pd.getId()); - - // first assert tasks then transitions - // start event - StartEvent startEvent = pd.getStartEvent(); - assertNotNull(startEvent); - assertEquals("start", startEvent.getId()); - assertEquals(startEvent, pd.getProcessNode("start")); - // task1 - ProcessNode processNode = pd.getProcessNode("task1"); - assertNotNull(processNode); - assertTrue(processNode instanceof TaskInfo); - TaskInfo task1 = (TaskInfo) processNode; - assertEquals("task1", task1.getId()); - assertFalse(task1.isAsync()); - // task2 - processNode = pd.getProcessNode("task2"); - assertNotNull(processNode); - assertTrue(processNode instanceof TaskInfo); - TaskInfo task2 = (TaskInfo) processNode; - assertEquals("task2", task2.getId()); - assertTrue(task2.isAsync()); - // end event - processNode = pd.getProcessNode("end"); - assertNotNull(processNode); - assertTrue(processNode instanceof EndEvent); - EndEvent endEvent = (EndEvent) processNode; - assertEquals("end", endEvent.getId()); - - // assert transitions - // start event - assertNotNull(startEvent.getIncomingTransitions()); - assertTrue(startEvent.getIncomingTransitions().isEmpty()); - assertNotNull(startEvent.getOutgoingTransitions()); - assertEquals(1, startEvent.getOutgoingTransitions().size()); - // transition from start to task1 - Transition startToTask1 = startEvent.getOutgoingTransitions().get(0); - assertEquals("fromStart", startToTask1.getId()); - assertEquals(startEvent, startToTask1.getFrom()); - assertEquals(task1, startToTask1.getTo()); - assertEquals("true", startToTask1.getConditionExpression()); - // task1 - assertNotNull(task1.getIncomingTransitions()); - assertEquals(1, task1.getIncomingTransitions().size()); - assertEquals(startToTask1, task1.getIncomingTransitions().get(0)); - assertNotNull(task1.getOutgoingTransitions()); - assertEquals(1, task1.getOutgoingTransitions().size()); - // transition from task1 to task2 - Transition task1ToTask2 = task1.getOutgoingTransitions().get(0); - assertNull(task1ToTask2.getId()); - assertEquals(task1, task1ToTask2.getFrom()); - assertEquals(task2, task1ToTask2.getTo()); - assertNull(task1ToTask2.getConditionExpression()); - // task2 - assertNotNull(task2.getIncomingTransitions()); - assertEquals(1, task2.getIncomingTransitions().size()); - assertEquals(task1ToTask2, task2.getIncomingTransitions().get(0)); - assertNotNull(task2.getOutgoingTransitions()); - assertEquals(1, task2.getOutgoingTransitions().size()); - // transition from task2 to end - Transition task2ToEnd = task2.getOutgoingTransitions().get(0); - assertNull(task2ToEnd.getId()); - assertEquals(task2, task2ToEnd.getFrom()); - assertEquals(endEvent, task2ToEnd.getTo()); - assertNull(task2ToEnd.getConditionExpression()); - - } - } + + @Test(expected = ProcessDefinitionParserException.class) + public void testParseInvalidProcessDefinition_MultipleStartEvents() + throws IOException, ProcessDefinitionParserException { + try (InputStream in = + getClass().getResourceAsStream("InvalidProcessDefinition_MultipleStartEvents.xml")) { + new ProcessDefinitionParser().parse(in); + } + } + + @Test(expected = ProcessDefinitionParserException.class) + public void testParseInvalidProcessDefinition_TransitionLoop() + throws IOException, ProcessDefinitionParserException { + try (InputStream in = + getClass().getResourceAsStream("InvalidProcessDefinition_TransitionLoop.xml")) { + new ProcessDefinitionParser().parse(in); + } + } + + @Test(expected = ProcessDefinitionParserException.class) + public void testParseInvalidProcessDefinition_TransitionStartsFromEndEvent() + throws IOException, ProcessDefinitionParserException { + try (InputStream in = getClass() + .getResourceAsStream("InvalidProcessDefinition_TransitionStartsFromEndEvent.xml")) { + new ProcessDefinitionParser().parse(in); + } + } + + @Test(expected = ProcessDefinitionParserException.class) + public void testParseInvalidProcessDefinition_TransitionRefsTransition() + throws IOException, ProcessDefinitionParserException { + try (InputStream in = + getClass().getResourceAsStream("InvalidProcessDefinition_TransitionRefsTransition.xml")) { + new ProcessDefinitionParser().parse(in); + } + } + + @Test(expected = ProcessDefinitionParserException.class) + public void testParseInvalidProcessDefinition_NoStartEvents() + throws IOException, ProcessDefinitionParserException { + try (InputStream in = + getClass().getResourceAsStream("InvalidProcessDefinition_NoStartEvents.xml")) { + new ProcessDefinitionParser().parse(in); + } + } + + @Test + public void testParseSampleProcessDefinition() + throws IOException, ProcessDefinitionParserException { + try (InputStream in = + getClass().getResourceAsStream("/process/test/SampleProcessDefinition1.xml")) { + + final ProcessDefinitionParser parser = new ProcessDefinitionParser(); + final ProcessDefinition pd = parser.parse(in); + + assertNotNull(pd); + assertEquals("SampleProcess1", pd.getId()); + + // first assert tasks then transitions + // start event + final StartEvent startEvent = pd.getStartEvent(); + assertNotNull(startEvent); + assertEquals("start", startEvent.getId()); + assertEquals(startEvent, pd.getProcessNode("start")); + // task1 + ProcessNode processNode = pd.getProcessNode("task1"); + assertNotNull(processNode); + assertTrue(processNode instanceof TaskInfo); + final TaskInfo task1 = (TaskInfo) processNode; + assertEquals("task1", task1.getId()); + assertFalse(task1.isAsync()); + // task2 + processNode = pd.getProcessNode("task2"); + assertNotNull(processNode); + assertTrue(processNode instanceof TaskInfo); + final TaskInfo task2 = (TaskInfo) processNode; + assertEquals("task2", task2.getId()); + assertTrue(task2.isAsync()); + // end event + processNode = pd.getProcessNode("end"); + assertNotNull(processNode); + assertTrue(processNode instanceof EndEvent); + final EndEvent endEvent = (EndEvent) processNode; + assertEquals("end", endEvent.getId()); + + // assert transitions + // start event + assertNotNull(startEvent.getIncomingTransitions()); + assertTrue(startEvent.getIncomingTransitions().isEmpty()); + assertNotNull(startEvent.getOutgoingTransitions()); + assertEquals(1, startEvent.getOutgoingTransitions().size()); + // transition from start to task1 + final Transition startToTask1 = startEvent.getOutgoingTransitions().get(0); + assertEquals("fromStart", startToTask1.getId()); + assertEquals(startEvent, startToTask1.getFrom()); + assertEquals(task1, startToTask1.getTo()); + assertEquals("true", startToTask1.getConditionExpression()); + // task1 + assertNotNull(task1.getIncomingTransitions()); + assertEquals(1, task1.getIncomingTransitions().size()); + assertEquals(startToTask1, task1.getIncomingTransitions().get(0)); + assertNotNull(task1.getOutgoingTransitions()); + assertEquals(1, task1.getOutgoingTransitions().size()); + // transition from task1 to task2 + final Transition task1ToTask2 = task1.getOutgoingTransitions().get(0); + assertNull(task1ToTask2.getId()); + assertEquals(task1, task1ToTask2.getFrom()); + assertEquals(task2, task1ToTask2.getTo()); + assertNull(task1ToTask2.getConditionExpression()); + // task2 + assertNotNull(task2.getIncomingTransitions()); + assertEquals(1, task2.getIncomingTransitions().size()); + assertEquals(task1ToTask2, task2.getIncomingTransitions().get(0)); + assertNotNull(task2.getOutgoingTransitions()); + assertEquals(1, task2.getOutgoingTransitions().size()); + // transition from task2 to end + final Transition task2ToEnd = task2.getOutgoingTransitions().get(0); + assertNull(task2ToEnd.getId()); + assertEquals(task2, task2ToEnd.getFrom()); + assertEquals(endEvent, task2ToEnd.getTo()); + assertNull(task2ToEnd.getConditionExpression()); + + } + } } diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/ProcessEngineTest.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/ProcessEngineTest.java index dc45534e..9e8ce781 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/ProcessEngineTest.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/ProcessEngineTest.java @@ -1,38 +1,37 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process.test; import static at.gv.egiz.eaaf.core.impl.idp.process.ProcessInstanceState.NOT_STARTED; import static at.gv.egiz.eaaf.core.impl.idp.process.ProcessInstanceState.SUSPENDED; import static org.junit.Assert.assertEquals; - import java.io.IOException; import java.io.InputStream; - +import at.gv.egiz.eaaf.core.api.idp.process.ProcessEngine; +import at.gv.egiz.eaaf.core.exceptions.ProcessExecutionException; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl; +import at.gv.egiz.eaaf.core.impl.idp.process.ProcessDefinitionParser; +import at.gv.egiz.eaaf.core.impl.idp.process.ProcessDefinitionParserException; +import at.gv.egiz.eaaf.core.impl.idp.process.ProcessEngineImpl; +import at.gv.egiz.eaaf.core.impl.idp.process.ProcessInstance; import org.apache.commons.lang3.RandomStringUtils; import org.junit.Assert; import org.junit.Before; @@ -43,184 +42,199 @@ import org.springframework.context.ApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import at.gv.egiz.eaaf.core.api.idp.process.ProcessEngine; -import at.gv.egiz.eaaf.core.exceptions.ProcessExecutionException; -import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; -import at.gv.egiz.eaaf.core.impl.idp.module.test.TestRequestImpl; -import at.gv.egiz.eaaf.core.impl.idp.process.ProcessDefinitionParser; -import at.gv.egiz.eaaf.core.impl.idp.process.ProcessDefinitionParserException; -import at.gv.egiz.eaaf.core.impl.idp.process.ProcessEngineImpl; -import at.gv.egiz.eaaf.core.impl.idp.process.ProcessInstance; - @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/process/spring/test/SpringExpressionAwareProcessEngineTest-context.xml") public class ProcessEngineTest { - - @Autowired private static ProcessEngine pe; - - @Autowired private ApplicationContext applicationContext; - - private boolean isInitialized = false; - - @Before - public void init() throws IOException, ProcessDefinitionParserException { - - if (!isInitialized) { - final ProcessDefinitionParser pdp = new ProcessDefinitionParser(); - - if (pe == null) { - pe = applicationContext.getBean("processEngine", ProcessEngine.class); - - } - - ((ProcessEngineImpl) pe).setTransitionConditionExpressionEvaluator(new BooleanStringExpressionEvaluator()); - try (InputStream in = ProcessEngineTest.class.getResourceAsStream("/process/test/SampleProcessDefinition1.xml")) { - ((ProcessEngineImpl) pe).registerProcessDefinition(pdp.parse(in)); - } - try (InputStream in = ProcessEngineTest.class.getResourceAsStream("/process/test/SampleProcessDefinition2.xml")) { - ((ProcessEngineImpl) pe).registerProcessDefinition(pdp.parse(in)); - } - - try (InputStream in = ProcessEngineTest.class.getResourceAsStream("/process/test/SampleProcessDefinition4.xml")) { - ((ProcessEngineImpl) pe).registerProcessDefinition(pdp.parse(in)); - } - - try (InputStream in = ProcessEngineTest.class.getResourceAsStream("/process/test/SampleProcessDefinition5.xml")) { - ((ProcessEngineImpl) pe).registerProcessDefinition(pdp.parse(in)); - } - - //initHibernateForTesting(); - isInitialized = true; - } - } - - @Test - public void wrongProcessDefinition() throws IOException { - try (InputStream in = ProcessEngineTest.class.getResourceAsStream("/process/test/SampleProcessDefinition3.xml")) { - try { - ((ProcessEngineImpl) pe).registerProcessDefinition(in); - Assert.fail(); - - } catch (final ProcessDefinitionParserException e) { - Assert.assertTrue(e.getMessage().contains("Post-validation find an error in process definition")); - } - } - - } - - @Test - public void testSampleProcess1() throws IOException, ProcessDefinitionParserException, ProcessExecutionException { - - final TestRequestImpl testReq = new TestRequestImpl(); - - final String piId = pe.createProcessInstance("SampleProcess1"); - ProcessInstance pi = pe.getProcessInstance(piId); - assertEquals(NOT_STARTED, pi.getState()); - - // start process - testReq.setProcessInstanceID(piId); - pe.start(testReq); - pi = pe.getProcessInstance(piId); - assertEquals(SUSPENDED, pi.getState()); - - System.out.println("Do something asynchronously"); - testReq.setProcessInstanceID(piId); - pe.signal(testReq); - try { - pi = pe.getProcessInstance(piId); - throw new ProcessExecutionException("ProcessInstance should be removed already, but it was found."); - //assertEquals(ENDED, pi.getState()); - - } catch (final IllegalArgumentException e) { - // do nothing because processInstance should be already removed - - } - } - - @Test - public void testSampleProcess2() throws IOException, ProcessDefinitionParserException, ProcessExecutionException { - - final TestRequestImpl testReq = new TestRequestImpl(); - - final String piId = pe.createProcessInstance("SampleProcess2"); - ProcessInstance pi = pe.getProcessInstance(piId); - assertEquals(NOT_STARTED, pi.getState()); - - // start process - testReq.setProcessInstanceID(piId); - pe.start(testReq); - pi = pe.getProcessInstance(piId); - assertEquals(SUSPENDED, pi.getState()); - - System.out.println("Do something asynchronously"); - testReq.setProcessInstanceID(piId); - pe.signal(testReq); - try { - pi = pe.getProcessInstance(piId); - throw new ProcessExecutionException("ProcessInstance should be removed already, but it was found."); - //assertEquals(ENDED, pi.getState()); - - } catch (final IllegalArgumentException e) { - // do nothing because processInstance should be already removed - - } - - } - - @Test - public void testSampleProcess4() throws IOException, ProcessDefinitionParserException, ProcessExecutionException { - - final TestRequestImpl testReq = new TestRequestImpl(); - testReq.setPendingReqId(RandomStringUtils.randomAlphanumeric(5)); - - final String piId = pe.createProcessInstance("SampleProcess4"); - final ProcessInstance pi = pe.getProcessInstance(piId); - assertEquals(NOT_STARTED, pi.getState()); - - // start process - testReq.setProcessInstanceID(piId); - try { - pe.start(testReq); - Assert.fail("Task exception not handled"); - - } catch (final ProcessExecutionException e1) { - org.springframework.util.Assert.isInstanceOf(TaskExecutionException.class, e1.getCause(), "No TaskExecutionException"); - Assert.assertEquals("Wrong error-msg", "jUnit Test", e1.getCause().getMessage()); - Assert.assertEquals("Wrong pendingReqId", testReq.getPendingRequestId(), ((TaskExecutionException) e1.getCause()).getPendingRequestID()); - org.springframework.util.Assert.isInstanceOf(RuntimeException.class, e1.getCause().getCause(), "Wrong Exception in TaskExecutionException"); - } - - - } - - @Test - public void testSampleProcess5() throws IOException, ProcessDefinitionParserException, ProcessExecutionException { - - final TestRequestImpl testReq = new TestRequestImpl(); - - final String piId = pe.createProcessInstance("SampleProcess5"); - ProcessInstance pi = pe.getProcessInstance(piId); - assertEquals(NOT_STARTED, pi.getState()); - - // start process - testReq.setProcessInstanceID(piId); - pe.start(testReq); - - try { - pi = pe.getProcessInstance(piId); - - } catch (final IllegalArgumentException e) { - Assert.assertTrue("wrong error-msg", e.getMessage().contains("does not/no longer exist.")); - Assert.assertTrue("wrong process-instance-id", e.getMessage().contains(piId)); - - } - - - } - - @Test(expected = IllegalArgumentException.class) - public void testProcessInstanceDoesNotExist() { - pe.getProcessInstance("does not exist"); - } + + @Autowired + private static ProcessEngine pe; + + @Autowired + private ApplicationContext applicationContext; + + private boolean isInitialized = false; + + /** + * jUnit test set-up. + * + * @throws IOException in case of an error + * @throws ProcessDefinitionParserException in case of an error + */ + @Before + public void init() throws IOException, ProcessDefinitionParserException { + + if (!isInitialized) { + final ProcessDefinitionParser pdp = new ProcessDefinitionParser(); + + if (pe == null) { + pe = applicationContext.getBean("processEngine", ProcessEngine.class); + + } + + ((ProcessEngineImpl) pe) + .setTransitionConditionExpressionEvaluator(new BooleanStringExpressionEvaluator()); + try (InputStream in = ProcessEngineTest.class + .getResourceAsStream("/process/test/SampleProcessDefinition1.xml")) { + ((ProcessEngineImpl) pe).registerProcessDefinition(pdp.parse(in)); + } + try (InputStream in = ProcessEngineTest.class + .getResourceAsStream("/process/test/SampleProcessDefinition2.xml")) { + ((ProcessEngineImpl) pe).registerProcessDefinition(pdp.parse(in)); + } + + try (InputStream in = ProcessEngineTest.class + .getResourceAsStream("/process/test/SampleProcessDefinition4.xml")) { + ((ProcessEngineImpl) pe).registerProcessDefinition(pdp.parse(in)); + } + + try (InputStream in = ProcessEngineTest.class + .getResourceAsStream("/process/test/SampleProcessDefinition5.xml")) { + ((ProcessEngineImpl) pe).registerProcessDefinition(pdp.parse(in)); + } + + // initHibernateForTesting(); + isInitialized = true; + } + } + + @Test + public void wrongProcessDefinition() throws IOException { + try (InputStream in = + ProcessEngineTest.class.getResourceAsStream("/process/test/SampleProcessDefinition3.xml")) { + try { + ((ProcessEngineImpl) pe).registerProcessDefinition(in); + Assert.fail(); + + } catch (final ProcessDefinitionParserException e) { + Assert.assertTrue( + e.getMessage().contains("Post-validation find an error in process definition")); + } + } + + } + + @Test + public void testSampleProcess1() + throws IOException, ProcessDefinitionParserException, ProcessExecutionException { + + final TestRequestImpl testReq = new TestRequestImpl(); + + final String piId = pe.createProcessInstance("SampleProcess1"); + ProcessInstance pi = pe.getProcessInstance(piId); + assertEquals(NOT_STARTED, pi.getState()); + + // start process + testReq.setProcessInstanceID(piId); + pe.start(testReq); + pi = pe.getProcessInstance(piId); + assertEquals(SUSPENDED, pi.getState()); + + System.out.println("Do something asynchronously"); + testReq.setProcessInstanceID(piId); + pe.signal(testReq); + try { + pi = pe.getProcessInstance(piId); + throw new ProcessExecutionException( + "ProcessInstance should be removed already, but it was found."); + // assertEquals(ENDED, pi.getState()); + + } catch (final IllegalArgumentException e) { + // do nothing because processInstance should be already removed + + } + } + + @Test + public void testSampleProcess2() + throws IOException, ProcessDefinitionParserException, ProcessExecutionException { + + final TestRequestImpl testReq = new TestRequestImpl(); + + final String piId = pe.createProcessInstance("SampleProcess2"); + ProcessInstance pi = pe.getProcessInstance(piId); + assertEquals(NOT_STARTED, pi.getState()); + + // start process + testReq.setProcessInstanceID(piId); + pe.start(testReq); + pi = pe.getProcessInstance(piId); + assertEquals(SUSPENDED, pi.getState()); + + System.out.println("Do something asynchronously"); + testReq.setProcessInstanceID(piId); + pe.signal(testReq); + try { + pi = pe.getProcessInstance(piId); + throw new ProcessExecutionException( + "ProcessInstance should be removed already, but it was found."); + // assertEquals(ENDED, pi.getState()); + + } catch (final IllegalArgumentException e) { + // do nothing because processInstance should be already removed + + } + + } + + @Test + public void testSampleProcess4() + throws IOException, ProcessDefinitionParserException, ProcessExecutionException { + + final TestRequestImpl testReq = new TestRequestImpl(); + testReq.setPendingReqId(RandomStringUtils.randomAlphanumeric(5)); + + final String piId = pe.createProcessInstance("SampleProcess4"); + final ProcessInstance pi = pe.getProcessInstance(piId); + assertEquals(NOT_STARTED, pi.getState()); + + // start process + testReq.setProcessInstanceID(piId); + try { + pe.start(testReq); + Assert.fail("Task exception not handled"); + + } catch (final ProcessExecutionException e1) { + org.springframework.util.Assert.isInstanceOf(TaskExecutionException.class, e1.getCause(), + "No TaskExecutionException"); + Assert.assertEquals("Wrong error-msg", "jUnit Test", e1.getCause().getMessage()); + Assert.assertEquals("Wrong pendingReqId", testReq.getPendingRequestId(), + ((TaskExecutionException) e1.getCause()).getPendingRequestID()); + org.springframework.util.Assert.isInstanceOf(RuntimeException.class, e1.getCause().getCause(), + "Wrong Exception in TaskExecutionException"); + } + + + } + + @Test + public void testSampleProcess5() + throws IOException, ProcessDefinitionParserException, ProcessExecutionException { + + final TestRequestImpl testReq = new TestRequestImpl(); + + final String piId = pe.createProcessInstance("SampleProcess5"); + ProcessInstance pi = pe.getProcessInstance(piId); + assertEquals(NOT_STARTED, pi.getState()); + + // start process + testReq.setProcessInstanceID(piId); + pe.start(testReq); + + try { + pi = pe.getProcessInstance(piId); + + } catch (final IllegalArgumentException e) { + Assert.assertTrue("wrong error-msg", e.getMessage().contains("does not/no longer exist.")); + Assert.assertTrue("wrong process-instance-id", e.getMessage().contains(piId)); + + } + + + } + + @Test(expected = IllegalArgumentException.class) + public void testProcessInstanceDoesNotExist() { + pe.getProcessInstance("does not exist"); + } } diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/StopProcessFlagTask.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/StopProcessFlagTask.java index 8cd76eaa..2ef58729 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/StopProcessFlagTask.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/StopProcessFlagTask.java @@ -1,52 +1,44 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.process.test; + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ -import org.springframework.stereotype.Service; +package at.gv.egiz.eaaf.core.impl.idp.process.test; import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; import at.gv.egiz.eaaf.core.api.idp.process.Task; +import org.springframework.stereotype.Service; /** * Simple task that just outputs a "Hello World" text to the console. - * + * * @author tknall - * + * */ @Service("HelloWorldTask") public class StopProcessFlagTask implements Task { - - @Override - public IRequest execute(IRequest pendingReq, ExecutionContext executionContext) { - System.out.println("Stop process-flow dynamically from task"); - executionContext.setCanceleProcessFlag(); - - return pendingReq; - } + + @Override + public IRequest execute(final IRequest pendingReq, final ExecutionContext executionContext) { + System.out.println("Stop process-flow dynamically from task"); + executionContext.setCanceleProcessFlag(); + + return pendingReq; + } } diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/ThrowExceptionTask.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/ThrowExceptionTask.java index ecd139c8..639121d6 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/ThrowExceptionTask.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/idp/process/test/ThrowExceptionTask.java @@ -1,52 +1,46 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.idp.process.test; + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ -import org.springframework.stereotype.Service; +package at.gv.egiz.eaaf.core.impl.idp.process.test; import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; import at.gv.egiz.eaaf.core.api.idp.process.Task; import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import org.springframework.stereotype.Service; /** * Simple task that just outputs a "Hello World" text to the console. - * + * * @author tknall - * + * */ @Service("HelloWorldTask") public class ThrowExceptionTask implements Task { - - @Override - public IRequest execute(IRequest pendingReq, ExecutionContext executionContext) throws TaskExecutionException { - System.out.println("Stop process-flow dynamically from task"); - throw new TaskExecutionException(pendingReq, "jUnit Test", new RuntimeException("jUnit test exception handling")); - - } + + @Override + public IRequest execute(final IRequest pendingReq, final ExecutionContext executionContext) + throws TaskExecutionException { + System.out.println("Stop process-flow dynamically from task"); + throw new TaskExecutionException(pendingReq, "jUnit Test", + new RuntimeException("jUnit test exception handling")); + + } } diff --git a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/utils/KeyValueUtilsTest.java b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/utils/KeyValueUtilsTest.java index 9df11ed6..d5ce24c5 100644 --- a/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/utils/KeyValueUtilsTest.java +++ b/eaaf_core/src/test/java/at/gv/egiz/eaaf/core/impl/utils/KeyValueUtilsTest.java @@ -8,7 +8,6 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; - import org.apache.commons.lang3.RandomStringUtils; import org.junit.Assert; import org.junit.Test; @@ -18,430 +17,430 @@ import org.junit.runners.BlockJUnit4ClassRunner; @RunWith(BlockJUnit4ClassRunner.class) public class KeyValueUtilsTest { - @Test - public void getFirstChildTest_1() { - final String prefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(5); - final String child = RandomStringUtils.randomAlphabetic(2); - final String key = prefix + KeyValueUtils.KEY_DELIMITER + child + KeyValueUtils.KEY_DELIMITER + RandomStringUtils.randomAlphabetic(4); - final String resut = KeyValueUtils.getFirstChildAfterPrefix(key, prefix); - Assert.assertEquals("First child not match", child, resut); - - } - - @Test - public void getFirstChildTest_2() { - final String prefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(5); - final String child = RandomStringUtils.randomAlphabetic(2); - final String key = prefix + KeyValueUtils.KEY_DELIMITER + child; - final String resut = KeyValueUtils.getFirstChildAfterPrefix(key, prefix); - Assert.assertEquals("First child not match", child, resut); - - } - - @Test - public void getFirstChildTest_3() { - final String prefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(5); - final String child = RandomStringUtils.randomAlphabetic(2); - final String key = prefix + KeyValueUtils.KEY_DELIMITER + child; - final String resut = KeyValueUtils.getFirstChildAfterPrefix(key, key); - Assert.assertNull("First child not null", resut); - - } - - @Test - public void getFirstChildTest_4() { - final String prefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(5); - final String child = RandomStringUtils.randomAlphabetic(2); - final String key = prefix + KeyValueUtils.KEY_DELIMITER + child; - final String resut = KeyValueUtils.getFirstChildAfterPrefix( - RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + key, - key); - Assert.assertNull("First child not null", resut); - - } - - @Test - public void getFirstChildTest_5() { - final String prefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(5); - final String child = RandomStringUtils.randomAlphabetic(2); - final String key = child + KeyValueUtils.KEY_DELIMITER + prefix; - final String resut = KeyValueUtils.getFirstChildAfterPrefix(key, null); - Assert.assertEquals("First child not match", child, resut); - - } - - @Test - public void getFirstChildTest_6() { - final String prefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(5); - final String child = RandomStringUtils.randomAlphabetic(2); - final String key = prefix + KeyValueUtils.KEY_DELIMITER + child; - final String resut = KeyValueUtils.getFirstChildAfterPrefix(key, key); - Assert.assertNull("First child not null", resut); - - } - - @Test - public void getPrefixFromKey_1() { - final String prefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(5); - final String child = RandomStringUtils.randomAlphabetic(2); - final String key = prefix + KeyValueUtils.KEY_DELIMITER + child; - final String resut = KeyValueUtils.getPrefixFromKey(key, child); - Assert.assertEquals("Prefix not match", prefix, resut); - - } - - @Test - public void getPrefixFromKey_2() { - final String child = RandomStringUtils.randomAlphabetic(2); - final String resut = KeyValueUtils.getPrefixFromKey(null, child); - Assert.assertNull("Prefix not null", resut); - - } - - @Test - public void getPrefixFromKey_3() { - final String prefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(5); - final String key = prefix + KeyValueUtils.KEY_DELIMITER + RandomStringUtils.randomAlphabetic(4); - final String resut = KeyValueUtils.getPrefixFromKey(key, RandomStringUtils.randomAlphabetic(5)); - Assert.assertNull("Prefix not null", resut); - - } - - @Test - public void getPrefixFromKey_4() { - final String prefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(5); - final String child = KeyValueUtils.KEY_DELIMITER + RandomStringUtils.randomAlphabetic(2); - final String key = prefix + child; - final String resut = KeyValueUtils.getPrefixFromKey(key, child); - Assert.assertEquals("Prefix not match", prefix, resut); - - } - - @Test - public void getPrefixFromKey_5() { - final String key = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(5); - final String resut = KeyValueUtils.getPrefixFromKey(key, null); - Assert.assertNull("Prefix not null", resut); - - } - - @Test - public void getRemovePrefixesFromKeys_1() { - final String testPrefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(5); - final Map testMap = generateTestMap(testPrefix , 5, 5); - - final Map result = KeyValueUtils.removePrefixFromKeys(testMap, testPrefix); - Assert.assertNotNull("Result is null", result); - Assert.assertFalse("Result is empty", result.isEmpty()); - Assert.assertEquals("Result size not match", 5, result.size()); - final Iterator> it = result.entrySet().iterator(); - while(it.hasNext()) { - final Entry next = it.next(); - Assert.assertNotNull("Key is null", next.getKey()); - Assert.assertNotNull("Value is null", next.getValue()); - Assert.assertTrue("Key is null", testMap.containsKey(testPrefix + "." + next.getKey())); - Assert.assertEquals("Value not match", testMap.get(testPrefix + "." + next.getKey()), next.getValue()); - - } - - } - - @Test - public void getSubSetWithPrefixTest_1() { - final String testPrefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(5); - final Map testMap = generateTestMap(testPrefix , 5, 5); - - final Map result = KeyValueUtils.getSubSetWithPrefix(testMap, testPrefix); - Assert.assertNotNull("Result is null", result); - Assert.assertFalse("Result is empty", result.isEmpty()); - Assert.assertEquals("Result size not match", 5, result.size()); - final Iterator> it = result.entrySet().iterator(); - while(it.hasNext()) { - final Entry next = it.next(); - Assert.assertNotNull("Key is null", next.getKey()); - Assert.assertNotNull("Value is null", next.getValue()); - Assert.assertTrue("Key is null", testMap.containsKey(testPrefix + "." + next.getKey())); - Assert.assertEquals("Value not match", testMap.get(testPrefix + "." + next.getKey()), next.getValue()); - - } - - } - - @Test - public void makeKeysAbsolutTest_1() { - final String absTestPrefixtestPrefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(5); - final String prefix = absTestPrefixtestPrefix + "." + RandomStringUtils.randomAlphabetic(4); - final Map testMap = generateTestMap(prefix, 5, 5); - final Map result = KeyValueUtils.makeKeysAbsolut( - testMap, - absTestPrefixtestPrefix, - prefix); - - Assert.assertNotNull("Result is null", result); - Assert.assertFalse("Result is empty", result.isEmpty()); - Assert.assertEquals("Result size not match", 10, result.size()); - final Iterator> it = result.entrySet().iterator(); - while(it.hasNext()) { - final Entry next = it.next(); - Assert.assertNotNull("Key is null", next.getKey()); - Assert.assertNotNull("Value is null", next.getValue()); - if (testMap.containsKey(next.getKey())) - Assert.assertEquals("Value not match", testMap.get(next.getKey()), next.getValue()); - else { - Assert.assertTrue("Key not found", testMap.containsKey( - next.getKey().substring( - absTestPrefixtestPrefix.length() + 1)) - ); - Assert.assertEquals("Value not match", testMap.get( - next.getKey().substring( - absTestPrefixtestPrefix.length() + 1)), - next.getValue()); - } - } - } - - @Test - public void getParentKeyTest_1() { - final String testPrefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(5); - final String result = KeyValueUtils.getParentKey(testPrefix + "." + RandomStringUtils.randomAlphabetic(5)); - Assert.assertNotNull("Result is null", result); - Assert.assertEquals("Parent not match", testPrefix, result); - - } - - @Test - public void getParentKeyTest_2() { - final String result = KeyValueUtils.getParentKey(RandomStringUtils.randomAlphabetic(5)); - Assert.assertNotNull("Result is null", result); - Assert.assertTrue("Result not empty", result.isEmpty()); - - } - - @Test - public void findNextFreeListCoutnerTest_1() { - final String testPrefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(5); - final Set propList = new HashSet(); - propList.add(testPrefix + ".1"); - propList.add(testPrefix + ".2"); - propList.add(testPrefix + ".0"); - propList.add(testPrefix + ".4"); - propList.add(testPrefix + ".3"); - - final int result = KeyValueUtils.findNextFreeListCounter(propList, testPrefix); - Assert.assertEquals("Next free element not fount", 5, result); - - } - - @Test - public void findNextFreeListCoutnerTest_2() { - final String testPrefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(5); - final Set propList = new HashSet(); - propList.add(testPrefix + ".1"); - propList.add(testPrefix + ".5"); - propList.add(testPrefix + ".0"); - propList.add(testPrefix + ".4"); - propList.add(testPrefix + ".3"); - - final int result = KeyValueUtils.findNextFreeListCounter(propList, testPrefix); - Assert.assertEquals("Next free element not fount", 6, result); - - } - - @Test - public void findNextFreeListCoutnerTest_3() { - final String testPrefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(5); - final Set propList = new HashSet();; - - final int result = KeyValueUtils.findNextFreeListCounter(propList, testPrefix); - Assert.assertEquals("Next free element not fount", 0, result); - - } - - @Test - public void findNextFreeListCoutnerTest_4() { - final String testPrefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER - + RandomStringUtils.randomAlphabetic(5); - final java.util.List propList = new ArrayList(); - - final int result = KeyValueUtils.findNextFreeListCounter(propList.stream().toArray(String[]::new), testPrefix); - Assert.assertEquals("Next free element not fount", 0, result); - - } - - @Test - public void normalizeCSVValueStringTest_1() { - final String csv1 = RandomStringUtils.randomAlphanumeric(5); - final String csv2 = RandomStringUtils.randomAlphanumeric(5); - final String csv3 = RandomStringUtils.randomAlphanumeric(5); - final String csv4 = RandomStringUtils.randomAlphanumeric(5); - final String testValue = " " + csv1 + " ," + csv2 + "," + csv3 + "\n," + csv4 + " "; - - final String result = KeyValueUtils.normalizeCSVValueString(testValue); - - Assert.assertNotNull("Result is null", result); - Assert.assertFalse("Result is empty", result.isEmpty()); - final String[] check = result.split(","); - Assert.assertEquals("Result size wrong", 4, check.length); - Assert.assertEquals("Result 1 wrong", csv1, check[0]); - Assert.assertEquals("Result 2 wrong", csv2, check[1]); - Assert.assertEquals("Result 3 wrong", csv3, check[2]); - Assert.assertEquals("Result 4 wrong", csv4, check[3]); - - } - - @Test - public void isCSVValueStringTest_1() { - final String csv1 = RandomStringUtils.randomAlphanumeric(5); - final String csv2 = RandomStringUtils.randomAlphanumeric(5); - final String csv3 = RandomStringUtils.randomAlphanumeric(5); - final String csv4 = RandomStringUtils.randomAlphanumeric(5); - final String testValue = " " + csv1 + " ," + csv2 + "," + csv3 + "\n," + csv4 + " "; - final boolean result = KeyValueUtils.isCSVValueString(testValue); - Assert.assertTrue("CSV value not detected", result); - - } - - @Test - public void isCSVValueStringTest_2() { - final String csv1 = RandomStringUtils.randomAlphanumeric(5); - final String testValue = " " + csv1 + " ,"; - final boolean result = KeyValueUtils.isCSVValueString(testValue); - Assert.assertFalse("CSV value not detected", result); - - } - - @Test - public void isCSVValueStringTest_3() { - final String csv1 = RandomStringUtils.randomAlphanumeric(5); - final String testValue = " " + csv1; - final boolean result = KeyValueUtils.isCSVValueString(testValue); - Assert.assertFalse("CSV value not detected", result); - - } - - @Test - public void getListOfCSVValuesTest_1() { - final String csv1 = RandomStringUtils.randomAlphanumeric(5); - final String csv2 = RandomStringUtils.randomAlphanumeric(5); - final String csv3 = RandomStringUtils.randomAlphanumeric(5); - final String csv4 = RandomStringUtils.randomAlphanumeric(5); - final String testValue = " " + csv1 + " ," + csv2 + "," + csv3 + "\n," + csv4 + " "; - - final List result = KeyValueUtils.getListOfCSVValues(testValue); - - Assert.assertNotNull("Result is null", result); - Assert.assertFalse("Result is empty", result.isEmpty()); - Assert.assertEquals("Result size wrong", 4, result.size()); - Assert.assertEquals("Result 1 wrong", csv1, result.get(0)); - Assert.assertEquals("Result 2 wrong", csv2, result.get(1)); - Assert.assertEquals("Result 3 wrong", csv3, result.get(2)); - Assert.assertEquals("Result 4 wrong", csv4, result.get(3)); - - } - - @Test - public void convertListToMapTest_1() { - final java.util.List propList = new ArrayList(); - final String prefix = RandomStringUtils.randomAlphabetic(4) + "."; - final String key1 = RandomStringUtils.randomAlphabetic(5); - final String value1 = RandomStringUtils.randomAlphanumeric(10); - final String key2 = RandomStringUtils.randomAlphabetic(5); - final String value2 = RandomStringUtils.randomAlphanumeric(10); - final String key3 = RandomStringUtils.randomAlphabetic(5); - final String value3 = RandomStringUtils.randomAlphanumeric(10); - final String key4 = RandomStringUtils.randomAlphabetic(5); - final String value4 = RandomStringUtils.randomAlphanumeric(10); - final String key5 = RandomStringUtils.randomAlphabetic(5); - final String value5 = RandomStringUtils.randomAlphanumeric(10); - final String key6 = RandomStringUtils.randomAlphabetic(5); - final String value6 = "="+RandomStringUtils.randomAlphanumeric(10); - - propList.add(prefix + key1 + "=" + value1); - propList.add(prefix + key2 + "=" + value2); - propList.add(prefix + key3 + "=" + value3); - propList.add(prefix + key4 + "=" + value4); - propList.add(prefix + key5 + "+" + value5); - propList.add(prefix + key6 + "=" + value6); - - final Map result = KeyValueUtils.convertListToMap(propList); - Assert.assertNotNull("Result is null", result); - Assert.assertFalse("Result is empty", result.isEmpty()); - Assert.assertEquals("Result size not match", 5, result.size()); - - Assert.assertTrue("Key1 not found", result.containsKey(prefix+key1)); - Assert.assertEquals("Value1 not found", value1, result.get(prefix+key1)); - Assert.assertTrue("Key2 not found", result.containsKey(prefix+key2)); - Assert.assertEquals("Value2 not found", value2, result.get(prefix+key2)); - Assert.assertTrue("Key3 not found", result.containsKey(prefix+key3)); - Assert.assertEquals("Value3 not found", value3, result.get(prefix+key3)); - Assert.assertTrue("Key4 not found", result.containsKey(prefix+key4)); - Assert.assertEquals("Value4 not found", value4, result.get(prefix+key4)); - - } - - @Test - public void convertListToMapTest_2() { - final java.util.List propList = new ArrayList(); - - final Map result = KeyValueUtils.convertListToMap(propList); - Assert.assertNotNull("Result is null", result); - Assert.assertTrue("Result is not empty", result.isEmpty()); - - } - - private Map generateTestMap(String testPrefix, int entriesWithPrefix, int entriesWithoutPrefix) { - final Map result = new HashMap(); - for (int i=0; i testMap = generateTestMap(testPrefix, 5, 5); + + final Map result = KeyValueUtils.removePrefixFromKeys(testMap, testPrefix); + Assert.assertNotNull("Result is null", result); + Assert.assertFalse("Result is empty", result.isEmpty()); + Assert.assertEquals("Result size not match", 5, result.size()); + final Iterator> it = result.entrySet().iterator(); + while (it.hasNext()) { + final Entry next = it.next(); + Assert.assertNotNull("Key is null", next.getKey()); + Assert.assertNotNull("Value is null", next.getValue()); + Assert.assertTrue("Key is null", testMap.containsKey(testPrefix + "." + next.getKey())); + Assert.assertEquals("Value not match", testMap.get(testPrefix + "." + next.getKey()), + next.getValue()); + + } + + } + + @Test + public void getSubSetWithPrefixTest_1() { + final String testPrefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(5); + final Map testMap = generateTestMap(testPrefix, 5, 5); + + final Map result = KeyValueUtils.getSubSetWithPrefix(testMap, testPrefix); + Assert.assertNotNull("Result is null", result); + Assert.assertFalse("Result is empty", result.isEmpty()); + Assert.assertEquals("Result size not match", 5, result.size()); + final Iterator> it = result.entrySet().iterator(); + while (it.hasNext()) { + final Entry next = it.next(); + Assert.assertNotNull("Key is null", next.getKey()); + Assert.assertNotNull("Value is null", next.getValue()); + Assert.assertTrue("Key is null", testMap.containsKey(testPrefix + "." + next.getKey())); + Assert.assertEquals("Value not match", testMap.get(testPrefix + "." + next.getKey()), + next.getValue()); + + } + + } + + @Test + public void makeKeysAbsolutTest_1() { + final String absTestPrefixtestPrefix = RandomStringUtils.randomAlphabetic(4) + + KeyValueUtils.KEY_DELIMITER + RandomStringUtils.randomAlphabetic(6) + + KeyValueUtils.KEY_DELIMITER + RandomStringUtils.randomAlphabetic(5); + final String prefix = absTestPrefixtestPrefix + "." + RandomStringUtils.randomAlphabetic(4); + final Map testMap = generateTestMap(prefix, 5, 5); + final Map result = + KeyValueUtils.makeKeysAbsolut(testMap, absTestPrefixtestPrefix, prefix); + + Assert.assertNotNull("Result is null", result); + Assert.assertFalse("Result is empty", result.isEmpty()); + Assert.assertEquals("Result size not match", 10, result.size()); + final Iterator> it = result.entrySet().iterator(); + while (it.hasNext()) { + final Entry next = it.next(); + Assert.assertNotNull("Key is null", next.getKey()); + Assert.assertNotNull("Value is null", next.getValue()); + if (testMap.containsKey(next.getKey())) { + Assert.assertEquals("Value not match", testMap.get(next.getKey()), next.getValue()); + } else { + Assert.assertTrue("Key not found", + testMap.containsKey(next.getKey().substring(absTestPrefixtestPrefix.length() + 1))); + Assert.assertEquals("Value not match", + testMap.get(next.getKey().substring(absTestPrefixtestPrefix.length() + 1)), + next.getValue()); + } + } + } + + @Test + public void getParentKeyTest_1() { + final String testPrefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(5); + final String result = + KeyValueUtils.getParentKey(testPrefix + "." + RandomStringUtils.randomAlphabetic(5)); + Assert.assertNotNull("Result is null", result); + Assert.assertEquals("Parent not match", testPrefix, result); + + } + + @Test + public void getParentKeyTest_2() { + final String result = KeyValueUtils.getParentKey(RandomStringUtils.randomAlphabetic(5)); + Assert.assertNotNull("Result is null", result); + Assert.assertTrue("Result not empty", result.isEmpty()); + + } + + @Test + public void findNextFreeListCoutnerTest_1() { + final String testPrefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(5); + final Set propList = new HashSet<>(); + propList.add(testPrefix + ".1"); + propList.add(testPrefix + ".2"); + propList.add(testPrefix + ".0"); + propList.add(testPrefix + ".4"); + propList.add(testPrefix + ".3"); + + final int result = KeyValueUtils.findNextFreeListCounter(propList, testPrefix); + Assert.assertEquals("Next free element not fount", 5, result); + + } + + @Test + public void findNextFreeListCoutnerTest_2() { + final String testPrefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(5); + final Set propList = new HashSet<>(); + propList.add(testPrefix + ".1"); + propList.add(testPrefix + ".5"); + propList.add(testPrefix + ".0"); + propList.add(testPrefix + ".4"); + propList.add(testPrefix + ".3"); + + final int result = KeyValueUtils.findNextFreeListCounter(propList, testPrefix); + Assert.assertEquals("Next free element not fount", 6, result); + + } + + @Test + public void findNextFreeListCoutnerTest_3() { + final String testPrefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(5); + final Set propList = new HashSet<>(); + + final int result = KeyValueUtils.findNextFreeListCounter(propList, testPrefix); + Assert.assertEquals("Next free element not fount", 0, result); + + } + + @Test + public void findNextFreeListCoutnerTest_4() { + final String testPrefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(5); + final java.util.List propList = new ArrayList<>(); + + final int result = + KeyValueUtils.findNextFreeListCounter(propList.stream().toArray(String[]::new), testPrefix); + Assert.assertEquals("Next free element not fount", 0, result); + + } + + @Test + public void normalizeCsvValueStringTest_1() { + final String csv1 = RandomStringUtils.randomAlphanumeric(5); + final String csv2 = RandomStringUtils.randomAlphanumeric(5); + final String csv3 = RandomStringUtils.randomAlphanumeric(5); + final String csv4 = RandomStringUtils.randomAlphanumeric(5); + final String testValue = " " + csv1 + " ," + csv2 + "," + csv3 + "\n," + csv4 + " "; + + final String result = KeyValueUtils.normalizeCsvValueString(testValue); + + Assert.assertNotNull("Result is null", result); + Assert.assertFalse("Result is empty", result.isEmpty()); + final String[] check = result.split(","); + Assert.assertEquals("Result size wrong", 4, check.length); + Assert.assertEquals("Result 1 wrong", csv1, check[0]); + Assert.assertEquals("Result 2 wrong", csv2, check[1]); + Assert.assertEquals("Result 3 wrong", csv3, check[2]); + Assert.assertEquals("Result 4 wrong", csv4, check[3]); + + } + + @Test + public void isCsvValueStringTest_1() { + final String csv1 = RandomStringUtils.randomAlphanumeric(5); + final String csv2 = RandomStringUtils.randomAlphanumeric(5); + final String csv3 = RandomStringUtils.randomAlphanumeric(5); + final String csv4 = RandomStringUtils.randomAlphanumeric(5); + final String testValue = " " + csv1 + " ," + csv2 + "," + csv3 + "\n," + csv4 + " "; + final boolean result = KeyValueUtils.isCsvValueString(testValue); + Assert.assertTrue("CSV value not detected", result); + + } + + @Test + public void isCsvValueStringTest_2() { + final String csv1 = RandomStringUtils.randomAlphanumeric(5); + final String testValue = " " + csv1 + " ,"; + final boolean result = KeyValueUtils.isCsvValueString(testValue); + Assert.assertFalse("CSV value not detected", result); + + } + + @Test + public void isCsvValueStringTest_3() { + final String csv1 = RandomStringUtils.randomAlphanumeric(5); + final String testValue = " " + csv1; + final boolean result = KeyValueUtils.isCsvValueString(testValue); + Assert.assertFalse("CSV value not detected", result); + + } + + @Test + public void getListOfCsvValuesTest_1() { + final String csv1 = RandomStringUtils.randomAlphanumeric(5); + final String csv2 = RandomStringUtils.randomAlphanumeric(5); + final String csv3 = RandomStringUtils.randomAlphanumeric(5); + final String csv4 = RandomStringUtils.randomAlphanumeric(5); + final String testValue = " " + csv1 + " ," + csv2 + "," + csv3 + "\n," + csv4 + " "; + + final List result = KeyValueUtils.getListOfCsvValues(testValue); + + Assert.assertNotNull("Result is null", result); + Assert.assertFalse("Result is empty", result.isEmpty()); + Assert.assertEquals("Result size wrong", 4, result.size()); + Assert.assertEquals("Result 1 wrong", csv1, result.get(0)); + Assert.assertEquals("Result 2 wrong", csv2, result.get(1)); + Assert.assertEquals("Result 3 wrong", csv3, result.get(2)); + Assert.assertEquals("Result 4 wrong", csv4, result.get(3)); + + } + + @Test + public void convertListToMapTest_1() { + final java.util.List propList = new ArrayList<>(); + final String prefix = RandomStringUtils.randomAlphabetic(4) + "."; + final String key1 = RandomStringUtils.randomAlphabetic(5); + final String value1 = RandomStringUtils.randomAlphanumeric(10); + final String key2 = RandomStringUtils.randomAlphabetic(5); + final String value2 = RandomStringUtils.randomAlphanumeric(10); + final String key3 = RandomStringUtils.randomAlphabetic(5); + final String value3 = RandomStringUtils.randomAlphanumeric(10); + final String key4 = RandomStringUtils.randomAlphabetic(5); + final String value4 = RandomStringUtils.randomAlphanumeric(10); + final String key5 = RandomStringUtils.randomAlphabetic(5); + final String value5 = RandomStringUtils.randomAlphanumeric(10); + final String key6 = RandomStringUtils.randomAlphabetic(5); + final String value6 = "=" + RandomStringUtils.randomAlphanumeric(10); + + propList.add(prefix + key1 + "=" + value1); + propList.add(prefix + key2 + "=" + value2); + propList.add(prefix + key3 + "=" + value3); + propList.add(prefix + key4 + "=" + value4); + propList.add(prefix + key5 + "+" + value5); + propList.add(prefix + key6 + "=" + value6); + + final Map result = KeyValueUtils.convertListToMap(propList); + Assert.assertNotNull("Result is null", result); + Assert.assertFalse("Result is empty", result.isEmpty()); + Assert.assertEquals("Result size not match", 5, result.size()); + + Assert.assertTrue("Key1 not found", result.containsKey(prefix + key1)); + Assert.assertEquals("Value1 not found", value1, result.get(prefix + key1)); + Assert.assertTrue("Key2 not found", result.containsKey(prefix + key2)); + Assert.assertEquals("Value2 not found", value2, result.get(prefix + key2)); + Assert.assertTrue("Key3 not found", result.containsKey(prefix + key3)); + Assert.assertEquals("Value3 not found", value3, result.get(prefix + key3)); + Assert.assertTrue("Key4 not found", result.containsKey(prefix + key4)); + Assert.assertEquals("Value4 not found", value4, result.get(prefix + key4)); + + } + + @Test + public void convertListToMapTest_2() { + final java.util.List propList = new ArrayList<>(); + + final Map result = KeyValueUtils.convertListToMap(propList); + Assert.assertNotNull("Result is null", result); + Assert.assertTrue("Result is not empty", result.isEmpty()); + + } + + private Map generateTestMap(final String testPrefix, final int entriesWithPrefix, + final int entriesWithoutPrefix) { + final Map result = new HashMap<>(); + for (int i = 0; i < entriesWithPrefix; i++) { + result.put(testPrefix + KeyValueUtils.KEY_DELIMITER + RandomStringUtils.randomAlphabetic(5), + RandomStringUtils.randomAlphabetic(5)); + } + + final String key = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(5); + for (int i = 0; i < entriesWithoutPrefix; i++) { + result.put(key + KeyValueUtils.KEY_DELIMITER + RandomStringUtils.randomAlphabetic(5), + RandomStringUtils.randomAlphabetic(5)); + } + + return result; + + } + } diff --git a/eaaf_core/src/test/resources/SpringTest-context_authManager.xml b/eaaf_core/src/test/resources/SpringTest-context_authManager.xml index b8eef11f..9c94d4a7 100644 --- a/eaaf_core/src/test/resources/SpringTest-context_authManager.xml +++ b/eaaf_core/src/test/resources/SpringTest-context_authManager.xml @@ -1,47 +1,48 @@ - - - - - - - - - - - - - - - - - - - - - - - - - + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:context="http://www.springframework.org/schema/context" + xmlns:tx="http://www.springframework.org/schema/tx" + xmlns:aop="http://www.springframework.org/schema/aop" + xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd + http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/eaaf_core/src/test/resources/SpringTest-context_eaaf_core.xml b/eaaf_core/src/test/resources/SpringTest-context_eaaf_core.xml index 523e9fc7..77d70740 100644 --- a/eaaf_core/src/test/resources/SpringTest-context_eaaf_core.xml +++ b/eaaf_core/src/test/resources/SpringTest-context_eaaf_core.xml @@ -1,20 +1,20 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:context="http://www.springframework.org/schema/context" + xmlns:tx="http://www.springframework.org/schema/tx" + xmlns:aop="http://www.springframework.org/schema/aop" + xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd + http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> + + + + + + - - - - - - diff --git a/eaaf_core/src/test/resources/log4j.xml b/eaaf_core/src/test/resources/log4j.xml index 90e3c763..83d8b703 100644 --- a/eaaf_core/src/test/resources/log4j.xml +++ b/eaaf_core/src/test/resources/log4j.xml @@ -1,19 +1,21 @@ - + - - - - - - + + + + + + - - - - + + + + diff --git a/eaaf_core/src/test/resources/process/spring/test/SpringExpressionAwareProcessEngineTest-context.xml b/eaaf_core/src/test/resources/process/spring/test/SpringExpressionAwareProcessEngineTest-context.xml index ebbd89e9..b84aad57 100644 --- a/eaaf_core/src/test/resources/process/spring/test/SpringExpressionAwareProcessEngineTest-context.xml +++ b/eaaf_core/src/test/resources/process/spring/test/SpringExpressionAwareProcessEngineTest-context.xml @@ -1,6 +1,4 @@ - + class="at.gv.egiz.eaaf.core.impl.idp.process.dao.ProcessInstanceStoreDaoImpl"/> @@ -37,10 +35,10 @@ class="at.gv.egiz.eaaf.core.impl.idp.process.test.ThrowExceptionTask"/> + class="at.gv.egiz.eaaf.core.impl.idp.process.spring.test.task.SelectBkuTask"/> + class="at.gv.egiz.eaaf.core.impl.idp.process.spring.test.task.CreateSaml1AssertionTask"/> diff --git a/eaaf_core_api/pom.xml b/eaaf_core_api/pom.xml index d3233dec..c16bf39c 100644 --- a/eaaf_core_api/pom.xml +++ b/eaaf_core_api/pom.xml @@ -1,6 +1,8 @@ - + 4.0.0 at.gv.egiz @@ -11,7 +13,7 @@ eaaf_core_api API for EAAF core components Core components API for identity managment implementations - + European Union Public License, version 1.2 (EUPL-1.2) @@ -28,41 +30,41 @@ https://www.egiz.gv.at - + UTF-8 - + - - org.slf4j - slf4j-api - - - com.google.code.findbugs - jsr305 - - - javax.servlet - javax.servlet-api - provided - - + + org.slf4j + slf4j-api + + + com.google.code.findbugs + jsr305 + + + javax.servlet + javax.servlet-api + provided + + junit junit test - - - eaaf_core_api - - - - src/main/resources - - - + + + eaaf_core_api + + + + src/main/resources + + + org.apache.maven.plugins @@ -73,44 +75,44 @@ 1.8 - - - compile - testCompile - - + + + compile + testCompile + + - org.apache.maven.plugins - maven-jar-plugin - 3.1.0 - - - - test-jar - - - - - + org.apache.maven.plugins + maven-jar-plugin + 3.1.0 + + + + test-jar + + + + + - - maven-surefire-plugin - ${surefire.version} - - 1 - - - - org.apache.maven.surefire - surefire-junit47 - ${surefire.version} - - - - + + maven-surefire-plugin + ${surefire.version} + + 1 + + + + org.apache.maven.surefire + surefire-junit47 + ${surefire.version} + + + + - + diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/IGarbageCollectorProcessing.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/IGarbageCollectorProcessing.java index d7c81050..1b8f0d48 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/IGarbageCollectorProcessing.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/IGarbageCollectorProcessing.java @@ -1,40 +1,35 @@ /******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + *
    + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* + *
    + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + *
    + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ + package at.gv.egiz.eaaf.core.api; /** + * Application internal garbage collector that can be used to clean caches as example. + * * @author tlenz * */ public interface IGarbageCollectorProcessing { - /** - * This method gets executed by the MOA garbage collector at regular intervals. - * - */ - public void runGarbageCollector(); + /** + * This method gets executed by the MOA garbage collector at regular intervals. + * + */ + public void runGarbageCollector(); } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/IPostStartupInitializable.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/IPostStartupInitializable.java index e0c2ebf7..c9eccbba 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/IPostStartupInitializable.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/IPostStartupInitializable.java @@ -1,45 +1,38 @@ /******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + *
    + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* + *
    + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + *
    + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ + package at.gv.egiz.eaaf.core.api; /** - * + * Interface initialize a Object when the MOA-ID-Auth start-up process is fully completed. + * * @author tlenz * - * Interface initialize a Object when the MOA-ID-Auth start-up process is fully completed * */ public interface IPostStartupInitializable { - /** - * This method is called once when MOA-ID-Auth start-up process is fully completed - * - */ - public void executeAfterStartup(); + /** + * This method is called once when MOA-ID-Auth start-up process is fully completed. + * + */ + public void executeAfterStartup(); } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/IRequest.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/IRequest.java index 77d718af..03575223 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/IRequest.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/IRequest.java @@ -1,257 +1,249 @@ /******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + *
    + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* -* - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. + *
    + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + *
    + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ + package at.gv.egiz.eaaf.core.api; +import java.io.Serializable; import java.util.Map; +import javax.annotation.Nonnull; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; + +public interface IRequest extends Serializable { + + /** + * Indicates the module, which implements this authentication protocol. The class, which is + * referenced, had to implement the 'IModulInfo' interface. + * + * @return Full-qualified name of the class which implements this protocol + */ + public String requestedModule(); + + /** + * Indicates the protocol specific action, which should executed if the request is processed. The + * class, which is referenced, had to implement the 'IAction' interface. + * + * @return Full-qualified name of the class which implements the action + */ + public String requestedAction(); + + /** + * Unique identifier, which indicates the service provider. + * + * @return Unique identifier for the service provider + */ + public String getSpEntityId(); + + /** + * Indicates the passive flag in authentication requests. If the passive flag is set, the + * identification and authentication process failed if no active SSO session is found. + * + * @return true, if the is passive flag is set in authentication request, otherwise false + */ + public boolean isPassiv(); + + /** + * Indicates the force authentication flag in authentication request If this flag is set, a new + * identification and authentication process is carried out in any case. + * + * @return true, if the force authentication flag is set, otherwise false + */ + public boolean forceAuth(); + + + /** + * Returns a generic request-data object with is stored with a specific identifier. + * + * @param key The specific identifier of the request-data object + * @return The request-data object or null if no data is found with this key + */ + public Object getRawData(String key); + + /** + * Returns a generic request-data object with is stored with a specific identifier. + * + * @param key The specific identifier of the request-data object + * @param clazz The class type which is stored with this key + * @return The request-data object or null if no data is found with this key + */ + public T getRawData(String key, final Class clazz); + + /** + * Store a generic data-object into pending request with a specific identifier. + * + * @param key Identifier for this data-object + * @param object Generic data-object which should be stored. This data-object had to be implement + * the 'java.io.Serializable' interface + * @throws SessionDataStorageException Error message if the data-object can not stored to generic + * request-data storage + */ + public void setRawDataToTransaction(String key, Object object) throws EaafStorageException; + + /** + * Store generic data-objects into pending request with specific identifiers. + * + * @param map Map with Identifiers and values + * @throws SessionDataStorageException Error message if the data-object can not stored to generic + * request-data storage + */ + public void setRawDataToTransaction(Map map) throws EaafStorageException; + + /** + * Wrap the internal dataStorage map into a DAO. + * + * @param wrapper DOA to access SessionData + * @return + */ + @Nonnull + public T getSessionData(@Nonnull Class wrapper); + + /** + * Hold the identifier of this request object. This identifier can be used to load the request + * from request storage. + * + * @return Request identifier + */ + public String getPendingRequestId(); + + + /** + * Hold the identifier of the SSO-Session which is associated with this request. + * + * @return SSO session-identifier if a associated session exists, otherwise null + */ + public String getInternalSsoSessionIdentifier(); + + /** + * Set the in SSO session identifier, if an active SSO session exists. + * + * @param internalSsoSessionId Internal SSO session id + */ + public void setInternalSsoSessionIdentifier(String internalSsoSessionId); + + /** + * Holds a unique transaction identifier, which could be used for looging This transaction + * identifier is unique for a single identification and authentication process. + * + * @return Unique transaction identifier. + */ + public String getUniqueTransactionIdentifier(); + + /** + * Holds a unique session identifier, which could be used for logging This session identifier is + * unique for the full Single Sign-On session time. + * + * @return Unique session identifier + */ + public String getUniqueSessionIdentifier(); + + + /** + * Hold the identifier if the process instance, which is associated with this request. + * + * @return ProcessInstanceID if this request is associated with a authentication process, + * otherwise null + */ + public String getProcessInstanceId(); + + + /** + * get the IDP URL PreFix, which was used for authentication request. + * + * @return IDP URL PreFix. The URL prefix always ends without / + */ + public String getAuthUrl(); + + /** + * get the IDP URL PreFix, which was used for authentication request. + * + * @return IDP URL PreFix. The URL prefix always ends without / + */ + public String getAuthUrlWithOutSlash(); + + /** + * Indicates if this pending request needs authentication. + * + * @return true if this request needs authentication, otherwise false + */ + public boolean isNeedAuthentication(); + + /** + * Indicates, if this pending request needs Single Sign-On (SSO) functionality. + * + * @return true if this request needs SSO, otherwise false + */ + public boolean needSingleSignOnFunctionality(); + + /** + * Set flag that this requests needs SSO. + * + * @param needSso true if SSO is needed, otherwise false + */ + public void setNeedSingleSignOnFunctionality(boolean needSso); + + + /** + * Indicates, if this pending request needs an additional user consent. + * + * @return true if this request needs additional user consent, otherwise false + */ + public boolean isNeedUserConsent(); + + public void setNeedUserConsent(boolean needConsent); + + /** + * Indicates, if this pending request is already authenticated. + * + * @return true if this request is already authenticated, otherwise false + */ + public boolean isAuthenticated(); + + public void setAuthenticated(boolean isAuthenticated); + + /** + * Get get Service-Provider configuration which is associated with this request. + * + * @return Service-Provider configuration + */ + public IspConfiguration getServiceProviderConfiguration(); + + + /** + * Get get Service-Provider configuration which is associated with this request. + * + * @return Service-Provider configuration as object + */ + public T getServiceProviderConfiguration(final Class decorator); + + + /** + * Indicates, if this pending-request is aborted by the user. + * + * @return true, if it is aborted, otherwise false + */ + public boolean isAbortedByUser(); + + /** + * Set the 'isAboredByUser' flag of this pending-request. + * + * @param isAborted true, if the user has abort the authentication process, otherwise false + */ + public void setAbortedByUser(boolean isAborted); -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.exceptions.EAAFStorageException; - -public interface IRequest { - - /** - * Indicates the module, which implements this authentication protocol. - * The class, which is referenced, had to implement the 'IModulInfo' interface. - * - * @return Full-qualified name of the class which implements this protocol - */ - public String requestedModule(); - - /** - * Indicates the protocol specific action, which should executed if the request is processed. - * The class, which is referenced, had to implement the 'IAction' interface. - * - * @return Full-qualified name of the class which implements the action - */ - public String requestedAction(); - - /** - * Unique identifier, which indicates the service provider. - * - * @return Unique identifier for the service provider - */ - public String getSPEntityId(); - - /** - * Indicates the passive flag in authentication requests. - * If the passive flag is set, the identification and authentication process - * failed if no active SSO session is found. - * - * @return true, if the is passive flag is set in authentication request, otherwise false - */ - public boolean isPassiv(); - - /** - * Indicates the force authentication flag in authentication request - * If this flag is set, a new identification and authentication process - * is carried out in any case. - * - * @return true, if the force authentication flag is set, otherwise false - */ - public boolean forceAuth(); - - - /** - * Returns a generic request-data object with is stored with a specific identifier - * - * @param key The specific identifier of the request-data object - * @return The request-data object or null if no data is found with this key - */ - public Object getRawData(String key); - - /** - * Returns a generic request-data object with is stored with a specific identifier - * - * @param key The specific identifier of the request-data object - * @param clazz The class type which is stored with this key - * @return The request-data object or null if no data is found with this key - */ - public T getRawData(String key, final Class clazz); - - /** - * Store a generic data-object into pending request with a specific identifier - * - * @param key Identifier for this data-object - * @param object Generic data-object which should be stored. This data-object had to be implement the 'java.io.Serializable' interface - * @throws SessionDataStorageException Error message if the data-object can not stored to generic request-data storage - */ - public void setRawDataToTransaction(String key, Object object) throws EAAFStorageException; - - /** - * Store generic data-objects into pending request with specific identifiers - * - * @param map Map with Identifiers and values - * @throws SessionDataStorageException Error message if the data-object can not stored to generic request-data storage - */ - public void setRawDataToTransaction(Map map) throws EAAFStorageException; - - /** - * Wrap the internal dataStorage map into a DAO - * - * @param wrapper DOA to access SessionData - * @return - */ - public T getSessionData(Class wrapper); - - /** - * Hold the identifier of this request object. - * This identifier can be used to load the request from request storage - * - * @return Request identifier - */ - public String getPendingRequestId(); - - - /** - * Hold the identifier of the SSO-Session which is associated with this request - * - * @return SSO session-identifier if a associated session exists, otherwise null - */ - public String getInternalSSOSessionIdentifier(); - - /** - * Set the in SSO session identifier, if an active SSO session exists - * - * @param internalSSOSessionId - */ - public void setInternalSSOSessionIdentifier(String internalSSOSessionId); - - /** - * Holds a unique transaction identifier, which could be used for looging - * This transaction identifier is unique for a single identification and authentication process - * - * @return Unique transaction identifier. - */ - public String getUniqueTransactionIdentifier(); - - /** - * Holds a unique session identifier, which could be used for logging - * This session identifier is unique for the full Single Sign-On session time - * - * @return Unique session identifier - */ - public String getUniqueSessionIdentifier(); - - - /** - * Hold the identifier if the process instance, which is associated with this request - * - * @return ProcessInstanceID if this request is associated with a authentication process, otherwise null - */ - public String getProcessInstanceId(); - - - /** - * get the IDP URL PreFix, which was used for authentication request - * - * @return IDP URL PreFix . The URL prefix always ends without / - */ - public String getAuthURL(); - public String getAuthURLWithOutSlash(); - - /** - * Indicates if this pending request needs authentication - * - * @return true if this request needs authentication, otherwise false - */ - public boolean isNeedAuthentication(); - - /** - * Indicates, if this pending request needs Single Sign-On (SSO) functionality - * - * @return true if this request needs SSO, otherwise false - */ - public boolean needSingleSignOnFunctionality(); - public void setNeedSingleSignOnFunctionality(boolean needSSO); - - - /** - * Indicates, if this pending request needs an additional user consent - * - * @return true if this request needs additional user consent, otherwise false - */ - public boolean isNeedUserConsent(); - public void setNeedUserConsent(boolean needConsent); - - /** - * Indicates, if this pending request is already authenticated - * - * @return true if this request is already authenticated, otherwise false - */ - public boolean isAuthenticated(); - public void setAuthenticated(boolean isAuthenticated); - - /** - * Get get Service-Provider configuration which is associated with this request. - * - * @return Service-Provider configuration - */ - public ISPConfiguration getServiceProviderConfiguration(); - - - /** - * Get get Service-Provider configuration which is associated with this request. - * - * @return Service-Provider configuration as object - */ - public T getServiceProviderConfiguration(final Class decorator); - - - /** - * Indicates, if this pending-request is aborted by the user - * - * @return true, if it is aborted, otherwise false - */ - public boolean isAbortedByUser(); - - /** - * Set the 'isAboredByUser' flag of this pending-request - * - * @param b true, if the user has abort the authentication process, otherwise false - */ - public void setAbortedByUser(boolean isAborted); - } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/IRequestStorage.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/IRequestStorage.java index 56179d55..c76dfe76 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/IRequestStorage.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/IRequestStorage.java @@ -1,90 +1,67 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/* - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. */ + package at.gv.egiz.eaaf.core.api; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.exceptions.PendingReqIdValidationException; /** + * Service to store pending requests. + * * @author tlenz * */ public interface IRequestStorage { - /** - * Get a pending-request from storage - * - * @param pendingReqID Id of the pending request - * @return - * @throws PendingReqIdValidationException if the pendingRequestId was invalid - */ - public IRequest getPendingRequest(String pendingReqID) throws PendingReqIdValidationException; - - /** - * Store a pending-request in storage - * - * @param pendingRequest - * @throws EAAFException - */ - public void storePendingRequest(IRequest pendingRequest) throws EAAFException; - - /** - * Remove a pending-request from storage - * - * @param pendingReqId Id of the pending request - */ - public void removePendingRequest(String pendingReqId); - - /** - * change the pendingRequestId of a pending-request - * - * @param pendingRequest current pending-reqeust - * @return new pending-requestId - * @throws EAAFException - */ - public String changePendingRequestID(IRequest pendingRequest) throws EAAFException; - + /** + * Get a pending-request from storage. + * + * @param pendingReqID Id of the pending request + * @return Pending Request Object + * @throws PendingReqIdValidationException if the pendingRequestId was invalid + */ + public IRequest getPendingRequest(String pendingReqID) throws PendingReqIdValidationException; + + /** + * Store a pending-request in storage. + * + * @param pendingRequest Pending-Request object to store + * @throws EaafException In case of a storage error + */ + public void storePendingRequest(IRequest pendingRequest) throws EaafException; + + /** + * Remove a pending-request from storage. + * + * @param pendingReqId Id of the pending request + */ + public void removePendingRequest(String pendingReqId); + + /** + * change the pendingRequestId of a pending-request. + * + * @param pendingRequest current pending-reqeust + * @return new pending-requestId + * @throws EaafException in case of a storage error + */ + public String changePendingRequestID(IRequest pendingRequest) throws EaafException; + } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/IStatusMessenger.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/IStatusMessenger.java index 04323dea..633f1583 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/IStatusMessenger.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/IStatusMessenger.java @@ -1,29 +1,22 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.api; import javax.annotation.Nonnull; @@ -31,56 +24,56 @@ import javax.annotation.Nullable; public interface IStatusMessenger { - //internal error codes defined in EAAFCore - public static final String CODES_INTERNAL_ERROR_GENERIC = "internal.00"; - public static final String CODES_INTERNAL_ERROR_AUTH_NOSPCONFIG = "auth.00"; - public static final String CODES_INTERNAL_ERROR_AUTH_NOPENDIGREQID = "auth.26"; - public static final String CODES_INTERNAL_ERROR_AUTH_TIMEOUT = "auth.28"; - public static final String CODES_INTERNAL_ERROR_AUTH_USERSTOP = "auth.21"; - public static final String CODES_INTERNAL_ERROR_AUTH_REQUEST_INVALID = "auth.38"; - - public static final String CODES_INTERNAL_ILLEGAL_STATE = "process.03"; - - //external error codes defined in EAAFCore - public static final String CODES_EXTERNAL_ERROR_GENERIC = "9199"; - public static final String CODES_EXTERNAL_ERROR_PROCESSENGINE = "1099"; - - - /** - * Get the message corresponding to a given message ID. - * - * @param messageId The ID of the message. - * @param parameters The parameters to fill in into the message arguments. - * @return The formatted message. - */ - @Nonnull - public String getMessage(String messageId, Object[] parameters); - - /** - * Get the message corresponding to a given message ID. - * - * @param messageId The ID of the message. - * @param parameters The parameters to fill in into the message arguments. - * @return The formatted message, or null if no message was fround - */ - @Nullable - public String getMessageWithoutDefault(String messageId, Object[] parameters); - - /** - * Get external errorCode from from Exception - * - * @param throwable - * @return - */ - public String getResponseErrorCode(Throwable throwable); - - - /** - * Map internal to external errorCode - * - * @param intErrorCode - * @return - */ - public String mapInternalErrorToExternalError(String intErrorCode); - + // internal error codes defined in EAAFCore + public static final String CODES_INTERNAL_ERROR_GENERIC = "internal.00"; + public static final String CODES_INTERNAL_ERROR_AUTH_NOSPCONFIG = "auth.00"; + public static final String CODES_INTERNAL_ERROR_AUTH_NOPENDIGREQID = "auth.26"; + public static final String CODES_INTERNAL_ERROR_AUTH_TIMEOUT = "auth.28"; + public static final String CODES_INTERNAL_ERROR_AUTH_USERSTOP = "auth.21"; + public static final String CODES_INTERNAL_ERROR_AUTH_REQUEST_INVALID = "auth.38"; + + public static final String CODES_INTERNAL_ILLEGAL_STATE = "process.03"; + + // external error codes defined in EAAFCore + public static final String CODES_EXTERNAL_ERROR_GENERIC = "9199"; + public static final String CODES_EXTERNAL_ERROR_PROCESSENGINE = "1099"; + + + /** + * Get the message corresponding to a given message ID. + * + * @param messageId The ID of the message. + * @param parameters The parameters to fill in into the message arguments. + * @return The formatted message. + */ + @Nonnull + public String getMessage(String messageId, Object[] parameters); + + /** + * Get the message corresponding to a given message ID. + * + * @param messageId The ID of the message. + * @param parameters The parameters to fill in into the message arguments. + * @return The formatted message, or null if no message was fround + */ + @Nullable + public String getMessageWithoutDefault(String messageId, Object[] parameters); + + /** + * Get external errorCode from from Exception. + * + * @param throwable Reason of error + * @return external error code + */ + public String getResponseErrorCode(Throwable throwable); + + + /** + * Map internal to external errorCode. + * + * @param intErrorCode internal error code + * @return external error code + */ + public String mapInternalErrorToExternalError(String intErrorCode); + } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/EAAFConfigConstants.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/EAAFConfigConstants.java index b75f9eb3..d3529592 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/EAAFConfigConstants.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/EAAFConfigConstants.java @@ -1,24 +1,20 @@ /******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ /******************************************************************************* *******************************************************************************/ @@ -28,5 +24,5 @@ package at.gv.egiz.eaaf.core.api.data; public class EAAFConfigConstants { - public static final String SERVICE_UNIQUEIDENTIFIER = "uniqueID"; //publicURLPrefix + public static final String SERVICE_UNIQUEIDENTIFIER = "uniqueID"; // publicURLPrefix } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/EAAFConstants.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/EAAFConstants.java index 32ea7a6f..dda3703a 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/EAAFConstants.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/EAAFConstants.java @@ -1,24 +1,20 @@ /******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ /******************************************************************************* *******************************************************************************/ @@ -29,52 +25,55 @@ package at.gv.egiz.eaaf.core.api.data; public class EAAFConstants { - public static final String CONTENTTYPE_HTML_UTF8 = "text/html; charset=UTF-8"; - - //http request parameters for process management - public static final String PARAM_HTTP_TARGET_PENDINGREQUESTID = "pendingid"; - public static final String PARAM_HTTP_ERROR_CODE = "errorid"; - public static final String PARAM_HTTP_STOP_PROCESS = "stopAuthProcess"; - - - public static final String EIDAS_LOA_PREFIX = "http://eidas.europa.eu/LoA/"; - public static final String EIDAS_LOA_LOW = EIDAS_LOA_PREFIX + "low"; - public static final String EIDAS_LOA_SUBSTANTIAL = EIDAS_LOA_PREFIX + "substantial"; - public static final String EIDAS_LOA_HIGH = EIDAS_LOA_PREFIX + "high"; - - public static final String EIDAS_LOA_MATCHING_MINIMUM = "minimum"; - public static final String EIDAS_LOA_MATCHING_EXACT = "exact"; - - //Austrian specific prefixes for pseudonyms of users - public static final String URN_PART_WBPK = "wbpk+"; - public static final String URN_PART_EIDAS = "eidasid+"; - - - public static final String URN_PREFIX = "urn:publicid:gv.at"; - public static final String URN_PREFIX_BASEID = URN_PREFIX + ":baseid"; - public static final String URN_PREFIX_CDID = URN_PREFIX + ":cdid+"; - public static final String URN_PREFIX_BPK = URN_PREFIX_CDID + "bpk"; - public static final String URN_PREFIX_WBPK = URN_PREFIX + ":" + URN_PART_WBPK; - public static final String URN_PREFIX_EIDAS = URN_PREFIX + ":" + URN_PART_EIDAS; - public static final String URN_PREFIX_OW_BPK = URN_PREFIX_CDID + "OW"; - - - //Authentication process data_constants - public static final String UNIQUESESSIONIDENTIFIER = "eaaf_uniqueSessionIdentifier"; - public static final String AUTH_DATA_CREATED = "eaaf_authdata_created"; - - - public static final String PROCESS_ENGINE_PREFIX = "PARAMS_"; - public static final String PROCESS_ENGINE_PENDINGREQUESTID = PROCESS_ENGINE_PREFIX + PARAM_HTTP_TARGET_PENDINGREQUESTID; - public static final String PROCESS_ENGINE_SERVICE_PROVIDER_ENTITYID = PROCESS_ENGINE_PREFIX + "uniqueSPId"; - public static final String PROCESS_ENGINE_SSL_CLIENT_CERTIFICATE = PROCESS_ENGINE_PREFIX + "holderofkey_cert"; - public static final String PROCESS_ENGINE_REQUIRES_NO_POSTAUTH_REDIRECT - = PROCESS_ENGINE_PREFIX + "requireNoPostAuthRedirect"; - public static final String PROCESSCONTEXT_SWITCH_LANGUAGE = "changeLanguage"; - - public static final int ALLOWED_TIME_JITTER = 5; //minutes - public static final String COUNTRYCODE_AUSTRIA = "AT"; - - public static final String TESTCREDENTIALROOTOID = "1.2.40.0.10.2.4.1"; - + public static final String CONTENTTYPE_HTML_UTF8 = "text/html; charset=UTF-8"; + + // http request parameters for process management + public static final String PARAM_HTTP_TARGET_PENDINGREQUESTID = "pendingid"; + public static final String PARAM_HTTP_ERROR_CODE = "errorid"; + public static final String PARAM_HTTP_STOP_PROCESS = "stopAuthProcess"; + + + public static final String EIDAS_LOA_PREFIX = "http://eidas.europa.eu/LoA/"; + public static final String EIDAS_LOA_LOW = EIDAS_LOA_PREFIX + "low"; + public static final String EIDAS_LOA_SUBSTANTIAL = EIDAS_LOA_PREFIX + "substantial"; + public static final String EIDAS_LOA_HIGH = EIDAS_LOA_PREFIX + "high"; + + public static final String EIDAS_LOA_MATCHING_MINIMUM = "minimum"; + public static final String EIDAS_LOA_MATCHING_EXACT = "exact"; + + // Austrian specific prefixes for pseudonyms of users + public static final String URN_PART_WBPK = "wbpk+"; + public static final String URN_PART_EIDAS = "eidasid+"; + + + public static final String URN_PREFIX = "urn:publicid:gv.at"; + public static final String URN_PREFIX_BASEID = URN_PREFIX + ":baseid"; + public static final String URN_PREFIX_CDID = URN_PREFIX + ":cdid+"; + public static final String URN_PREFIX_BPK = URN_PREFIX_CDID + "bpk"; + public static final String URN_PREFIX_WBPK = URN_PREFIX + ":" + URN_PART_WBPK; + public static final String URN_PREFIX_EIDAS = URN_PREFIX + ":" + URN_PART_EIDAS; + public static final String URN_PREFIX_OW_BPK = URN_PREFIX_CDID + "OW"; + + + // Authentication process data_constants + public static final String UNIQUESESSIONIDENTIFIER = "eaaf_uniqueSessionIdentifier"; + public static final String AUTH_DATA_CREATED = "eaaf_authdata_created"; + + + public static final String PROCESS_ENGINE_PREFIX = "PARAMS_"; + public static final String PROCESS_ENGINE_PENDINGREQUESTID = + PROCESS_ENGINE_PREFIX + PARAM_HTTP_TARGET_PENDINGREQUESTID; + public static final String PROCESS_ENGINE_SERVICE_PROVIDER_ENTITYID = + PROCESS_ENGINE_PREFIX + "uniqueSPId"; + public static final String PROCESS_ENGINE_SSL_CLIENT_CERTIFICATE = + PROCESS_ENGINE_PREFIX + "holderofkey_cert"; + public static final String PROCESS_ENGINE_REQUIRES_NO_POSTAUTH_REDIRECT = + PROCESS_ENGINE_PREFIX + "requireNoPostAuthRedirect"; + public static final String PROCESSCONTEXT_SWITCH_LANGUAGE = "changeLanguage"; + + public static final int ALLOWED_TIME_JITTER = 5; // minutes + public static final String COUNTRYCODE_AUSTRIA = "AT"; + + public static final String TESTCREDENTIALROOTOID = "1.2.40.0.10.2.4.1"; + } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/EAAFEventCodes.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/EAAFEventCodes.java index 5ee6eb90..e25c05b5 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/EAAFEventCodes.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/EAAFEventCodes.java @@ -1,5 +1,5 @@ package at.gv.egiz.eaaf.core.api.data; public class EAAFEventCodes { - public static final int PROCESS_STOPPED_BY_USER = 4102; + public static final int PROCESS_STOPPED_BY_USER = 4102; } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/ExceptionContainer.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/ExceptionContainer.java index f3e8b65c..69268562 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/ExceptionContainer.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/ExceptionContainer.java @@ -1,24 +1,20 @@ /******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ /******************************************************************************* *******************************************************************************/ @@ -36,63 +32,65 @@ import at.gv.egiz.eaaf.core.api.IRequest; */ public class ExceptionContainer implements Serializable { - private static final long serialVersionUID = 5355860753609684995L; - private Throwable exceptionThrown = null; - private IRequest pendingReq = null; - - - /** - * - */ - public ExceptionContainer(IRequest pendingReq, Throwable exception) { - this.pendingReq = pendingReq; - this.exceptionThrown = exception; - - } - - /** - * @return the exceptionThrown - */ - public Throwable getExceptionThrown() { - return this.exceptionThrown; - } - - public IRequest getPendingRequest() { - return this.pendingReq; - - } - - /** - * @return the uniqueSessionID - */ - public String getUniqueSessionID() { - if (this.pendingReq != null) - return this.pendingReq.getUniqueSessionIdentifier(); - else - return null; - } - /** - * @return the uniqueTransactionID - */ - public String getUniqueTransactionID() { - if (this.pendingReq != null) - return this.pendingReq.getUniqueTransactionIdentifier(); - else - return null; - } - - /** - * @return the uniqueServiceProviderId - */ - public String getUniqueServiceProviderId() { - if (this.pendingReq != null && - this.pendingReq.getServiceProviderConfiguration() != null) - return this.pendingReq.getServiceProviderConfiguration().getUniqueIdentifier(); - else - return null; - } - - - - + private static final long serialVersionUID = 5355860753609684995L; + private Throwable exceptionThrown = null; + private IRequest pendingReq = null; + + + /** + * + */ + public ExceptionContainer(final IRequest pendingReq, final Throwable exception) { + this.pendingReq = pendingReq; + this.exceptionThrown = exception; + + } + + /** + * @return the exceptionThrown + */ + public Throwable getExceptionThrown() { + return this.exceptionThrown; + } + + public IRequest getPendingRequest() { + return this.pendingReq; + + } + + /** + * @return the uniqueSessionID + */ + public String getUniqueSessionID() { + if (this.pendingReq != null) { + return this.pendingReq.getUniqueSessionIdentifier(); + } else { + return null; + } + } + + /** + * @return the uniqueTransactionID + */ + public String getUniqueTransactionID() { + if (this.pendingReq != null) { + return this.pendingReq.getUniqueTransactionIdentifier(); + } else { + return null; + } + } + + /** + * @return the uniqueServiceProviderId + */ + public String getUniqueServiceProviderId() { + if (this.pendingReq != null && this.pendingReq.getServiceProviderConfiguration() != null) { + return this.pendingReq.getServiceProviderConfiguration().getUniqueIdentifier(); + } else { + return null; + } + } + + + } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/ExtendedPVPAttributeDefinitions.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/ExtendedPVPAttributeDefinitions.java index d9ab2283..2d0fde0b 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/ExtendedPVPAttributeDefinitions.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/ExtendedPVPAttributeDefinitions.java @@ -1,24 +1,20 @@ /******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ /******************************************************************************* *******************************************************************************/ @@ -26,24 +22,27 @@ package at.gv.egiz.eaaf.core.api.data; public interface ExtendedPVPAttributeDefinitions extends PVPAttributeDefinitions { - public static final String SP_UNIQUEID_NAME = "urn:eidgvat:attributes.ServiceProviderUniqueId"; - public static final String SP_UNIQUEID_FRIENDLY_NAME = "ServiceProvider-UniqueId"; - - public static final String SP_FRIENDLYNAME_NAME = "urn:eidgvat:attributes.ServiceProviderFriendlyName"; - public static final String SP_FRIENDLYNAME_FRIENDLY_NAME = "ServiceProvider-FriendlyName"; - - public static final String SP_COUNTRYCODE_NAME = "urn:eidgvat:attributes.ServiceProviderCountryCode"; - public static final String SP_COUNTRYCODE_FRIENDLY_NAME = "ServiceProvider-CountryCode"; - - public static final String SP_USESMANDATES_NAME = "urn:eidgvat:attributes.ServiceProviderMandateProfiles"; - public static final String SP_USESMANDATES_FRIENDLY_NAME = "ServiceProvider-MandateProfiles"; - - /* Attributes for E-ID */ - public static final String EID_ENCRYPTED_SOURCEID_NAME = "urn:eidgvat:attributes.vsz.value"; - public static final String EID_ENCRYPTED_SOURCEID_FRIENDLY_NAME = "vSZ"; - - public static final String EID_ENCRYPTED_SOURCEID_TYPE_NAME = "urn:eidgvat:attributes.vsz.type"; - public static final String EID_ENCRYPTED_SOURCEID_TYPE_FRIENDLY_NAME = "vSZ-Type"; - - + public static final String SP_UNIQUEID_NAME = "urn:eidgvat:attributes.ServiceProviderUniqueId"; + public static final String SP_UNIQUEID_FRIENDLY_NAME = "ServiceProvider-UniqueId"; + + public static final String SP_FRIENDLYNAME_NAME = + "urn:eidgvat:attributes.ServiceProviderFriendlyName"; + public static final String SP_FRIENDLYNAME_FRIENDLY_NAME = "ServiceProvider-FriendlyName"; + + public static final String SP_COUNTRYCODE_NAME = + "urn:eidgvat:attributes.ServiceProviderCountryCode"; + public static final String SP_COUNTRYCODE_FRIENDLY_NAME = "ServiceProvider-CountryCode"; + + public static final String SP_USESMANDATES_NAME = + "urn:eidgvat:attributes.ServiceProviderMandateProfiles"; + public static final String SP_USESMANDATES_FRIENDLY_NAME = "ServiceProvider-MandateProfiles"; + + /* Attributes for E-ID */ + public static final String EID_ENCRYPTED_SOURCEID_NAME = "urn:eidgvat:attributes.vsz.value"; + public static final String EID_ENCRYPTED_SOURCEID_FRIENDLY_NAME = "vSZ"; + + public static final String EID_ENCRYPTED_SOURCEID_TYPE_NAME = "urn:eidgvat:attributes.vsz.type"; + public static final String EID_ENCRYPTED_SOURCEID_TYPE_FRIENDLY_NAME = "vSZ-Type"; + + } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/ILoALevelMapper.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/ILoALevelMapper.java index ed79dc60..c58f4fe7 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/ILoALevelMapper.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/ILoALevelMapper.java @@ -1,24 +1,20 @@ /******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ /******************************************************************************* *******************************************************************************/ @@ -28,29 +24,29 @@ package at.gv.egiz.eaaf.core.api.data; public interface ILoALevelMapper { - /** - * Map an arbitrary QAA level to eIDAS LoA - * - * @param qaa, but not null - * @return An eIDAS LoA if there is a mapping, otherwise null - */ - public String mapToeIDASLoA(String qaa); - - /** - * Map an arbitrary QAA level to PVP SecClass - * - * @param qaa, but not null - * @return A PVP SecClass if there is a mapping, otherwise null - */ - public String mapToSecClass(String qaa); + /** + * Map an arbitrary QAA level to eIDAS LoA + * + * @param qaa, but not null + * @return An eIDAS LoA if there is a mapping, otherwise null + */ + public String mapToeIDASLoA(String qaa); - - /** - * Map an an arbitrary eIDAS LoA to STORK QAA Level - * - * @param eidasqaaLevel - * @return A STORK QAA level - */ - @Deprecated - public String mapeIDASQAAToSTORKQAA(String eidasqaaLevel); + /** + * Map an arbitrary QAA level to PVP SecClass + * + * @param qaa, but not null + * @return A PVP SecClass if there is a mapping, otherwise null + */ + public String mapToSecClass(String qaa); + + + /** + * Map an an arbitrary eIDAS LoA to STORK QAA Level + * + * @param eidasqaaLevel + * @return A STORK QAA level + */ + @Deprecated + public String mapeIDASQAAToSTORKQAA(String eidasqaaLevel); } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/PVPAttributeDefinitions.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/PVPAttributeDefinitions.java index 03879a0c..f162ad3d 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/PVPAttributeDefinitions.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/PVPAttributeDefinitions.java @@ -1,24 +1,20 @@ /******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ /******************************************************************************* *******************************************************************************/ @@ -28,294 +24,357 @@ package at.gv.egiz.eaaf.core.api.data; public interface PVPAttributeDefinitions { - public static final String URN_OID_PREFIX = "urn:oid:"; - - public static final String PVP_VERSION_OID = "1.2.40.0.10.2.1.1.261.10"; - public static final String PVP_VERSION_NAME = URN_OID_PREFIX + PVP_VERSION_OID; - public static final String PVP_VERSION_FRIENDLY_NAME = "PVP-VERSION"; - public static final String PVP_VERSION_2_1 = "2.2"; - - - public static final String SECCLASS_OID = "1.2.40.0.10.2.1.1.261.110"; - public static final String SECCLASS_FRIENDLY_NAME = "SECCLASS"; - public static final String SECCLASS_NAME = URN_OID_PREFIX + SECCLASS_OID; - public static final int SECCLASS_MAX_LENGTH = 128; - - public static final String PRINCIPAL_NAME_OID = "1.2.40.0.10.2.1.1.261.20"; - public static final String PRINCIPAL_NAME_NAME = URN_OID_PREFIX + PRINCIPAL_NAME_OID; - public static final String PRINCIPAL_NAME_FRIENDLY_NAME = "PRINCIPAL-NAME"; - public static final int PRINCIPAL_NAME_MAX_LENGTH = 128; - - public static final String GIVEN_NAME_OID = "2.5.4.42"; - public static final String GIVEN_NAME_NAME = URN_OID_PREFIX + GIVEN_NAME_OID; - public static final String GIVEN_NAME_FRIENDLY_NAME = "GIVEN-NAME"; - public static final int GIVEN_NAME_MAX_LENGTH = 128; - - public static final String BIRTHDATE_OID = "1.2.40.0.10.2.1.1.55"; - public static final String BIRTHDATE_NAME = URN_OID_PREFIX + BIRTHDATE_OID; - public static final String BIRTHDATE_FRIENDLY_NAME = "BIRTHDATE"; - public static final String BIRTHDATE_FORMAT_PATTERN = "yyyy-MM-dd"; - - public static final String USERID_OID = "0.9.2342.19200300.100.1.1"; - public static final String USERID_NAME = URN_OID_PREFIX + USERID_OID; - public static final String USERID_FRIENDLY_NAME = "USERID"; - public static final int USERID_MAX_LENGTH = 128; - - public static final String GID_OID = "1.2.40.0.10.2.1.1.1"; - public static final String GID_NAME = URN_OID_PREFIX + GID_OID; - public static final String GID_FRIENDLY_NAME = "GID"; - public static final int GID_MAX_LENGTH = 128; - - public static final String BPK_OID = "1.2.40.0.10.2.1.1.149"; - public static final String BPK_NAME = URN_OID_PREFIX + BPK_OID; - public static final String BPK_FRIENDLY_NAME = "BPK"; - public static final int BPK_MAX_LENGTH = 1024; - public static final String BPK_R_PROFILE21_HEADER = "X-PVP-BPK"; - - public static final String BPK_LIST_OID = "1.2.40.0.10.2.1.1.261.28"; - public static final String BPK_LIST_NAME = URN_OID_PREFIX + BPK_LIST_OID; - public static final String BPK_LIST_FRIENDLY_NAME = "BPK-LIST"; - public static final int BPK_LIST_MAX_LENGTH = 32767; - - public static final String ENC_BPK_LIST_OID = "1.2.40.0.10.2.1.1.261.22"; - public static final String ENC_BPK_LIST_NAME = URN_OID_PREFIX+ENC_BPK_LIST_OID; - public static final String ENC_BPK_LIST_FRIENDLY_NAME = "ENC-BPK-LIST"; - public static final int ENC_BPK_LIST_MAX_LENGTH = 32767; - - public static final String MAIL_OID = "0.9.2342.19200300.100.1.3"; - public static final String MAIL_NAME = URN_OID_PREFIX + MAIL_OID; - public static final String MAIL_FRIENDLY_NAME = "MAIL"; - public static final int MAIL_MAX_LENGTH = 128; - - public static final String TEL_OID = "2.5.4.20"; - public static final String TEL_NAME = URN_OID_PREFIX + TEL_OID; - public static final String TEL_FRIENDLY_NAME = "TEL"; - public static final int TEL_MAX_LENGTH = 32; - - public static final String PARTICIPANT_ID_OID = "1.2.40.0.10.2.1.1.71"; - public static final String PARTICIPANT_ID_NAME = URN_OID_PREFIX + PARTICIPANT_ID_OID; - public static final String PARTICIPANT_ID_FRIENDLY_NAME = "PARTICIPANT-ID"; - public static final int PARTICIPANT_MAX_LENGTH = 39; - - public static final String PARTICIPANT_OKZ_OID = "1.2.40.0.10.2.1.1.261.24"; - public static final String PARTICIPANT_OKZ_NAME = URN_OID_PREFIX + PARTICIPANT_OKZ_OID; - public static final String PARTICIPANT_OKZ_FRIENDLY_NAME = "PARTICIPANT-OKZ"; - public static final int PARTICIPANT_OKZ_MAX_LENGTH = 32; - - public static final String OU_OKZ_OID = "1.2.40.0.10.2.1.1.153"; - public static final String OU_OKZ_NAME = URN_OID_PREFIX + OU_OKZ_OID; - public static final int OU_OKZ_MAX_LENGTH = 32; - - public static final String OU_GV_OU_ID_OID = "1.2.40.0.10.2.1.1.3"; - public static final String OU_GV_OU_ID_NAME = URN_OID_PREFIX + OU_GV_OU_ID_OID; - public static final String OU_GV_OU_ID_FRIENDLY_NAME = "OU-GV-OU-ID"; - public static final int OU_GV_OU_ID_MAX_LENGTH = 39; - - public static final String OU_OID = "2.5.4.11"; - public static final String OU_NAME = URN_OID_PREFIX + OU_OID; - public static final String OU_FRIENDLY_NAME = "OU"; - public static final int OU_MAX_LENGTH = 64; - - public static final String FUNCTION_OID = "1.2.40.0.10.2.1.1.33"; - public static final String FUNCTION_NAME = URN_OID_PREFIX + FUNCTION_OID; - public static final String FUNCTION_FRIENDLY_NAME = "FUNCTION"; - public static final int FUNCTION_MAX_LENGTH = 32; - - public static final String ROLES_OID = "1.2.40.0.10.2.1.1.261.30"; - public static final String ROLES_NAME = URN_OID_PREFIX + ROLES_OID; - public static final String ROLES_FRIENDLY_NAME = "ROLES"; - public static final int ROLES_MAX_LENGTH = 32767; - - @Deprecated public static final String EID_CITIZEN_QAA_LEVEL_OID = "1.2.40.0.10.2.1.1.261.94"; - @Deprecated public static final String EID_CITIZEN_QAA_LEVEL_NAME = URN_OID_PREFIX + EID_CITIZEN_QAA_LEVEL_OID; - @Deprecated public static final String EID_CITIZEN_QAA_LEVEL_FRIENDLY_NAME = "EID-CITIZEN-QAA-LEVEL"; - - public static final String EID_CITIZEN_EIDAS_QAA_LEVEL_OID = "1.2.40.0.10.2.1.1.261.108"; - public static final String EID_CITIZEN_EIDAS_QAA_LEVEL_NAME = URN_OID_PREFIX + EID_CITIZEN_EIDAS_QAA_LEVEL_OID; - public static final String EID_CITIZEN_EIDAS_QAA_LEVEL_FRIENDLY_NAME = "EID-CITIZEN-QAA-EIDAS-LEVEL"; - - public static final String EID_IDENTITY_STATUS_LEVEL_OID = "1.2.40.0.10.2.1.1.261.109"; - public static final String EID_IDENTITY_STATUS_LEVEL_NAME = URN_OID_PREFIX + EID_IDENTITY_STATUS_LEVEL_OID; - public static final String EID_IDENTITY_STATUS_LEVEL_FRIENDLY_NAME = "EID-IDENTITY-STATUS-LEVEL"; - public enum EID_IDENTITY_STATUS_LEVEL_VALUES { - IDENTITY("http://eid.gv.at/eID/status/identity"), - TESTIDENTITY("http://eid.gv.at/eID/status/testidentity"), - SYSTEM("http://eid.gv.at/eID/status/system"); - - private final String uri; - - private EID_IDENTITY_STATUS_LEVEL_VALUES(String uri) { - this.uri = uri; - } - - /** - * Get the URI based status identifier of an E-ID - * - * @return - */ - public String getURI() { - return this.uri; - } - }; - - public static final String EID_ISSUING_NATION_OID = "1.2.40.0.10.2.1.1.261.32"; - public static final String EID_ISSUING_NATION_NAME = URN_OID_PREFIX + EID_ISSUING_NATION_OID; - public static final String EID_ISSUING_NATION_FRIENDLY_NAME = "EID-ISSUING-NATION"; - public static final int EID_ISSUING_NATION_MAX_LENGTH = 2; - - public static final String EID_SECTOR_FOR_IDENTIFIER_OID = "1.2.40.0.10.2.1.1.261.34"; - public static final String EID_SECTOR_FOR_IDENTIFIER_NAME = URN_OID_PREFIX + EID_SECTOR_FOR_IDENTIFIER_OID; - public static final String EID_SECTOR_FOR_IDENTIFIER_FRIENDLY_NAME = "EID-SECTOR-FOR-IDENTIFIER"; - public static final int EID_SECTOR_FOR_IDENTIFIER_MAX_LENGTH = 255; - - @Deprecated public static final String EID_SOURCE_PIN_OID = "1.2.40.0.10.2.1.1.261.36"; - @Deprecated public static final String EID_SOURCE_PIN_NAME = URN_OID_PREFIX + EID_SOURCE_PIN_OID; - @Deprecated public static final String EID_SOURCE_PIN_FRIENDLY_NAME = "EID-SOURCE-PIN"; - @Deprecated public static final int EID_SOURCE_PIN_MAX_LENGTH = 128; - - @Deprecated public static final String EID_SOURCE_PIN_TYPE_OID = "1.2.40.0.10.2.1.1.261.104"; - @Deprecated public static final String EID_SOURCE_PIN_TYPE_NAME = URN_OID_PREFIX + EID_SOURCE_PIN_TYPE_OID; - @Deprecated public static final String EID_SOURCE_PIN_TYPE_FRIENDLY_NAME = "EID-SOURCE-PIN-TYPE"; - @Deprecated public static final int EID_SOURCE_PIN_TYPE_MAX_LENGTH = 128; - - @Deprecated public static final String EID_IDENTITY_LINK_OID = "1.2.40.0.10.2.1.1.261.38"; - @Deprecated public static final String EID_IDENTITY_LINK_NAME = URN_OID_PREFIX + EID_IDENTITY_LINK_OID; - @Deprecated public static final String EID_IDENTITY_LINK_FRIENDLY_NAME = "EID-IDENTITY-LINK"; - @Deprecated public static final int EID_IDENTITY_LINK_MAX_LENGTH = 32767; - - public static final String EID_E_ID_TOKEN_OID = "1.2.40.0.10.2.1.1.261.39"; - public static final String EID_E_ID_TOKEN_NAME = URN_OID_PREFIX + EID_E_ID_TOKEN_OID; - public static final String EID_E_ID_TOKEN_FRIENDLY_NAME = "EID-E-ID-TOKEN"; - public static final int EID_E_ID_TOKEN_MAX_LENGTH = 32767; - - @Deprecated public static final String EID_AUTH_BLOCK_OID = "1.2.40.0.10.2.1.1.261.62"; - @Deprecated public static final String EID_AUTH_BLOCK_NAME = URN_OID_PREFIX + EID_AUTH_BLOCK_OID; - @Deprecated public static final String EID_AUTH_BLOCK_FRIENDLY_NAME = "EID-AUTH-BLOCK"; - @Deprecated public static final int EID_AUTH_BLOCK_MAX_LENGTH = 32767; - - public static final String EID_CCS_URL_OID = "1.2.40.0.10.2.1.1.261.64"; - public static final String EID_CCS_URL_NAME = URN_OID_PREFIX + EID_CCS_URL_OID; - public static final String EID_CCS_URL_FRIENDLY_NAME = "EID-CCS-URL"; - public static final int EID_CCS_URL_MAX_LENGTH = 1024; - - public static final String EID_SIGNER_CERTIFICATE_OID = "1.2.40.0.10.2.1.1.261.66"; - public static final String EID_SIGNER_CERTIFICATE_NAME = URN_OID_PREFIX + EID_SIGNER_CERTIFICATE_OID; - public static final String EID_SIGNER_CERTIFICATE_FRIENDLY_NAME = "EID-SIGNER-CERTIFICATE"; - public static final int EID_SIGNER_CERTIFICATE_MAX_LENGTH = 32767; - - @Deprecated public static final String EID_STORK_TOKEN_OID = "1.2.40.0.10.2.1.1.261.96"; - @Deprecated public static final String EID_STORK_TOKEN_NAME = URN_OID_PREFIX + EID_STORK_TOKEN_OID; - @Deprecated public static final String EID_STORK_TOKEN_FRIENDLY_NAME = "EID-STORK-TOKEN"; - @Deprecated public static final int EID_STORK_TOKEN_MAX_LENGTH = 32767; - - public static final String MANDATE_TYPE_OID = "1.2.40.0.10.2.1.1.261.68"; - public static final String MANDATE_TYPE_NAME = URN_OID_PREFIX + MANDATE_TYPE_OID; - public static final String MANDATE_TYPE_FRIENDLY_NAME = "MANDATE-TYPE"; - public static final int MANDATE_TYPE_MAX_LENGTH = 256; - - public static final String MANDATE_TYPE_OID_OID = "1.2.40.0.10.2.1.1.261.106"; - public static final String MANDATE_TYPE_OID_NAME = URN_OID_PREFIX + MANDATE_TYPE_OID_OID; - public static final String MANDATE_TYPE_OID_FRIENDLY_NAME = "MANDATE-TYPE-OID"; - public static final int MANDATE_TYPE_OID_MAX_LENGTH = 256; - - @Deprecated public static final String MANDATE_NAT_PER_SOURCE_PIN_OID = "1.2.40.0.10.2.1.1.261.70"; - @Deprecated public static final String MANDATE_NAT_PER_SOURCE_PIN_NAME = URN_OID_PREFIX + MANDATE_NAT_PER_SOURCE_PIN_OID; - @Deprecated public static final String MANDATE_NAT_PER_SOURCE_PIN_FRIENDLY_NAME = "MANDATOR-NATURAL-PERSON-SOURCE-PIN"; - @Deprecated public static final int MANDATE_NAT_PER_SOURCE_PIN_MAX_LENGTH = 128; - - public static final String MANDATE_LEG_PER_SOURCE_PIN_OID = "1.2.40.0.10.2.1.1.261.100"; - public static final String MANDATE_LEG_PER_SOURCE_PIN_NAME = URN_OID_PREFIX + MANDATE_LEG_PER_SOURCE_PIN_OID; - public static final String MANDATE_LEG_PER_SOURCE_PIN_FRIENDLY_NAME = "MANDATOR-LEGAL-PERSON-SOURCE-PIN"; - public static final int MANDATE_LEG_PER_SOURCE_PIN_MAX_LENGTH = 128; - - @Deprecated public static final String MANDATE_NAT_PER_SOURCE_PIN_TYPE_OID = "1.2.40.0.10.2.1.1.261.102"; - @Deprecated public static final String MANDATE_NAT_PER_SOURCE_PIN_TYPE_NAME = URN_OID_PREFIX + MANDATE_NAT_PER_SOURCE_PIN_TYPE_OID; - @Deprecated public static final String MANDATE_NAT_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME = "MANDATOR-NATURAL-PERSON-SOURCE-PIN-TYPE"; - @Deprecated public static final int MANDATE_NAT_PER_SOURCE_PIN_TYPE_MAX_LENGTH = 128; - - public static final String MANDATE_LEG_PER_SOURCE_PIN_TYPE_OID = "1.2.40.0.10.2.1.1.261.76"; - public static final String MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME = URN_OID_PREFIX + MANDATE_LEG_PER_SOURCE_PIN_TYPE_OID; - public static final String MANDATE_LEG_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME = "MANDATOR-LEGAL-PERSON-SOURCE-PIN-TYPE"; - public static final int MANDATE_LEG_PER_SOURCE_PIN_TYPE_MAX_LENGTH = 128; - - public static final String MANDATE_NAT_PER_BPK_OID = "1.2.40.0.10.2.1.1.261.98"; - public static final String MANDATE_NAT_PER_BPK_NAME = URN_OID_PREFIX + MANDATE_NAT_PER_BPK_OID; - public static final String MANDATE_NAT_PER_BPK_FRIENDLY_NAME = "MANDATOR-NATURAL-PERSON-BPK"; - public static final int MANDATE_NAT_PER_BPK_MAX_LENGTH = 1024; - - public static final String MANDATE_NAT_PER_BPK_LIST_OID = "1.2.40.0.10.2.1.1.261.73"; - public static final String MANDATE_NAT_PER_BPK_LIST_NAME = URN_OID_PREFIX + MANDATE_NAT_PER_BPK_LIST_OID; - public static final String MANDATE_NAT_PER_BPK_LIST_FRIENDLY_NAME = "MANDATOR-NATURAL-PERSON-BPK-LIST"; - public static final int MANDATE_NAT_PER_ENC_LIST_MAX_LENGTH = 32767; - - public static final String MANDATE_NAT_PER_ENC_BPK_LIST_OID = "1.2.40.0.10.2.1.1.261.72"; - public static final String MANDATE_NAT_PER_ENC_BPK_LIST_NAME = URN_OID_PREFIX + MANDATE_NAT_PER_ENC_BPK_LIST_OID; - public static final String MANDATE_NAT_PER_ENC_BPK_LIST_FRIENDLY_NAME = "MANDATOR-NATURAL-PERSON-ENC-BPK-LIST"; - public static final int MANDATE_NAT_PER_ENC_BPK_LIST_MAX_LENGTH = 32767; - - public static final String MANDATE_NAT_PER_GIVEN_NAME_OID = "1.2.40.0.10.2.1.1.261.78"; - public static final String MANDATE_NAT_PER_GIVEN_NAME_NAME = URN_OID_PREFIX + MANDATE_NAT_PER_GIVEN_NAME_OID; - public static final String MANDATE_NAT_PER_GIVEN_NAME_FRIENDLY_NAME = "MANDATOR-NATURAL-PERSON-GIVEN-NAME"; - public static final int MANDATE_NAT_PER_GIVEN_NAME_MAX_LENGTH = 128; - - public static final String MANDATE_NAT_PER_FAMILY_NAME_OID = "1.2.40.0.10.2.1.1.261.80"; - public static final String MANDATE_NAT_PER_FAMILY_NAME_NAME = URN_OID_PREFIX + MANDATE_NAT_PER_FAMILY_NAME_OID; - public static final String MANDATE_NAT_PER_FAMILY_NAME_FRIENDLY_NAME = "MANDATOR-NATURAL-PERSON-FAMILY-NAME"; - public static final int MANDATE_NAT_PER_FAMILY_NAME_MAX_LENGTH = 128; - - public static final String MANDATE_NAT_PER_BIRTHDATE_OID = "1.2.40.0.10.2.1.1.261.82"; - public static final String MANDATE_NAT_PER_BIRTHDATE_NAME = URN_OID_PREFIX + MANDATE_NAT_PER_BIRTHDATE_OID; - public static final String MANDATE_NAT_PER_BIRTHDATE_FRIENDLY_NAME = "MANDATOR-NATURAL-PERSON-BIRTHDATE"; - public static final String MANDATE_NAT_PER_BIRTHDATE_FORMAT_PATTERN = BIRTHDATE_FORMAT_PATTERN; - - public static final String MANDATE_LEG_PER_FULL_NAME_OID = "1.2.40.0.10.2.1.1.261.84"; - public static final String MANDATE_LEG_PER_FULL_NAME_NAME = URN_OID_PREFIX + MANDATE_LEG_PER_FULL_NAME_OID; - public static final String MANDATE_LEG_PER_FULL_NAME_FRIENDLY_NAME = "MANDATOR-LEGAL-PERSON-FULL-NAME"; - public static final int MANDATE_LEG_PER_FULL_NAME_MAX_LENGTH = 256; - - public static final String MANDATE_PROF_REP_OID_OID = "1.2.40.0.10.2.1.1.261.86"; - public static final String MANDATE_PROF_REP_OID_NAME = URN_OID_PREFIX + MANDATE_PROF_REP_OID_OID; - public static final String MANDATE_PROF_REP_OID_FRIENDLY_NAME = "MANDATE-PROF-REP-OID"; - public static final int MANDATE_PROF_REP_OID_MAX_LENGTH = 256; - - public static final String MANDATE_PROF_REP_DESC_OID = "1.2.40.0.10.2.1.1.261.88"; - public static final String MANDATE_PROF_REP_DESC_NAME = URN_OID_PREFIX + MANDATE_PROF_REP_DESC_OID; - public static final String MANDATE_PROF_REP_DESC_FRIENDLY_NAME = "MANDATE-PROF-REP-DESCRIPTION"; - public static final int MANDATE_PROF_REP_DESC_MAX_LENGTH = 1024; - - public static final String MANDATE_REFERENCE_VALUE_OID = "1.2.40.0.10.2.1.1.261.90"; - public static final String MANDATE_REFERENCE_VALUE_NAME = URN_OID_PREFIX + MANDATE_REFERENCE_VALUE_OID; - public static final String MANDATE_REFERENCE_VALUE_FRIENDLY_NAME = "MANDATE-REFERENCE-VALUE"; - public static final int MANDATE_REFERENCE_VALUE_MAX_LENGTH = 100; - - public static final String MANDATE_IDENTIFIER_OID = "1.2.40.0.10.2.1.1.261.91"; - public static final String MANDATE_IDENTIFIER_FRIENDLY_NAME = "MANDATE-IDENTIFIER"; - public static final String MANDATE_IDENTIFIER_NAME = URN_OID_PREFIX + MANDATE_IDENTIFIER_OID; - public static final int MANDATE_IDENTIFIER_MAX_LENGTH = 256; - - - @Deprecated public static final String MANDATE_FULL_MANDATE_OID = "1.2.40.0.10.2.1.1.261.92"; - @Deprecated public static final String MANDATE_FULL_MANDATE_NAME = URN_OID_PREFIX + MANDATE_FULL_MANDATE_OID; - @Deprecated public static final String MANDATE_FULL_MANDATE_FRIENDLY_NAME = "MANDATE-FULL-MANDATE"; - @Deprecated public static final int MANDATE_FULL_MANDATE_MAX_LENGTH = 32767; - - public static final String INVOICE_RECPT_ID_OID = "1.2.40.0.10.2.1.1.261.40"; - public static final String INVOICE_RECPT_ID_NAME = URN_OID_PREFIX + INVOICE_RECPT_ID_OID; - public static final String INVOICE_RECPT_ID_FRIENDLY_NAME = "INVOICE-RECPT-ID"; - public static final int INVOICE_RECPT_ID_MAX_LENGTH = 64; - - public static final String COST_CENTER_ID_OID = "1.2.40.0.10.2.1.1.261.50"; - public static final String COST_CENTER_ID_NAME = URN_OID_PREFIX + COST_CENTER_ID_OID; - public static final String COST_CENTER_ID_FRIENDLY_NAME = "COST-CENTER-ID"; - public static final int COST_CENTER_ID_MAX_LENGTH = 32767; - - public static final String CHARGE_CODE_OID = "1.2.40.0.10.2.1.1.261.60"; - public static final String CHARGE_CODE_NAME = URN_OID_PREFIX + CHARGE_CODE_OID; - public static final String CHARGE_CODE_FRIENDLY_NAME = "CHARGE-CODE"; - public static final int CHARGE_CODE_MAX_LENGTH = 32767; - - public static final String PVP_HOLDEROFKEY_OID = "1.2.40.0.10.2.1.1.261.xx.xx"; - public static final String PVP_HOLDEROFKEY_NAME = URN_OID_PREFIX + PVP_HOLDEROFKEY_OID; - public static final String PVP_HOLDEROFKEY_FRIENDLY_NAME = "HOLDER-OF-KEY-CERTIFICATE"; + public static final String URN_OID_PREFIX = "urn:oid:"; + + public static final String PVP_VERSION_OID = "1.2.40.0.10.2.1.1.261.10"; + public static final String PVP_VERSION_NAME = URN_OID_PREFIX + PVP_VERSION_OID; + public static final String PVP_VERSION_FRIENDLY_NAME = "PVP-VERSION"; + public static final String PVP_VERSION_2_1 = "2.2"; + + + public static final String SECCLASS_OID = "1.2.40.0.10.2.1.1.261.110"; + public static final String SECCLASS_FRIENDLY_NAME = "SECCLASS"; + public static final String SECCLASS_NAME = URN_OID_PREFIX + SECCLASS_OID; + public static final int SECCLASS_MAX_LENGTH = 128; + + public static final String PRINCIPAL_NAME_OID = "1.2.40.0.10.2.1.1.261.20"; + public static final String PRINCIPAL_NAME_NAME = URN_OID_PREFIX + PRINCIPAL_NAME_OID; + public static final String PRINCIPAL_NAME_FRIENDLY_NAME = "PRINCIPAL-NAME"; + public static final int PRINCIPAL_NAME_MAX_LENGTH = 128; + + public static final String GIVEN_NAME_OID = "2.5.4.42"; + public static final String GIVEN_NAME_NAME = URN_OID_PREFIX + GIVEN_NAME_OID; + public static final String GIVEN_NAME_FRIENDLY_NAME = "GIVEN-NAME"; + public static final int GIVEN_NAME_MAX_LENGTH = 128; + + public static final String BIRTHDATE_OID = "1.2.40.0.10.2.1.1.55"; + public static final String BIRTHDATE_NAME = URN_OID_PREFIX + BIRTHDATE_OID; + public static final String BIRTHDATE_FRIENDLY_NAME = "BIRTHDATE"; + public static final String BIRTHDATE_FORMAT_PATTERN = "yyyy-MM-dd"; + + public static final String USERID_OID = "0.9.2342.19200300.100.1.1"; + public static final String USERID_NAME = URN_OID_PREFIX + USERID_OID; + public static final String USERID_FRIENDLY_NAME = "USERID"; + public static final int USERID_MAX_LENGTH = 128; + + public static final String GID_OID = "1.2.40.0.10.2.1.1.1"; + public static final String GID_NAME = URN_OID_PREFIX + GID_OID; + public static final String GID_FRIENDLY_NAME = "GID"; + public static final int GID_MAX_LENGTH = 128; + + public static final String BPK_OID = "1.2.40.0.10.2.1.1.149"; + public static final String BPK_NAME = URN_OID_PREFIX + BPK_OID; + public static final String BPK_FRIENDLY_NAME = "BPK"; + public static final int BPK_MAX_LENGTH = 1024; + public static final String BPK_R_PROFILE21_HEADER = "X-PVP-BPK"; + + public static final String BPK_LIST_OID = "1.2.40.0.10.2.1.1.261.28"; + public static final String BPK_LIST_NAME = URN_OID_PREFIX + BPK_LIST_OID; + public static final String BPK_LIST_FRIENDLY_NAME = "BPK-LIST"; + public static final int BPK_LIST_MAX_LENGTH = 32767; + + public static final String ENC_BPK_LIST_OID = "1.2.40.0.10.2.1.1.261.22"; + public static final String ENC_BPK_LIST_NAME = URN_OID_PREFIX + ENC_BPK_LIST_OID; + public static final String ENC_BPK_LIST_FRIENDLY_NAME = "ENC-BPK-LIST"; + public static final int ENC_BPK_LIST_MAX_LENGTH = 32767; + + public static final String MAIL_OID = "0.9.2342.19200300.100.1.3"; + public static final String MAIL_NAME = URN_OID_PREFIX + MAIL_OID; + public static final String MAIL_FRIENDLY_NAME = "MAIL"; + public static final int MAIL_MAX_LENGTH = 128; + + public static final String TEL_OID = "2.5.4.20"; + public static final String TEL_NAME = URN_OID_PREFIX + TEL_OID; + public static final String TEL_FRIENDLY_NAME = "TEL"; + public static final int TEL_MAX_LENGTH = 32; + + public static final String PARTICIPANT_ID_OID = "1.2.40.0.10.2.1.1.71"; + public static final String PARTICIPANT_ID_NAME = URN_OID_PREFIX + PARTICIPANT_ID_OID; + public static final String PARTICIPANT_ID_FRIENDLY_NAME = "PARTICIPANT-ID"; + public static final int PARTICIPANT_MAX_LENGTH = 39; + + public static final String PARTICIPANT_OKZ_OID = "1.2.40.0.10.2.1.1.261.24"; + public static final String PARTICIPANT_OKZ_NAME = URN_OID_PREFIX + PARTICIPANT_OKZ_OID; + public static final String PARTICIPANT_OKZ_FRIENDLY_NAME = "PARTICIPANT-OKZ"; + public static final int PARTICIPANT_OKZ_MAX_LENGTH = 32; + + public static final String OU_OKZ_OID = "1.2.40.0.10.2.1.1.153"; + public static final String OU_OKZ_NAME = URN_OID_PREFIX + OU_OKZ_OID; + public static final int OU_OKZ_MAX_LENGTH = 32; + + public static final String OU_GV_OU_ID_OID = "1.2.40.0.10.2.1.1.3"; + public static final String OU_GV_OU_ID_NAME = URN_OID_PREFIX + OU_GV_OU_ID_OID; + public static final String OU_GV_OU_ID_FRIENDLY_NAME = "OU-GV-OU-ID"; + public static final int OU_GV_OU_ID_MAX_LENGTH = 39; + + public static final String OU_OID = "2.5.4.11"; + public static final String OU_NAME = URN_OID_PREFIX + OU_OID; + public static final String OU_FRIENDLY_NAME = "OU"; + public static final int OU_MAX_LENGTH = 64; + + public static final String FUNCTION_OID = "1.2.40.0.10.2.1.1.33"; + public static final String FUNCTION_NAME = URN_OID_PREFIX + FUNCTION_OID; + public static final String FUNCTION_FRIENDLY_NAME = "FUNCTION"; + public static final int FUNCTION_MAX_LENGTH = 32; + + public static final String ROLES_OID = "1.2.40.0.10.2.1.1.261.30"; + public static final String ROLES_NAME = URN_OID_PREFIX + ROLES_OID; + public static final String ROLES_FRIENDLY_NAME = "ROLES"; + public static final int ROLES_MAX_LENGTH = 32767; + + @Deprecated + public static final String EID_CITIZEN_QAA_LEVEL_OID = "1.2.40.0.10.2.1.1.261.94"; + @Deprecated + public static final String EID_CITIZEN_QAA_LEVEL_NAME = + URN_OID_PREFIX + EID_CITIZEN_QAA_LEVEL_OID; + @Deprecated + public static final String EID_CITIZEN_QAA_LEVEL_FRIENDLY_NAME = "EID-CITIZEN-QAA-LEVEL"; + + public static final String EID_CITIZEN_EIDAS_QAA_LEVEL_OID = "1.2.40.0.10.2.1.1.261.108"; + public static final String EID_CITIZEN_EIDAS_QAA_LEVEL_NAME = + URN_OID_PREFIX + EID_CITIZEN_EIDAS_QAA_LEVEL_OID; + public static final String EID_CITIZEN_EIDAS_QAA_LEVEL_FRIENDLY_NAME = + "EID-CITIZEN-QAA-EIDAS-LEVEL"; + + public static final String EID_IDENTITY_STATUS_LEVEL_OID = "1.2.40.0.10.2.1.1.261.109"; + public static final String EID_IDENTITY_STATUS_LEVEL_NAME = + URN_OID_PREFIX + EID_IDENTITY_STATUS_LEVEL_OID; + public static final String EID_IDENTITY_STATUS_LEVEL_FRIENDLY_NAME = "EID-IDENTITY-STATUS-LEVEL"; + + public enum EID_IDENTITY_STATUS_LEVEL_VALUES { + IDENTITY("http://eid.gv.at/eID/status/identity"), TESTIDENTITY( + "http://eid.gv.at/eID/status/testidentity"), SYSTEM("http://eid.gv.at/eID/status/system"); + + private final String uri; + + private EID_IDENTITY_STATUS_LEVEL_VALUES(final String uri) { + this.uri = uri; + } + + /** + * Get the URI based status identifier of an E-ID + * + * @return + */ + public String getURI() { + return this.uri; + } + } + + public static final String EID_ISSUING_NATION_OID = "1.2.40.0.10.2.1.1.261.32"; + public static final String EID_ISSUING_NATION_NAME = URN_OID_PREFIX + EID_ISSUING_NATION_OID; + public static final String EID_ISSUING_NATION_FRIENDLY_NAME = "EID-ISSUING-NATION"; + public static final int EID_ISSUING_NATION_MAX_LENGTH = 2; + + public static final String EID_SECTOR_FOR_IDENTIFIER_OID = "1.2.40.0.10.2.1.1.261.34"; + public static final String EID_SECTOR_FOR_IDENTIFIER_NAME = + URN_OID_PREFIX + EID_SECTOR_FOR_IDENTIFIER_OID; + public static final String EID_SECTOR_FOR_IDENTIFIER_FRIENDLY_NAME = "EID-SECTOR-FOR-IDENTIFIER"; + public static final int EID_SECTOR_FOR_IDENTIFIER_MAX_LENGTH = 255; + + @Deprecated + public static final String EID_SOURCE_PIN_OID = "1.2.40.0.10.2.1.1.261.36"; + @Deprecated + public static final String EID_SOURCE_PIN_NAME = URN_OID_PREFIX + EID_SOURCE_PIN_OID; + @Deprecated + public static final String EID_SOURCE_PIN_FRIENDLY_NAME = "EID-SOURCE-PIN"; + @Deprecated + public static final int EID_SOURCE_PIN_MAX_LENGTH = 128; + + @Deprecated + public static final String EID_SOURCE_PIN_TYPE_OID = "1.2.40.0.10.2.1.1.261.104"; + @Deprecated + public static final String EID_SOURCE_PIN_TYPE_NAME = URN_OID_PREFIX + EID_SOURCE_PIN_TYPE_OID; + @Deprecated + public static final String EID_SOURCE_PIN_TYPE_FRIENDLY_NAME = "EID-SOURCE-PIN-TYPE"; + @Deprecated + public static final int EID_SOURCE_PIN_TYPE_MAX_LENGTH = 128; + + @Deprecated + public static final String EID_IDENTITY_LINK_OID = "1.2.40.0.10.2.1.1.261.38"; + @Deprecated + public static final String EID_IDENTITY_LINK_NAME = URN_OID_PREFIX + EID_IDENTITY_LINK_OID; + @Deprecated + public static final String EID_IDENTITY_LINK_FRIENDLY_NAME = "EID-IDENTITY-LINK"; + @Deprecated + public static final int EID_IDENTITY_LINK_MAX_LENGTH = 32767; + + public static final String EID_E_ID_TOKEN_OID = "1.2.40.0.10.2.1.1.261.39"; + public static final String EID_E_ID_TOKEN_NAME = URN_OID_PREFIX + EID_E_ID_TOKEN_OID; + public static final String EID_E_ID_TOKEN_FRIENDLY_NAME = "EID-E-ID-TOKEN"; + public static final int EID_E_ID_TOKEN_MAX_LENGTH = 32767; + + @Deprecated + public static final String EID_AUTH_BLOCK_OID = "1.2.40.0.10.2.1.1.261.62"; + @Deprecated + public static final String EID_AUTH_BLOCK_NAME = URN_OID_PREFIX + EID_AUTH_BLOCK_OID; + @Deprecated + public static final String EID_AUTH_BLOCK_FRIENDLY_NAME = "EID-AUTH-BLOCK"; + @Deprecated + public static final int EID_AUTH_BLOCK_MAX_LENGTH = 32767; + + public static final String EID_CCS_URL_OID = "1.2.40.0.10.2.1.1.261.64"; + public static final String EID_CCS_URL_NAME = URN_OID_PREFIX + EID_CCS_URL_OID; + public static final String EID_CCS_URL_FRIENDLY_NAME = "EID-CCS-URL"; + public static final int EID_CCS_URL_MAX_LENGTH = 1024; + + public static final String EID_SIGNER_CERTIFICATE_OID = "1.2.40.0.10.2.1.1.261.66"; + public static final String EID_SIGNER_CERTIFICATE_NAME = + URN_OID_PREFIX + EID_SIGNER_CERTIFICATE_OID; + public static final String EID_SIGNER_CERTIFICATE_FRIENDLY_NAME = "EID-SIGNER-CERTIFICATE"; + public static final int EID_SIGNER_CERTIFICATE_MAX_LENGTH = 32767; + + @Deprecated + public static final String EID_STORK_TOKEN_OID = "1.2.40.0.10.2.1.1.261.96"; + @Deprecated + public static final String EID_STORK_TOKEN_NAME = URN_OID_PREFIX + EID_STORK_TOKEN_OID; + @Deprecated + public static final String EID_STORK_TOKEN_FRIENDLY_NAME = "EID-STORK-TOKEN"; + @Deprecated + public static final int EID_STORK_TOKEN_MAX_LENGTH = 32767; + + public static final String MANDATE_TYPE_OID = "1.2.40.0.10.2.1.1.261.68"; + public static final String MANDATE_TYPE_NAME = URN_OID_PREFIX + MANDATE_TYPE_OID; + public static final String MANDATE_TYPE_FRIENDLY_NAME = "MANDATE-TYPE"; + public static final int MANDATE_TYPE_MAX_LENGTH = 256; + + public static final String MANDATE_TYPE_OID_OID = "1.2.40.0.10.2.1.1.261.106"; + public static final String MANDATE_TYPE_OID_NAME = URN_OID_PREFIX + MANDATE_TYPE_OID_OID; + public static final String MANDATE_TYPE_OID_FRIENDLY_NAME = "MANDATE-TYPE-OID"; + public static final int MANDATE_TYPE_OID_MAX_LENGTH = 256; + + @Deprecated + public static final String MANDATE_NAT_PER_SOURCE_PIN_OID = "1.2.40.0.10.2.1.1.261.70"; + @Deprecated + public static final String MANDATE_NAT_PER_SOURCE_PIN_NAME = + URN_OID_PREFIX + MANDATE_NAT_PER_SOURCE_PIN_OID; + @Deprecated + public static final String MANDATE_NAT_PER_SOURCE_PIN_FRIENDLY_NAME = + "MANDATOR-NATURAL-PERSON-SOURCE-PIN"; + @Deprecated + public static final int MANDATE_NAT_PER_SOURCE_PIN_MAX_LENGTH = 128; + + public static final String MANDATE_LEG_PER_SOURCE_PIN_OID = "1.2.40.0.10.2.1.1.261.100"; + public static final String MANDATE_LEG_PER_SOURCE_PIN_NAME = + URN_OID_PREFIX + MANDATE_LEG_PER_SOURCE_PIN_OID; + public static final String MANDATE_LEG_PER_SOURCE_PIN_FRIENDLY_NAME = + "MANDATOR-LEGAL-PERSON-SOURCE-PIN"; + public static final int MANDATE_LEG_PER_SOURCE_PIN_MAX_LENGTH = 128; + + @Deprecated + public static final String MANDATE_NAT_PER_SOURCE_PIN_TYPE_OID = "1.2.40.0.10.2.1.1.261.102"; + @Deprecated + public static final String MANDATE_NAT_PER_SOURCE_PIN_TYPE_NAME = + URN_OID_PREFIX + MANDATE_NAT_PER_SOURCE_PIN_TYPE_OID; + @Deprecated + public static final String MANDATE_NAT_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME = + "MANDATOR-NATURAL-PERSON-SOURCE-PIN-TYPE"; + @Deprecated + public static final int MANDATE_NAT_PER_SOURCE_PIN_TYPE_MAX_LENGTH = 128; + + public static final String MANDATE_LEG_PER_SOURCE_PIN_TYPE_OID = "1.2.40.0.10.2.1.1.261.76"; + public static final String MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME = + URN_OID_PREFIX + MANDATE_LEG_PER_SOURCE_PIN_TYPE_OID; + public static final String MANDATE_LEG_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME = + "MANDATOR-LEGAL-PERSON-SOURCE-PIN-TYPE"; + public static final int MANDATE_LEG_PER_SOURCE_PIN_TYPE_MAX_LENGTH = 128; + + public static final String MANDATE_NAT_PER_BPK_OID = "1.2.40.0.10.2.1.1.261.98"; + public static final String MANDATE_NAT_PER_BPK_NAME = URN_OID_PREFIX + MANDATE_NAT_PER_BPK_OID; + public static final String MANDATE_NAT_PER_BPK_FRIENDLY_NAME = "MANDATOR-NATURAL-PERSON-BPK"; + public static final int MANDATE_NAT_PER_BPK_MAX_LENGTH = 1024; + + public static final String MANDATE_NAT_PER_BPK_LIST_OID = "1.2.40.0.10.2.1.1.261.73"; + public static final String MANDATE_NAT_PER_BPK_LIST_NAME = + URN_OID_PREFIX + MANDATE_NAT_PER_BPK_LIST_OID; + public static final String MANDATE_NAT_PER_BPK_LIST_FRIENDLY_NAME = + "MANDATOR-NATURAL-PERSON-BPK-LIST"; + public static final int MANDATE_NAT_PER_ENC_LIST_MAX_LENGTH = 32767; + + public static final String MANDATE_NAT_PER_ENC_BPK_LIST_OID = "1.2.40.0.10.2.1.1.261.72"; + public static final String MANDATE_NAT_PER_ENC_BPK_LIST_NAME = + URN_OID_PREFIX + MANDATE_NAT_PER_ENC_BPK_LIST_OID; + public static final String MANDATE_NAT_PER_ENC_BPK_LIST_FRIENDLY_NAME = + "MANDATOR-NATURAL-PERSON-ENC-BPK-LIST"; + public static final int MANDATE_NAT_PER_ENC_BPK_LIST_MAX_LENGTH = 32767; + + public static final String MANDATE_NAT_PER_GIVEN_NAME_OID = "1.2.40.0.10.2.1.1.261.78"; + public static final String MANDATE_NAT_PER_GIVEN_NAME_NAME = + URN_OID_PREFIX + MANDATE_NAT_PER_GIVEN_NAME_OID; + public static final String MANDATE_NAT_PER_GIVEN_NAME_FRIENDLY_NAME = + "MANDATOR-NATURAL-PERSON-GIVEN-NAME"; + public static final int MANDATE_NAT_PER_GIVEN_NAME_MAX_LENGTH = 128; + + public static final String MANDATE_NAT_PER_FAMILY_NAME_OID = "1.2.40.0.10.2.1.1.261.80"; + public static final String MANDATE_NAT_PER_FAMILY_NAME_NAME = + URN_OID_PREFIX + MANDATE_NAT_PER_FAMILY_NAME_OID; + public static final String MANDATE_NAT_PER_FAMILY_NAME_FRIENDLY_NAME = + "MANDATOR-NATURAL-PERSON-FAMILY-NAME"; + public static final int MANDATE_NAT_PER_FAMILY_NAME_MAX_LENGTH = 128; + + public static final String MANDATE_NAT_PER_BIRTHDATE_OID = "1.2.40.0.10.2.1.1.261.82"; + public static final String MANDATE_NAT_PER_BIRTHDATE_NAME = + URN_OID_PREFIX + MANDATE_NAT_PER_BIRTHDATE_OID; + public static final String MANDATE_NAT_PER_BIRTHDATE_FRIENDLY_NAME = + "MANDATOR-NATURAL-PERSON-BIRTHDATE"; + public static final String MANDATE_NAT_PER_BIRTHDATE_FORMAT_PATTERN = BIRTHDATE_FORMAT_PATTERN; + + public static final String MANDATE_LEG_PER_FULL_NAME_OID = "1.2.40.0.10.2.1.1.261.84"; + public static final String MANDATE_LEG_PER_FULL_NAME_NAME = + URN_OID_PREFIX + MANDATE_LEG_PER_FULL_NAME_OID; + public static final String MANDATE_LEG_PER_FULL_NAME_FRIENDLY_NAME = + "MANDATOR-LEGAL-PERSON-FULL-NAME"; + public static final int MANDATE_LEG_PER_FULL_NAME_MAX_LENGTH = 256; + + public static final String MANDATE_PROF_REP_OID_OID = "1.2.40.0.10.2.1.1.261.86"; + public static final String MANDATE_PROF_REP_OID_NAME = URN_OID_PREFIX + MANDATE_PROF_REP_OID_OID; + public static final String MANDATE_PROF_REP_OID_FRIENDLY_NAME = "MANDATE-PROF-REP-OID"; + public static final int MANDATE_PROF_REP_OID_MAX_LENGTH = 256; + + public static final String MANDATE_PROF_REP_DESC_OID = "1.2.40.0.10.2.1.1.261.88"; + public static final String MANDATE_PROF_REP_DESC_NAME = + URN_OID_PREFIX + MANDATE_PROF_REP_DESC_OID; + public static final String MANDATE_PROF_REP_DESC_FRIENDLY_NAME = "MANDATE-PROF-REP-DESCRIPTION"; + public static final int MANDATE_PROF_REP_DESC_MAX_LENGTH = 1024; + + public static final String MANDATE_REFERENCE_VALUE_OID = "1.2.40.0.10.2.1.1.261.90"; + public static final String MANDATE_REFERENCE_VALUE_NAME = + URN_OID_PREFIX + MANDATE_REFERENCE_VALUE_OID; + public static final String MANDATE_REFERENCE_VALUE_FRIENDLY_NAME = "MANDATE-REFERENCE-VALUE"; + public static final int MANDATE_REFERENCE_VALUE_MAX_LENGTH = 100; + + public static final String MANDATE_IDENTIFIER_OID = "1.2.40.0.10.2.1.1.261.91"; + public static final String MANDATE_IDENTIFIER_FRIENDLY_NAME = "MANDATE-IDENTIFIER"; + public static final String MANDATE_IDENTIFIER_NAME = URN_OID_PREFIX + MANDATE_IDENTIFIER_OID; + public static final int MANDATE_IDENTIFIER_MAX_LENGTH = 256; + + + @Deprecated + public static final String MANDATE_FULL_MANDATE_OID = "1.2.40.0.10.2.1.1.261.92"; + @Deprecated + public static final String MANDATE_FULL_MANDATE_NAME = URN_OID_PREFIX + MANDATE_FULL_MANDATE_OID; + @Deprecated + public static final String MANDATE_FULL_MANDATE_FRIENDLY_NAME = "MANDATE-FULL-MANDATE"; + @Deprecated + public static final int MANDATE_FULL_MANDATE_MAX_LENGTH = 32767; + + public static final String INVOICE_RECPT_ID_OID = "1.2.40.0.10.2.1.1.261.40"; + public static final String INVOICE_RECPT_ID_NAME = URN_OID_PREFIX + INVOICE_RECPT_ID_OID; + public static final String INVOICE_RECPT_ID_FRIENDLY_NAME = "INVOICE-RECPT-ID"; + public static final int INVOICE_RECPT_ID_MAX_LENGTH = 64; + + public static final String COST_CENTER_ID_OID = "1.2.40.0.10.2.1.1.261.50"; + public static final String COST_CENTER_ID_NAME = URN_OID_PREFIX + COST_CENTER_ID_OID; + public static final String COST_CENTER_ID_FRIENDLY_NAME = "COST-CENTER-ID"; + public static final int COST_CENTER_ID_MAX_LENGTH = 32767; + + public static final String CHARGE_CODE_OID = "1.2.40.0.10.2.1.1.261.60"; + public static final String CHARGE_CODE_NAME = URN_OID_PREFIX + CHARGE_CODE_OID; + public static final String CHARGE_CODE_FRIENDLY_NAME = "CHARGE-CODE"; + public static final int CHARGE_CODE_MAX_LENGTH = 32767; + + public static final String PVP_HOLDEROFKEY_OID = "1.2.40.0.10.2.1.1.261.xx.xx"; + public static final String PVP_HOLDEROFKEY_NAME = URN_OID_PREFIX + PVP_HOLDEROFKEY_OID; + public static final String PVP_HOLDEROFKEY_FRIENDLY_NAME = "HOLDER-OF-KEY-CERTIFICATE"; } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/XMLNamespaceConstants.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/XMLNamespaceConstants.java index 2b70fd4c..8f367281 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/XMLNamespaceConstants.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/data/XMLNamespaceConstants.java @@ -1,24 +1,20 @@ /******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ /******************************************************************************* *******************************************************************************/ @@ -35,7 +31,7 @@ import java.util.Map; /** * Contains various constants used throughout the system. - + * */ public interface XMLNamespaceConstants { /** Root location of the schema files. */ @@ -43,21 +39,21 @@ public interface XMLNamespaceConstants { /** URI of the Widerrufregister XML namespace. */ public static final String WRR_NS_URI = - "http://reference.e-government.gv.at/namespace/moavv/20041223"; + "http://reference.e-government.gv.at/namespace/moavv/20041223"; /** Prefix used for the Widerrufregister XML namespace */ public static final String WRR_PREFIX = "wrr"; /** URI of the StandardTextBlock XML namespace. */ public static final String STB_NS_URI = - "http://reference.e-government.gv.at/namespace/standardtextblock/20041105#"; + "http://reference.e-government.gv.at/namespace/standardtextblock/20041105#"; /** Prefix used for the standard text block XML namespace */ public static final String STB_PREFIX = "stb"; /** URI of the MOA XML namespace. */ public static final String MOA_NS_URI = - "http://reference.e-government.gv.at/namespace/moa/20020822#"; + "http://reference.e-government.gv.at/namespace/moa/20020822#"; /** Name of the mandates infobox */ public static final String INFOBOXIDENTIFIER_MANDATES = "Mandates"; @@ -67,36 +63,35 @@ public interface XMLNamespaceConstants { /** URI of the Mandate XML namespace. */ public static final String MD_NS_URI = - "http://reference.e-government.gv.at/namespace/mandates/20040701#"; + "http://reference.e-government.gv.at/namespace/mandates/20040701#"; /** Prefix used for the Mandate XML namespace */ public static final String MVV_PREFIX = "mvv"; /** URI of the Mandate XML namespace. */ public static final String MVV_NS_URI = - "http://reference.e-government.gv.at/namespace/moavv/app2mvv/20041125"; + "http://reference.e-government.gv.at/namespace/moavv/app2mvv/20041125"; /** Prefix used for the MandateCheckProfile XML namespace */ public static final String MDP_PREFIX = "mdp"; /** URI of the Mandate XML namespace. */ public static final String MDP_NS_URI = - "http://reference.e-government.gv.at/namespace/mandateprofile/20041105#"; + "http://reference.e-government.gv.at/namespace/mandateprofile/20041105#"; /** Prefix used for the MOA XML namespace */ public static final String MOA_PREFIX = "moa"; /** Local location of the MOA XML schema definition. */ - public static final String MOA_SCHEMA_LOCATION = - SCHEMA_ROOT + "MOA-SPSS-2.0.0.xsd"; + public static final String MOA_SCHEMA_LOCATION = SCHEMA_ROOT + "MOA-SPSS-2.0.0.xsd"; /** URI of the MOA configuration XML namespace. */ public static final String MOA_CONFIG_NS_URI = - "http://reference.e-government.gv.at/namespace/moaconfig/20021122#"; + "http://reference.e-government.gv.at/namespace/moaconfig/20021122#"; /** URI of the MOA ID configuration XML namespace. */ public static final String MOA_ID_CONFIG_NS_URI = - "http://www.buergerkarte.at/namespaces/moaconfig#"; + "http://www.buergerkarte.at/namespaces/moaconfig#"; /** Prefix used for the MOA configuration XML namespace */ public static final String MOA_CONFIG_PREFIX = "conf"; @@ -105,97 +100,85 @@ public interface XMLNamespaceConstants { public static final String MOA_ID_CONFIG_PREFIX = "confID"; /** Local location of the MOA configuration XML schema definition. */ - public static final String MOA_CONFIG_SCHEMA_LOCATION = - SCHEMA_ROOT + "MOA-SPSS-config-2.0.0.xsd"; + public static final String MOA_CONFIG_SCHEMA_LOCATION = SCHEMA_ROOT + "MOA-SPSS-config-2.0.0.xsd"; /** Local location of the MOA ID configuration XML schema definition. */ public static final String MOA_ID_CONFIG_SCHEMA_LOCATION = - SCHEMA_ROOT + "MOA-ID-Configuration-1.5.2.xsd"; + SCHEMA_ROOT + "MOA-ID-Configuration-1.5.2.xsd"; /** URI of the Security Layer 1.0 namespace. */ public static final String SL10_NS_URI = - "http://www.buergerkarte.at/namespaces/securitylayer/20020225#"; + "http://www.buergerkarte.at/namespaces/securitylayer/20020225#"; /** Prefix used for the Security Layer 1.0 XML namespace */ public static final String SL10_PREFIX = "sl10"; /** Local location of the Security Layer 1.0 XML schema definition */ - public static final String SL10_SCHEMA_LOCATION = - SCHEMA_ROOT + "Core.20020225.xsd"; + public static final String SL10_SCHEMA_LOCATION = SCHEMA_ROOT + "Core.20020225.xsd"; /** URI of the Security Layer 1.1 XML namespace */ public static final String SL11_NS_URI = - "http://www.buergerkarte.at/namespaces/securitylayer/20020831#"; + "http://www.buergerkarte.at/namespaces/securitylayer/20020831#"; /** Prefix used for the Security Layer 1.1 XML namespace */ public static final String SL11_PREFIX = "sl11"; /** Local location of the Security Layer 1.1 XML schema definition */ - public static final String SL11_SCHEMA_LOCATION = - SCHEMA_ROOT + "Core.20020831.xsd"; - + public static final String SL11_SCHEMA_LOCATION = SCHEMA_ROOT + "Core.20020831.xsd"; + /** URI of the Security Layer 1.2 XML namespace */ public static final String SL12_NS_URI = - "http://www.buergerkarte.at/namespaces/securitylayer/1.2#"; + "http://www.buergerkarte.at/namespaces/securitylayer/1.2#"; /** Prefix used for the Security Layer 1.2 XML namespace */ public static final String SL12_PREFIX = "sl"; /** Local location of the Security Layer 1.2 XML schema definition */ - public static final String SL12_SCHEMA_LOCATION = - SCHEMA_ROOT + "Core-1.2.xsd"; - + public static final String SL12_SCHEMA_LOCATION = SCHEMA_ROOT + "Core-1.2.xsd"; + /** URI of the ECDSA XML namespace */ - public static final String ECDSA_NS_URI = - "http://www.w3.org/2001/04/xmldsig-more#"; - + public static final String ECDSA_NS_URI = "http://www.w3.org/2001/04/xmldsig-more#"; + /** Prefix used for ECDSA namespace */ public static final String ECDSA_PREFIX = "ecdsa"; /** Local location of ECDSA XML schema definition */ - public static final String ECDSA_SCHEMA_LOCATION = - SCHEMA_ROOT + "ECDSAKeyValue.xsd"; + public static final String ECDSA_SCHEMA_LOCATION = SCHEMA_ROOT + "ECDSAKeyValue.xsd"; /** URI of the PersonData XML namespace. */ public static final String PD_NS_URI = - "http://reference.e-government.gv.at/namespace/persondata/20020228#"; + "http://reference.e-government.gv.at/namespace/persondata/20020228#"; /** Prefix used for the PersonData XML namespace */ public static final String PD_PREFIX = "pr"; -// /** Local location of the PersonData XML schema definition */ -// public static final String PD_SCHEMA_LOCATION = -// SCHEMA_ROOT + "PersonData.xsd"; - + // /** Local location of the PersonData XML schema definition */ + // public static final String PD_SCHEMA_LOCATION = + // SCHEMA_ROOT + "PersonData.xsd"; + /** Local location of the PersonData XML schema definition */ - public static final String PD_SCHEMA_LOCATION = - SCHEMA_ROOT + "PersonData_20_en_moaWID.xsd"; + public static final String PD_SCHEMA_LOCATION = SCHEMA_ROOT + "PersonData_20_en_moaWID.xsd"; /** URI of the SAML namespace. */ - public static final String SAML_NS_URI = - "urn:oasis:names:tc:SAML:1.0:assertion"; + public static final String SAML_NS_URI = "urn:oasis:names:tc:SAML:1.0:assertion"; /** Prefix used for the SAML XML namespace */ public static final String SAML_PREFIX = "saml"; /** Local location of the SAML XML schema definition. */ - public static final String SAML_SCHEMA_LOCATION = - SCHEMA_ROOT + "cs-sstc-schema-assertion-01.xsd"; + public static final String SAML_SCHEMA_LOCATION = SCHEMA_ROOT + "cs-sstc-schema-assertion-01.xsd"; /** URI of the SAML request-response protocol namespace. */ - public static final String SAMLP_NS_URI = - "urn:oasis:names:tc:SAML:1.0:protocol"; + public static final String SAMLP_NS_URI = "urn:oasis:names:tc:SAML:1.0:protocol"; /** Prefix used for the SAML request-response protocol namespace */ public static final String SAMLP_PREFIX = "samlp"; /** Local location of the SAML request-response protocol schema definition. */ - public static final String SAMLP_SCHEMA_LOCATION = - SCHEMA_ROOT + "cs-sstc-schema-protocol-01.xsd"; + public static final String SAMLP_SCHEMA_LOCATION = SCHEMA_ROOT + "cs-sstc-schema-protocol-01.xsd"; /** URI of the XML namespace. */ - public static final String XML_NS_URI = - "http://www.w3.org/XML/1998/namespace"; + public static final String XML_NS_URI = "http://www.w3.org/XML/1998/namespace"; /** Prefix used for the XML namespace */ public static final String XML_PREFIX = "xml"; @@ -210,16 +193,13 @@ public interface XMLNamespaceConstants { public static final String XSI_PREFIX = "xsi"; /** Local location of the XSI schema definition. */ - public static final String XSI_SCHEMA_LOCATION = - SCHEMA_ROOT + "XMLSchema-instance.xsd"; + public static final String XSI_SCHEMA_LOCATION = SCHEMA_ROOT + "XMLSchema-instance.xsd"; /** URI of the XSI XMLNS namespace */ - public static final String XSI_NS_URI = - "http://www.w3.org/2001/XMLSchema-instance"; + public static final String XSI_NS_URI = "http://www.w3.org/2001/XMLSchema-instance"; /** URI of the XSLT XML namespace */ - public static final String XSLT_NS_URI = - "http://www.w3.org/1999/XSL/Transform"; + public static final String XSLT_NS_URI = "http://www.w3.org/1999/XSL/Transform"; /** Prefix used for the XSLT XML namespace */ public static final String XSLT_PREFIX = "xsl"; @@ -231,189 +211,168 @@ public interface XMLNamespaceConstants { public static final String DSIG_PREFIX = "dsig"; /** Local location of the XMLDSig XML schema. */ - public static final String DSIG_SCHEMA_LOCATION = - SCHEMA_ROOT + "xmldsig-core-schema.xsd"; + public static final String DSIG_SCHEMA_LOCATION = SCHEMA_ROOT + "xmldsig-core-schema.xsd"; /** URI of the XMLDSig XPath Filter XML namespace. */ - public static final String DSIG_FILTER2_NS_URI = - "http://www.w3.org/2002/06/xmldsig-filter2"; + public static final String DSIG_FILTER2_NS_URI = "http://www.w3.org/2002/06/xmldsig-filter2"; /** Prefix used for the XMLDSig XPath Filter XML namespace */ public static final String DSIG_FILTER2_PREFIX = "dsig-filter2"; /** Local location of the XMLDSig XPath Filter XML schema definition. */ - public static final String DSIG_FILTER2_SCHEMA_LOCATION = - SCHEMA_ROOT + "xmldsig-filter2.xsd"; + public static final String DSIG_FILTER2_SCHEMA_LOCATION = SCHEMA_ROOT + "xmldsig-filter2.xsd"; /** URI of the Exclusive Canonicalization XML namespace */ - public static final String DSIG_EC_NS_URI = - "http://www.w3.org/2001/10/xml-exc-c14n#"; - + public static final String DSIG_EC_NS_URI = "http://www.w3.org/2001/10/xml-exc-c14n#"; + /** Prefix used for the Exclusive Canonicalization XML namespace */ public static final String DSIG_EC_PREFIX = "ec"; /** Local location of the Exclusive Canonicalizaion XML schema definition */ public static final String DSIG_EC_SCHEMA_LOCATION = - SCHEMA_ROOT + "exclusive-canonicalization.xsd"; + SCHEMA_ROOT + "exclusive-canonicalization.xsd"; + + /** URI of the XMLLoginParameterResolver Configuration XML namespace */ + public static final String XMLLPR_NS_URI = + "http://reference.e-government.gv.at/namespace/moa/20020822#/xmllpr20030814"; - /** URI of the XMLLoginParameterResolver Configuration XML namespace */ - public static final String XMLLPR_NS_URI="http://reference.e-government.gv.at/namespace/moa/20020822#/xmllpr20030814"; + /** Local location of the XMLLoginParameterResolver Configuration XML schema definition */ + public static final String XMLLPR_SCHEMA_LOCATION = SCHEMA_ROOT + "MOAIdentities.xsd"; - /** Local location of the XMLLoginParameterResolver Configuration XML schema definition */ - public static final String XMLLPR_SCHEMA_LOCATION = - SCHEMA_ROOT + "MOAIdentities.xsd"; - - /** Local location of the XAdES v1.1.1 schema definition */ - public static final String XADES_1_1_1_SCHEMA_LOCATION = - SCHEMA_ROOT + "XAdES-1.1.1.xsd"; + /** Local location of the XAdES v1.1.1 schema definition */ + public static final String XADES_1_1_1_SCHEMA_LOCATION = SCHEMA_ROOT + "XAdES-1.1.1.xsd"; /** URI of the XAdES v1.1.1 namespace */ public static final String XADES_1_1_1_NS_URI = "http://uri.etsi.org/01903/v1.1.1#"; - + public static final String XADES_1_1_1_NS_PREFIX = "xades111"; - - /** Local location of the XAdES v1.2.2 schema definition */ - public static final String XADES_1_2_2_SCHEMA_LOCATION = - SCHEMA_ROOT + "XAdES-1.2.2.xsd"; + + /** Local location of the XAdES v1.2.2 schema definition */ + public static final String XADES_1_2_2_SCHEMA_LOCATION = SCHEMA_ROOT + "XAdES-1.2.2.xsd"; /** URI of the XAdES v1.2.2 namespace */ public static final String XADES_1_2_2_NS_URI = "http://uri.etsi.org/01903/v1.2.2#"; - + public static final String XADES_1_2_2_NS_PREFIX = "xades122"; - /** Local location of the XAdES v1.1.1 schema definition */ - public static final String XADES_1_3_2_SCHEMA_LOCATION = - SCHEMA_ROOT + "XAdES-1.3.2.xsd"; + /** Local location of the XAdES v1.1.1 schema definition */ + public static final String XADES_1_3_2_SCHEMA_LOCATION = SCHEMA_ROOT + "XAdES-1.3.2.xsd"; /** URI of the XAdES v1.3.2 namespace */ public static final String XADES_1_3_2_NS_URI = "http://uri.etsi.org/01903/v1.3.2#"; - + public static final String XADES_1_3_2_NS_PREFIX = "xades132"; - /** Local location of the XAdES v1.4.1 schema definition */ - public static final String XADES_1_4_1_SCHEMA_LOCATION = - SCHEMA_ROOT + "XAdES-1.4.1.xsd"; + /** Local location of the XAdES v1.4.1 schema definition */ + public static final String XADES_1_4_1_SCHEMA_LOCATION = SCHEMA_ROOT + "XAdES-1.4.1.xsd"; /** URI of the XAdES v1.4.1 namespace */ public static final String XADES_1_4_1_NS_URI = "http://uri.etsi.org/01903/v1.4.1#"; - + public static final String XADES_1_4_1_NS_PREFIX = "xades141"; /** URI of the SAML 2.0 namespace. */ - public static final String SAML2_NS_URI = - "urn:oasis:names:tc:SAML:2.0:assertion"; + public static final String SAML2_NS_URI = "urn:oasis:names:tc:SAML:2.0:assertion"; /** Prefix used for the SAML 2.0 XML namespace */ public static final String SAML2_PREFIX = "saml2"; /** Local location of the SAML 2.0 XML schema definition. */ - public static final String SAML2_SCHEMA_LOCATION = - SCHEMA_ROOT + "saml-schema-assertion-2.0.xsd"; - + public static final String SAML2_SCHEMA_LOCATION = SCHEMA_ROOT + "saml-schema-assertion-2.0.xsd"; + /** URI of the SAML 2.0 protocol namespace. */ - public static final String SAML2P_NS_URI = - "urn:oasis:names:tc:SAML:2.0:protocol"; + public static final String SAML2P_NS_URI = "urn:oasis:names:tc:SAML:2.0:protocol"; /** Prefix used for the SAML 2.0 protocol XML namespace */ public static final String SAML2P_PREFIX = "saml2p"; /** Local location of the SAML 2.0 protocol XML schema definition. */ - public static final String SAML2P_SCHEMA_LOCATION = - SCHEMA_ROOT + "saml-schema-protocol-2.0.xsd"; - + public static final String SAML2P_SCHEMA_LOCATION = SCHEMA_ROOT + "saml-schema-protocol-2.0.xsd"; + /** URI of the STORK namespace. */ - public static final String STORK_NS_URI = - "urn:eu:stork:names:tc:STORK:1.0:assertion"; + public static final String STORK_NS_URI = "urn:eu:stork:names:tc:STORK:1.0:assertion"; /** Prefix used for the STORK XML namespace */ public static final String STORK_PREFIX = "stork"; /** Local location of the STORK XML schema definition. */ - public static final String STORK_SCHEMA_LOCATION = - SCHEMA_ROOT + "stork-schema-assertion-1.0.xsd"; - + public static final String STORK_SCHEMA_LOCATION = SCHEMA_ROOT + "stork-schema-assertion-1.0.xsd"; + /** URI of the STORK protocol namespace. */ - public static final String STORKP_NS_URI = - "urn:eu:stork:names:tc:STORK:1.0:protocol"; + public static final String STORKP_NS_URI = "urn:eu:stork:names:tc:STORK:1.0:protocol"; /** Prefix used for the STORK protocol XML namespace */ public static final String STORKP_PREFIX = "storkp"; /** Local location of the STORK protocol XML schema definition. */ - public static final String STORKP_SCHEMA_LOCATION = - SCHEMA_ROOT + "stork-schema-protocol-1.0.xsd"; - + public static final String STORKP_SCHEMA_LOCATION = SCHEMA_ROOT + "stork-schema-protocol-1.0.xsd"; + /** URI of the TSL namespace. */ - public static final String TSL_NS_URI = - "http://uri.etsi.org/02231/v2#"; + public static final String TSL_NS_URI = "http://uri.etsi.org/02231/v2#"; /** Prefix used for the TSL namespace */ public static final String TSL_PREFIX = "tsl1"; /** Local location of the TSL schema definition. */ - public static final String TSL_SCHEMA_LOCATION = - SCHEMA_ROOT + "ts_119612v010201_xsd.xsd"; + public static final String TSL_SCHEMA_LOCATION = SCHEMA_ROOT + "ts_119612v010201_xsd.xsd"; /** URI of the TSL SIE namespace. */ public static final String TSL_SIE_NS_URI = - "http://uri.etsi.org/TrstSvc/SvcInfoExt/eSigDir-1999-93-EC-TrustedList/#"; + "http://uri.etsi.org/TrstSvc/SvcInfoExt/eSigDir-1999-93-EC-TrustedList/#"; /** Prefix used for the TSL SIE namespace */ public static final String TSL_SIE_PREFIX = "tslsie"; /** Local location of the TSL SIE schema definition. */ - public static final String TSL_SIE_SCHEMA_LOCATION = - SCHEMA_ROOT + "ts_119612v010201_sie_xsd.xsd"; - + public static final String TSL_SIE_SCHEMA_LOCATION = SCHEMA_ROOT + "ts_119612v010201_sie_xsd.xsd"; + /** URI of the TSL additional types namespace. */ - public static final String TSL_ADDTYPES_NS_URI = - "http://uri.etsi.org/02231/v2/additionaltypes#"; + public static final String TSL_ADDTYPES_NS_URI = "http://uri.etsi.org/02231/v2/additionaltypes#"; /** Prefix used for the TSL additional types namespace */ public static final String TSL_ADDTYPES_PREFIX = "tsltype"; /** Local location of the TSL additional types schema definition. */ public static final String TSL_ADDTYPES_SCHEMA_LOCATION = - SCHEMA_ROOT + "ts_ts_119612v010201_additionaltypes_xsd.xsd"; - + SCHEMA_ROOT + "ts_ts_119612v010201_additionaltypes_xsd.xsd"; + /** URI of the XML Encryption namespace. */ - public static final String XENC_NS_URI = - "http://www.w3.org/2001/04/xmlenc#"; + public static final String XENC_NS_URI = "http://www.w3.org/2001/04/xmlenc#"; /** Prefix used for the XML Encryption XML namespace */ public static final String XENC_PREFIX = "xenc"; /** Local location of the XML Encryption XML schema definition. */ - public static final String XENC_SCHEMA_LOCATION = - SCHEMA_ROOT + "xenc-schema.xsd"; + public static final String XENC_SCHEMA_LOCATION = SCHEMA_ROOT + "xenc-schema.xsd"; /** Prefix used for the XML Encryption XML namespace */ public static final String SAML2_METADATA_PREFIX = "md"; - + /** Prefix used for the XML Encryption XML namespace */ public static final String SAML2_METADATA_URI = "urn:oasis:names:tc:SAML:2.0:metadata"; /** Local location of the XML Encryption XML schema definition. */ public static final String SAML2_METADATA_SCHEMA_LOCATION = - SCHEMA_ROOT + "saml-schema-metadata-2.0.xsd"; - - - /* Prefix and Schema definition for eIDAS specific SAML2 extensions*/ + SCHEMA_ROOT + "saml-schema-metadata-2.0.xsd"; + + + /* Prefix and Schema definition for eIDAS specific SAML2 extensions */ public static final String SAML2_eIDAS_EXTENSIONS_PREFIX = "eidas"; public static final String SAML2_eIDAS_EXTENSIONS = "http://eidas.europa.eu/saml-extensions"; - public static final String SAML2_eIDAS_EXTENSIONS_SCHEMA_LOCATION = SCHEMA_ROOT + "eIDAS_saml_extensions.xsd"; - - + public static final String SAML2_eIDAS_EXTENSIONS_SCHEMA_LOCATION = + SCHEMA_ROOT + "eIDAS_saml_extensions.xsd"; + + /* Prefix and Schema for SAML2 Entity Attributes */ public static final String SAML2_MDATTR_EXTENSIONS_PREFIX = "mdattr"; public static final String SAML2_MDATTR_EXTENSIONS = "urn:oasis:names:tc:SAML:metadata:attribute"; - public static final String SAML2_MDATTR_EXTENSIONS_SCHEMA_LOCATION = SCHEMA_ROOT + "sstc-metadata-attr.xsd"; - + public static final String SAML2_MDATTR_EXTENSIONS_SCHEMA_LOCATION = + SCHEMA_ROOT + "sstc-metadata-attr.xsd"; + /** - * Contains all namespaces and local schema locations for XML schema - * definitions relevant for MOA. For use in validating XML parsers. + * Contains all namespaces and local schema locations for XML schema definitions relevant for MOA. + * For use in validating XML parsers. */ - public static final String ALL_SCHEMA_LOCATIONS = - (MOA_NS_URI + " " + MOA_SCHEMA_LOCATION + " ") + public static final String ALL_SCHEMA_LOCATIONS = (MOA_NS_URI + " " + MOA_SCHEMA_LOCATION + " ") + (MOA_CONFIG_NS_URI + " " + MOA_CONFIG_SCHEMA_LOCATION + " ") + (MOA_ID_CONFIG_NS_URI + " " + MOA_ID_CONFIG_SCHEMA_LOCATION + " ") + (SL10_NS_URI + " " + SL10_SCHEMA_LOCATION + " ") @@ -443,64 +402,57 @@ public interface XMLNamespaceConstants { + (SAML2_METADATA_URI + " " + SAML2_METADATA_SCHEMA_LOCATION + " ") + (XENC_NS_URI + " " + XENC_SCHEMA_LOCATION + " ") + (SAML2_eIDAS_EXTENSIONS + " " + SAML2_eIDAS_EXTENSIONS_SCHEMA_LOCATION + " ") - + (SAML2_MDATTR_EXTENSIONS + " " + SAML2_MDATTR_EXTENSIONS_SCHEMA_LOCATION); + + (SAML2_MDATTR_EXTENSIONS + " " + SAML2_MDATTR_EXTENSIONS_SCHEMA_LOCATION); + - /** Security Layer manifest type URI. */ public static final String SL_MANIFEST_TYPE_URI = - "http://www.buergerkarte.at/specifications/Security-Layer/20020225#SignatureManifest"; + "http://www.buergerkarte.at/specifications/Security-Layer/20020225#SignatureManifest"; /** URI of the SHA1 digest algorithm */ - public static final String SHA1_URI = - "http://www.w3.org/2000/09/xmldsig#sha1"; - + public static final String SHA1_URI = "http://www.w3.org/2000/09/xmldsig#sha1"; + /** URI of the SHA1 digest algorithm */ - public static final String SHA256_URI = - "http://www.w3.org/2000/09/xmldsig#sha256"; - + public static final String SHA256_URI = "http://www.w3.org/2000/09/xmldsig#sha256"; + /** URI of the SHA1 digest algorithm */ - public static final String SHA384_URI = - "http://www.w3.org/2000/09/xmldsig#sha384"; - + public static final String SHA384_URI = "http://www.w3.org/2000/09/xmldsig#sha384"; + /** URI of the SHA1 digest algorithm */ - public static final String SHA512_URI = - "http://www.w3.org/2000/09/xmldsig#sha512"; - - public static final String SHA3_256_URI = - "http://www.w3.org/2007/05/xmldsig-more#sha3-256"; - - public static final String SHA3_512_URI = - "http://www.w3.org/2007/05/xmldsig-more#sha3-512"; - - - + public static final String SHA512_URI = "http://www.w3.org/2000/09/xmldsig#sha512"; + + public static final String SHA3_256_URI = "http://www.w3.org/2007/05/xmldsig-more#sha3-256"; + + public static final String SHA3_512_URI = "http://www.w3.org/2007/05/xmldsig-more#sha3-512"; + + + /** URI of the Canonical XML algorithm */ - public static final String C14N_URI = - "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; + public static final String C14N_URI = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; /** URI of the Canoncial XML with comments algorithm */ public static final String C14N_WITH_COMMENTS_URI = - "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"; + "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"; /** URI of the Exclusive Canonical XML algorithm */ - public static final String EXC_C14N_URI = - "http://www.w3.org/2001/10/xml-exc-c14n#"; - + public static final String EXC_C14N_URI = "http://www.w3.org/2001/10/xml-exc-c14n#"; + /** URI of the Exclusive Canonical XML with commments algorithm */ public static final String EXC_C14N_WITH_COMMENTS_URI = - "http://www.w3.org/2001/10/xml-exc-c14n#WithComments"; - - /** - * A map used to map namespace prefixes to namespace URIs - */ - public static final Map nSMap = Collections.unmodifiableMap(new HashMap(){ - private static final long serialVersionUID = 3845384324295136490L; - { - put(XMLNamespaceConstants.SAML_PREFIX, XMLNamespaceConstants.SAML_NS_URI); - put(XMLNamespaceConstants.ECDSA_PREFIX, "http://www.w3.org/2001/04/xmldsig-more#"); - put(XMLNamespaceConstants.DSIG_PREFIX, XMLNamespaceConstants.DSIG_NS_URI); - } - }); - - + "http://www.w3.org/2001/10/xml-exc-c14n#WithComments"; + + /** + * A map used to map namespace prefixes to namespace URIs + */ + public static final Map nSMap = + Collections.unmodifiableMap(new HashMap() { + private static final long serialVersionUID = 3845384324295136490L; + { + put(XMLNamespaceConstants.SAML_PREFIX, XMLNamespaceConstants.SAML_NS_URI); + put(XMLNamespaceConstants.ECDSA_PREFIX, "http://www.w3.org/2001/04/xmldsig-more#"); + put(XMLNamespaceConstants.DSIG_PREFIX, XMLNamespaceConstants.DSIG_NS_URI); + } + }); + + } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/GroupDefinition.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/GroupDefinition.java index 441f1917..b53ba830 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/GroupDefinition.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/GroupDefinition.java @@ -1,34 +1,34 @@ package at.gv.egiz.eaaf.core.api.gui; public class GroupDefinition { - - private final String name; - private final TYPE type; - - private GroupDefinition(String name, TYPE type) { - this.name = name; - this.type = type; - } - - public static GroupDefinition getInstance(String name, TYPE type) { - return new GroupDefinition(name, type); - } - - public String getName() { - return name; - } - - public TYPE getType() { - return type; - } - - public enum TYPE { - LIST("list"), - MAP("map"); - - private TYPE(String type) { - } - } - + + private final String name; + private final Type type; + + private GroupDefinition(final String name, final Type type) { + this.name = name; + this.type = type; + } + + public static GroupDefinition getInstance(final String name, final Type type) { + return new GroupDefinition(name, type); + } + + public String getName() { + return name; + } + + public Type getType() { + return type; + } + + public enum Type { + LIST("list"), MAP("map"); + + private Type(final String type) { + + } + } + } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IGUIBuilderConfiguration.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IGUIBuilderConfiguration.java deleted file mode 100644 index 82d82a3a..00000000 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IGUIBuilderConfiguration.java +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.api.gui; - -import java.util.Map; - -/** - * @author tlenz - * - */ -public interface IGUIBuilderConfiguration { - - - /** - * Define the name of the template (with suffix) which should be used - * - * @return templatename, but never null - */ - public String getViewName(); - - /** - * Define the parameters, which should be evaluated in the template - * - * @return Map of parameters, which should be added to template - */ - public Map getViewParameters(); - - /** - * Get the contentType, which should be set in HTTP response - *

    - * DefaultValue: text/html;charset=UTF-8 - * - * @return ContentType, or null if default ContentType should be used. - */ - public String getDefaultContentType(); -} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IGUIBuilderConfigurationFactory.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IGUIBuilderConfigurationFactory.java deleted file mode 100644 index 1776a630..00000000 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IGUIBuilderConfigurationFactory.java +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.api.gui; - -import java.net.MalformedURLException; -import java.net.URI; - -import at.gv.egiz.eaaf.core.api.IRequest; - -public interface IGUIBuilderConfigurationFactory { - - /** - * Get a DefaultGuiBuilderConfiguration to render an error message - * - * @param authURL PublicURLPrefix of the IDP but never null - * @return - */ - public IGUIBuilderConfiguration getDefaultErrorGUI(String authURL); - - /** - * @param Current processed pending-request but never null - * @param viewName Name of the default template (with suffix) but never null - * @param configRootContextDir Path to configuration root directory - * @return - * @throws MalformedURLException If configRootContextDir is not a valid URI - */ - public IVelocityGUIBuilderConfiguration getSPSpecificSAML2PostConfiguration(IRequest pendingReq, String viewName, URI configRootContextDir) - throws MalformedURLException; - -} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IGUIFormBuilder.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IGUIFormBuilder.java deleted file mode 100644 index 7730e516..00000000 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IGUIFormBuilder.java +++ /dev/null @@ -1,74 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.api.gui; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import at.gv.egiz.eaaf.core.exceptions.GUIBuildException; - -/** - * @author tlenz - * - */ -public interface IGUIFormBuilder { - - - - /** - * Parse a GUI template, with parameters into a http servlet-response - * and use the default http-response content-type. - *

    - * The parser use the VelocityEngine as internal template evaluator. - * - * @param httpReq http-request object - * @param httpResp http-response object - * @param config Configuration object - * @param loggerName String, which should be used from logger - * - * @throws GUIBuildException - */ - public void build(HttpServletRequest httpReq, HttpServletResponse httpResp, IGUIBuilderConfiguration config, String loggerName) throws GUIBuildException; - - /** - * Parse a GUI template, with parameters into a http servlet-response. - *

    - * The parser use the VelocityEngine as internal template evaluator. - * - * @param httpReq http-request object - * @param httpResp http-response object - * @param config Configuration object - * @param contentType http-response content-type, which should be set - * @param loggerName String, which should be used from logger - * - * @throws GUIBuildException - */ - void build(HttpServletRequest httpReq, HttpServletResponse httpResp, IGUIBuilderConfiguration config, String contentType, - String loggerName) throws GUIBuildException; - - -} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IGuiBuilderConfiguration.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IGuiBuilderConfiguration.java new file mode 100644 index 00000000..6fa80919 --- /dev/null +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IGuiBuilderConfiguration.java @@ -0,0 +1,55 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. + */ + +package at.gv.egiz.eaaf.core.api.gui; + +import java.util.Map; + +/** + * GUI builder configuration. + * + * @author tlenz + * + */ +public interface IGuiBuilderConfiguration { + + + /** + * Define the name of the template (with suffix) which should be used. + * + * @return templatename, but never null + */ + public String getViewName(); + + /** + * Define the parameters, which should be evaluated in the template. + * + * @return Map of parameters, which should be added to template + */ + public Map getViewParameters(); + + /** + * Get the contentType, which should be set in HTTP response.
    + *
    + * DefaultValue: text/html;charset=UTF-8 + * + * @return ContentType, or null if default ContentType should be used. + */ + public String getDefaultContentType(); +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IGuiBuilderConfigurationFactory.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IGuiBuilderConfigurationFactory.java new file mode 100644 index 00000000..77bdf89d --- /dev/null +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IGuiBuilderConfigurationFactory.java @@ -0,0 +1,53 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + + +package at.gv.egiz.eaaf.core.api.gui; + +import java.net.MalformedURLException; +import java.net.URI; +import at.gv.egiz.eaaf.core.api.IRequest; + +public interface IGuiBuilderConfigurationFactory { + + /** + * Get a DefaultGuiBuilderConfiguration to render an error message. + * + * @param authUrl PublicURLPrefix of the IDP but never null + * @return + */ + public IGuiBuilderConfiguration getDefaultErrorGui(String authUrl); + + /** + * Default Velocity based GUI builder configuration. + * + *

    + * Manly used for SAML2 POST-Binding + *

    + * + * @param pendingReq Current processed pending-request but never null + * @param viewName Name of the default template (with suffix) but never null + * @param configRootContextDir Path to configuration root directory + * @return GUI builder configuration + * @throws MalformedURLException If configRootContextDir is not a valid URI + */ + public IVelocityGuiBuilderConfiguration getSpSpecificSaml2PostConfiguration(IRequest pendingReq, + String viewName, URI configRootContextDir) throws MalformedURLException; + +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IGuiFormBuilder.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IGuiFormBuilder.java new file mode 100644 index 00000000..25349861 --- /dev/null +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IGuiFormBuilder.java @@ -0,0 +1,70 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.api.gui; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import at.gv.egiz.eaaf.core.exceptions.GuiBuildException; + +/** + * Builder to generate HTML GUIs. + * + * @author tlenz + * + */ +public interface IGuiFormBuilder { + + + + /** + * Parse a GUI template, with parameters into a http servlet-response and use the default + * http-response content-type.
    + *
    + * The parser use the VelocityEngine as internal template evaluator. + * + * @param httpReq http-request object + * @param httpResp http-response object + * @param config Configuration object + * @param loggerName String, which should be used from logger + * + * @throws GuiBuildException in case of an error + */ + public void build(HttpServletRequest httpReq, HttpServletResponse httpResp, + IGuiBuilderConfiguration config, String loggerName) throws GuiBuildException; + + /** + * Parse a GUI template, with parameters into a http servlet-response.
    + *
    + * The parser use the VelocityEngine as internal template evaluator. + * + * @param httpReq http-request object + * @param httpResp http-response object + * @param config Configuration object + * @param contentType http-response content-type, which should be set + * @param loggerName String, which should be used from logger + * + * @throws GuiBuildException in case of an error + */ + void build(HttpServletRequest httpReq, HttpServletResponse httpResp, + IGuiBuilderConfiguration config, String contentType, String loggerName) + throws GuiBuildException; + + +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/ISpringMVCGUIFormBuilder.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/ISpringMVCGUIFormBuilder.java deleted file mode 100644 index e759b253..00000000 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/ISpringMVCGUIFormBuilder.java +++ /dev/null @@ -1,5 +0,0 @@ -package at.gv.egiz.eaaf.core.api.gui; - -public interface ISpringMVCGUIFormBuilder extends IGUIFormBuilder{ - -} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/ISpringMvcGuiFormBuilder.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/ISpringMvcGuiFormBuilder.java new file mode 100644 index 00000000..43591b5d --- /dev/null +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/ISpringMvcGuiFormBuilder.java @@ -0,0 +1,5 @@ +package at.gv.egiz.eaaf.core.api.gui; + +public interface ISpringMvcGuiFormBuilder extends IGuiFormBuilder { + +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IVelocityGUIBuilderConfiguration.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IVelocityGUIBuilderConfiguration.java deleted file mode 100644 index e56bf1af..00000000 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IVelocityGUIBuilderConfiguration.java +++ /dev/null @@ -1,22 +0,0 @@ -package at.gv.egiz.eaaf.core.api.gui; - -import java.io.InputStream; - -public interface IVelocityGUIBuilderConfiguration extends IGUIBuilderConfiguration { - /** - * Get a specific classpath template-directory prefix, which is used - * to load a template from classpath by using ClassLoader.getResourceAsStream(...) - * - * @return Classpath directory, or null if the default directory should be used - */ - public String getClasspathTemplateDir(); - - /** - * Get the GUI template with a specific name - * - * @param viewName Name of the template - * @return Tempate as InputStream, or null if default getTemplate method should be used - */ - public InputStream getTemplate(String viewName); - -} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IVelocityGuiBuilderConfiguration.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IVelocityGuiBuilderConfiguration.java new file mode 100644 index 00000000..a6ea0606 --- /dev/null +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/IVelocityGuiBuilderConfiguration.java @@ -0,0 +1,23 @@ +package at.gv.egiz.eaaf.core.api.gui; + +import java.io.InputStream; + +public interface IVelocityGuiBuilderConfiguration extends IGuiBuilderConfiguration { + /** + * Get a specific classpath template-directory prefix, which is used to load a template from + * classpath by using ClassLoader.getResourceAsStream(...). + * + * @return Classpath directory, or null if the default directory should be used + */ + public String getClasspathTemplateDir(); + + /** + * Get the GUI template with a specific name. + * + * @param viewName Name of the template + * @return Tempate as InputStream, or null if default getTemplate method should be + * used + */ + public InputStream getTemplate(String viewName); + +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/ModifyableGuiBuilderConfiguration.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/ModifyableGuiBuilderConfiguration.java index 6df6a78f..9d6b10ef 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/ModifyableGuiBuilderConfiguration.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/gui/ModifyableGuiBuilderConfiguration.java @@ -1,29 +1,22 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.api.gui; import javax.annotation.Nonnull; @@ -31,24 +24,26 @@ import javax.annotation.Nullable; public interface ModifyableGuiBuilderConfiguration { - /** - * Add a key/value pair into Velocity context.
    - * IMPORTANT: external HTML escapetion is required, because it is NOT done internally - * - * @param group Group element of the key parameter, or null if root element should be set - * @param key velocity context key - * @param value of this key - */ - void putCustomParameterWithOutEscaption(@Nullable GroupDefinition group, @Nonnull String key, @Nonnull Object value); + /** + * Add a key/value pair into Velocity context.
    + * IMPORTANT: external HTML escapetion is required, because it is NOT done internally + * + * @param group Group element of the key parameter, or null if root element should be set + * @param key velocity context key, can be null in case of List based group element + * @param value of this key + */ + void putCustomParameterWithOutEscaption(@Nullable GroupDefinition group, @Nullable String key, + @Nonnull Object value); - /** - * Add a key/value pair into Velocity context.
    - * All parameters get escaped internally - * - * @param group Group element of the key parameter, or null if root element should be set - * @param key velocity context key - * @param value of this key - */ - void putCustomParameter(@Nullable GroupDefinition group, @Nonnull String key, @Nonnull String value); + /** + * Add a key/value pair into Velocity context.
    + * All parameters get escaped internally + * + * @param group Group element of the key parameter, or null if root element should be set + * @param key velocity context key, can be null in case of List based group element + * @param value of this key + */ + void putCustomParameter(@Nullable GroupDefinition group, @Nullable String key, + @Nonnull String value); -} \ No newline at end of file +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/EAAFAuthProcessDataConstants.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/EAAFAuthProcessDataConstants.java deleted file mode 100644 index 7ce24cf4..00000000 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/EAAFAuthProcessDataConstants.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.api.idp; - -public interface EAAFAuthProcessDataConstants { - - public static final String GENERIC_PREFIX = "generic_"; - - public static final String VALUE_ISSUEINSTANT = "direct_issueInstant"; - - public static final String FLAG_IS_AUTHENTICATED = "direct_flagIsAuth"; - public static final String FLAG_IS_FOREIGNER = "direct_flagIsForeigner"; - public static final String FLAG_USE_MANDATE = "direct_flagUseMandate"; - public static final String FLAG_IS_ORGANWALTER = "direct_flagOrganwalter"; - public static final String FLAG_IS_NEW_EID_PROCESS = "direct_flagIsNewEID"; - - @Deprecated public static final String VALUE_IDENTITYLINK = "direct_idl"; - public static final String VALUE_QAALEVEL = "direct_qaaLevel"; - @Deprecated public static final String VALUE_MISMANDATE = "direct_MIS_Mandate"; - - -} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/EaafAuthProcessDataConstants.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/EaafAuthProcessDataConstants.java new file mode 100644 index 00000000..e4763ddc --- /dev/null +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/EaafAuthProcessDataConstants.java @@ -0,0 +1,41 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.api.idp; + +public interface EaafAuthProcessDataConstants { + + public static final String GENERIC_PREFIX = "generic_"; + + public static final String VALUE_ISSUEINSTANT = "direct_issueInstant"; + + public static final String FLAG_IS_AUTHENTICATED = "direct_flagIsAuth"; + public static final String FLAG_IS_FOREIGNER = "direct_flagIsForeigner"; + public static final String FLAG_USE_MANDATE = "direct_flagUseMandate"; + public static final String FLAG_IS_ORGANWALTER = "direct_flagOrganwalter"; + public static final String FLAG_IS_NEW_EID_PROCESS = "direct_flagIsNewEID"; + + @Deprecated + public static final String VALUE_IDENTITYLINK = "direct_idl"; + public static final String VALUE_QAALEVEL = "direct_qaaLevel"; + @Deprecated + public static final String VALUE_MISMANDATE = "direct_MIS_Mandate"; + + +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IAction.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IAction.java index a40394b3..50a76007 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IAction.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IAction.java @@ -1,67 +1,44 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.api.idp; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.core.api.idp.slo.SLOInformationInterface; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.api.idp.slo.SloInformationInterface; +import at.gv.egiz.eaaf.core.exceptions.EaafException; /** - * Basic interface of a specific operation that is requested by an authentication protocol implementation - * + * Basic interface of a specific operation that is requested by an authentication protocol + * implementation. + * * @author tlenz * */ public interface IAction { - public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) - throws EAAFException; - public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp); - - public String getDefaultActionName(); + public SloInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, + HttpServletResponse httpResp, IAuthData authData) throws EaafException; + + public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, + HttpServletResponse httpResp); + + public String getDefaultActionName(); } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IAttributeBuilder.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IAttributeBuilder.java index 902aabbe..d3736a17 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IAttributeBuilder.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IAttributeBuilder.java @@ -1,56 +1,31 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.api.idp; import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; public interface IAttributeBuilder { - public String getName(); - - public ATT build(final ISPConfiguration oaParam, final IAuthData authData, - final IAttributeGenerator g) throws AttributeBuilderException; - - public ATT buildEmpty(final IAttributeGenerator g); + public String getName(); + + public ATT build(final IspConfiguration oaParam, final IAuthData authData, + final IAttributeGenerator g) throws AttributeBuilderException; + + public ATT buildEmpty(final IAttributeGenerator g); } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IAttributeGenerator.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IAttributeGenerator.java index 3591e313..0f50bada 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IAttributeGenerator.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IAttributeGenerator.java @@ -1,63 +1,41 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.api.idp; public interface IAttributeGenerator { - /** - * - * @param friendlyName FriendlyName - * @param name Name - * @param value value - * @return - */ - public abstract ATT buildStringAttribute(final String friendlyName, final String name, final String value); - - public abstract ATT buildIntegerAttribute(final String friendlyName, final String name, final int value); - - public abstract ATT buildLongAttribute(final String friendlyName, final String name, final long value); - - public abstract ATT buildEmptyAttribute(final String friendlyName, final String name); + /** + * Protocol attribute generator. + * + * @param friendlyName FriendlyName + * @param name Name + * @param value value + * @return + */ + public abstract ATT buildStringAttribute(final String friendlyName, final String name, + final String value); + + public abstract ATT buildIntegerAttribute(final String friendlyName, final String name, + final int value); + + public abstract ATT buildLongAttribute(final String friendlyName, final String name, + final long value); + + public abstract ATT buildEmptyAttribute(final String friendlyName, final String name); } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IAuthData.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IAuthData.java index e9d86efa..68106549 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IAuthData.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IAuthData.java @@ -1,251 +1,227 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/** - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.api.idp; import java.util.Date; import java.util.List; - import at.gv.egiz.eaaf.core.api.idp.auth.data.IIdentityLink; import at.gv.egiz.eaaf.core.impl.data.Pair; /** + * Service-Provider specific authentication-data. + * * @author tlenz * */ public interface IAuthData { - /** - * BaseId transfer policy - * - * @return true if baseID transfer to service provider is allowed, otherwise false - */ - boolean isBaseIDTransferRestrication(); - - /** - * Identifier of the IDP that authenicates the user - * - * @return - */ - String getAuthenticationIssuer(); - - /** - * Timestamp of the authentication process - * - * @return - */ - Date getAuthenticationIssueInstant(); - - /** - * Get string formated timestamp of the authentication process - * - * @return - */ - String getAuthenticationIssueInstantString(); - - - /** - * Familyname of the user - * - * @return - */ - String getFamilyName(); - - /** - * Givenname of the user - * - * @return - */ - String getGivenName(); - - /** - * Date of birth of the user - * - * @return date of birth or null no data of birth is available - */ - Date getDateOfBirth(); - - /** - * String formated date of birth of the user with pattern yyyy-MM-dd - * - * - * @return date of birth or '2999-12-31' if no data of birth is available - */ - String getFormatedDateOfBirth(); - - /** - * Get the encrypted SourceId (vSZ) from new E-ID scheme - * - * @return - */ - String getEncryptedSourceId(); - - /** - * Get the type identifier of encrypted SourceId - * - * @return - */ - String getEncryptedSourceIdType(); - - /** - * Return LoA for this user authentication - * - * @return eIDAS LoA URI - */ - public String getEIDASQAALevel(); - - - /** - * Indicates that the user is a foreigner - * - * @return true if the user is foreigner, otherwise false - */ - boolean isForeigner(); - - /** - * Code of the citizen country of the authenticated user - * - * @return - */ - String getCiticenCountryCode(); - - - /** - * Indicate that the authentication was done by using an active single sign-on session - * - * @return true if it an SSO session was used, otherwise false - */ - boolean isSsoSession(); - - /** - * Date, up to which the SSO that was used for authentication is valid to - * - * @return - */ - Date getSsoSessionValidTo(); - - - /** - * SessionIndex, if it was an reauthentication on a service provider by using the same SSO session - * - * @return - */ - String getSessionIndex(); - - /** - * SAML2 NameID for the user - * - * @return - */ - String getNameID(); - - /** - * Format of the SAML2 NameID - * - * @return - */ - String getNameIDFormat(); - - - /** - * Get generic information for this authenticated user - * - * @param key Identifier for the generic data - * @param clazz Type of the generic data - * @return return the generic data of specific type, otherwise null - */ - public T getGenericData(String key, final Class clazz); - - - /** - * Get bPK of the user - * - * @return - */ - @Deprecated - String getBPK(); - - /** - * Get sector for user's bPK - * - * - * @return Sector identifier with prefix - */ - @Deprecated - String getBPKType(); - - - /** - * Get List of bPK/bPKType tuples for this service provider - * @return List of Pairs - */ - @Deprecated - List> getAdditionalbPKs(); - - /** - * Get baseId of this user - * - * @return - */ - @Deprecated - String getIdentificationValue(); - - /** - * Get type identifier of the baseId - * By default, this type is urn:publicid:gv.at:baseid - * - * @return - */ - @Deprecated - String getIdentificationType(); - - - /** - * Get the identityLink for the authenticated user - * - * @return IDL, or NULL if no IDL is available - */ - @Deprecated - IIdentityLink getIdentityLink(); + /** + * BaseId transfer policy. + * + * @return true if baseID transfer to service provider is allowed, otherwise false + */ + boolean isBaseIdTransferRestrication(); + + /** + * Identifier of the IDP that authenicates the user. + * + * @return + */ + String getAuthenticationIssuer(); + + /** + * Timestamp of the authentication process. + * + * @return + */ + Date getAuthenticationIssueInstant(); + + /** + * Get string formated timestamp of the authentication process. + * + * @return + */ + String getAuthenticationIssueInstantString(); + + + /** + * Familyname of the user. + * + * @return + */ + String getFamilyName(); + + /** + * Givenname of the user. + * + * @return + */ + String getGivenName(); + + /** + * Date of birth of the user. + * + * @return date of birth or null no data of birth is available + */ + Date getDateOfBirth(); + + /** + * String formated date of birth of the user with pattern yyyy-MM-dd. + * + * + * @return date of birth or '2999-12-31' if no data of birth is available + */ + String getFormatedDateOfBirth(); + + /** + * Get the encrypted SourceId (vSZ) from new E-ID scheme. + * + * @return + */ + String getEncryptedSourceId(); + + /** + * Get the type identifier of encrypted SourceId. + * + * @return + */ + String getEncryptedSourceIdType(); + + /** + * Return LoA for this user authentication. + * + * @return eIDAS LoA URI + */ + public String getEidasQaaLevel(); + + + /** + * Indicates that the user is a foreigner. + * + * @return true if the user is foreigner, otherwise false + */ + boolean isForeigner(); + + /** + * Code of the citizen country of the authenticated user. + * + * @return + */ + String getCiticenCountryCode(); + + + /** + * Indicate that the authentication was done by using an active single sign-on session. + * + * @return true if it an SSO session was used, otherwise false + */ + boolean isSsoSession(); + + /** + * Date, up to which the SSO that was used for authentication is valid to. + * + * @return + */ + Date getSsoSessionValidTo(); + + + /** + * SessionIndex, if it was an reauthentication on a service provider by using the same SSO session. + * + * @return + */ + String getSessionIndex(); + + /** + * SAML2 NameID for the user. + * + * @return + */ + String getNameID(); + + /** + * Format of the SAML2 NameID. + * + * @return + */ + String getNameIdFormat(); + + + /** + * Get generic information for this authenticated user. + * + * @param key Identifier for the generic data + * @param clazz Type of the generic data + * @return return the generic data of specific type, otherwise null + */ + public T getGenericData(String key, final Class clazz); + + + /** + * Get bPK of the user. + * + * @return + */ + @Deprecated + String getBpk(); + + /** + * Get sector for user's bPK. + * + * + * @return Sector identifier with prefix + */ + @Deprecated + String getBpkType(); + + + /** + * Get List of bPK/bPKType tuples for this service provider. + * + * @return List of Pairs bPK/bPKType + */ + @Deprecated + List> getAdditionalbPKs(); + + /** + * Get baseId of this user. + * + * @return + */ + @Deprecated + String getIdentificationValue(); + + /** + * Get type identifier of the baseId By default, this type is urn:publicid:gv.at:baseid. + * + * @return + */ + @Deprecated + String getIdentificationType(); + + + /** + * Get the identityLink for the authenticated user. + * + * @return IDL, or NULL if no IDL is available + */ + @Deprecated + IIdentityLink getIdentityLink(); } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IAuthenticationDataBuilder.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IAuthenticationDataBuilder.java index 2e67f2a8..519c4f5e 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IAuthenticationDataBuilder.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IAuthenticationDataBuilder.java @@ -1,38 +1,31 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.api.idp; import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.core.exceptions.EAAFAuthenticationException; +import at.gv.egiz.eaaf.core.exceptions.EaafAuthenticationException; public interface IAuthenticationDataBuilder { - IAuthData buildAuthenticationData(IRequest pendingReq) throws EAAFAuthenticationException; + IAuthData buildAuthenticationData(IRequest pendingReq) throws EaafAuthenticationException; + + - - } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IConfiguration.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IConfiguration.java index 3ed505ef..e41f099b 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IConfiguration.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IConfiguration.java @@ -1,78 +1,73 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.api.idp; import java.net.URI; public interface IConfiguration { - - /** - * Get a configuration value from file based configuration - * - * @param key configuration key - * @return configuration value or null if it is not found - */ - public String getBasicConfiguration(final String key); - - - /** - * Get a configuration value from file based configuration - * - * @param key configuration key - * @param defaultValue Default value if no value with this key is found - * @return configuration value - */ - public String getBasicConfiguration(final String key, final String defaultValue); - - - /** - * Get a configuration value from file based configuration - * - * @param key configuration key - * @return configuration value as {@link Boolean.parseBoolean(value)} or null if key does not exist - */ - public Boolean getBasicConfigurationBoolean(final String key); - - /** - * Get a configuration value from file based configuration - * - * @param key configuration key - * @param defaultValue Default value if no value with this key is found - * @return configuration value as {@link Boolean.parseBoolean(value)} or defaultValue if key does not exist - */ - public boolean getBasicConfigurationBoolean(final String key, final boolean defaultValue); - - - /** - * Get the root directory of the configuration folder - * - * @return - */ - public URI getConfigurationRootDirectory(); - - + + /** + * Get a configuration value from file based configuration. + * + * @param key configuration key + * @return configuration value or null if it is not found + */ + public String getBasicConfiguration(final String key); + + + /** + * Get a configuration value from file based configuration. + * + * @param key configuration key + * @param defaultValue Default value if no value with this key is found + * @return configuration value + */ + public String getBasicConfiguration(final String key, final String defaultValue); + + + /** + * Get a configuration value from file based configuration. + * + * @param key configuration key + * @return configuration value as {@link Boolean} or false if key + * does not exist + */ + public boolean getBasicConfigurationBoolean(final String key); + + /** + * Get a configuration value from file based configuration. + * + * @param key configuration key + * @param defaultValue Default value if no value with this key is found + * @return configuration value as {@link Boolean} or defaultValue + * if key does not exist + */ + public boolean getBasicConfigurationBoolean(final String key, final boolean defaultValue); + + + /** + * Get the root directory of the configuration folder. + * + * @return + */ + public URI getConfigurationRootDirectory(); + + } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IConfigurationWithSP.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IConfigurationWithSP.java index ef453808..1c065c94 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IConfigurationWithSP.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IConfigurationWithSP.java @@ -2,56 +2,58 @@ package at.gv.egiz.eaaf.core.api.idp; import java.net.URL; import java.util.Map; - import javax.annotation.Nullable; - -import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; public interface IConfigurationWithSP extends IConfiguration { - public static final String CONFIG_PROPS_AUTH_DEFAULT_COUNTRYCODE = "configuration.auth.default.countrycode"; - - - /** - * Get a configuration entry for a specific Service Provider - * - * @param uniqueID Unique identifier of the Service Provider - * @return {@link ISPConfiguration} or null if no SP configuration was found - * @throws EAAFConfigurationException - */ - @Nullable - public ISPConfiguration getServiceProviderConfiguration(final String uniqueID) throws EAAFConfigurationException; - - - /** - * Get a configuration entry for a specific Service Provider that is decorated by a Object - * - * @param spIdentifier EntityID of a Service Provider - * @param decorator Decorator that should be used to decorate the result. - * This decorator has to be implement or extend the {@link ISPConfiguration} interface - * @return T or null if no SP configuration was found - * @throws EAAFConfigurationException - */ - @Nullable - public T getServiceProviderConfiguration(String spIdentifier, final Class decorator) throws EAAFConfigurationException; - - - /** - * Get a set of configuration values from file based configuration that starts with this prefix - *

    - * Important: The configuration values must be of type String! - * - * @param prefix Prefix of the configuration key - * @return Map without prefix, but never null - */ - public Map getBasicConfigurationWithPrefix(final String prefix); - - /** - * Validate a URL if it it is allowed by configuration. - * - * @param authReqUrl URL for validation - * @return URL of the application context if the authReqUrl was valid, otherwise null - */ - public String validateIDPURL(URL authReqUrl) throws EAAFException; + public static final String CONFIG_PROPS_AUTH_DEFAULT_COUNTRYCODE = + "configuration.auth.default.countrycode"; + + + /** + * Get a configuration entry for a specific Service Provider. + * + * @param uniqueID Unique identifier of the Service Provider + * @return {@link IspConfiguration} or null if no SP configuration was found + * @throws EaafConfigurationException In case of a Service-Provider loading error + */ + @Nullable + public IspConfiguration getServiceProviderConfiguration(final String uniqueID) + throws EaafConfigurationException; + + + /** + * Get a configuration entry for a specific Service Provider that is decorated by a Object. + * + * @param spIdentifier EntityID of a Service Provider + * @param decorator Decorator that should be used to decorate the result. This decorator has to be + * implement or extend the {@link IspConfiguration} interface + * @return T or null if no SP configuration was found + * @throws EaafConfigurationException In case of a Service-Provider loading error + */ + @Nullable + public T getServiceProviderConfiguration(String spIdentifier, final Class decorator) + throws EaafConfigurationException; + + + /** + * Get a set of configuration values from file based configuration that starts with this prefix. + *
    + *
    + * Important: The configuration values must be of type String! + * + * @param prefix Prefix of the configuration key + * @return Map String/String without prefix, but never null + */ + public Map getBasicConfigurationWithPrefix(final String prefix); + + /** + * Validate a URL if it it is allowed by configuration. + * + * @param authReqUrl URL for validation + * @return URL of the application context if the authReqUrl was valid, otherwise null + */ + public String validateIdpUrl(URL authReqUrl) throws EaafException; } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IEidAuthData.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IEidAuthData.java index 74c84468..97951d40 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IEidAuthData.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IEidAuthData.java @@ -4,42 +4,42 @@ import at.gv.egiz.eaaf.core.api.data.PVPAttributeDefinitions; public interface IEidAuthData extends IAuthData { - /** - * Get the serialized signing certificate that was used to sign the consent - * - * @return - */ - byte[] getSignerCertificate(); - - - /** - * Get the serialized E-ID token that can be used to validate the Identity-Link - * - * @return - */ - byte[] getEIDToken(); - - - /** - * Get the status of the E-ID - * - * @return {@link PVPAttributeDefinitions.EID_IDENTITY_STATUS_LEVEL_VALUES} - */ - PVPAttributeDefinitions.EID_IDENTITY_STATUS_LEVEL_VALUES getEIDStatus(); - - - /** - * Get the URL of the VDA EndPoint, that was used for authentication - * - * @return - */ - String getVdaEndPointUrl(); - - - /** - * Flag that mandates are used - * - * @return true if mandates are used, otherwise false - */ - boolean isUseMandate(); + /** + * Get the serialized signing certificate that was used to sign the consent. + * + * @return + */ + byte[] getSignerCertificate(); + + + /** + * Get the serialized E-ID token that can be used to validate the Identity-Link. + * + * @return + */ + byte[] getEidToken(); + + + /** + * Get the status of the E-ID. + * + * @return {@link PVPAttributeDefinitions.EID_IDENTITY_STATUS_LEVEL_VALUES} + */ + PVPAttributeDefinitions.EID_IDENTITY_STATUS_LEVEL_VALUES getEidStatus(); + + + /** + * Get the URL of the VDA EndPoint, that was used for authentication. + * + * @return + */ + String getVdaEndPointUrl(); + + + /** + * Flag that mandates are used. + * + * @return true if mandates are used, otherwise false + */ + boolean isUseMandate(); } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IExtendedConfiguration.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IExtendedConfiguration.java index a12a7260..61bce96d 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IExtendedConfiguration.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IExtendedConfiguration.java @@ -5,20 +5,20 @@ import java.util.Properties; public interface IExtendedConfiguration extends IConfigurationWithSP { - /** - * Get the full configuration properties object - * - * @return - */ - @Deprecated - public Properties getFullConfigurationProperties(); - - /** - * Get the path to EAAFCore configuration that is internally used - * - * @return - */ - @Deprecated - public URI getConfigurationFilePath(); - + /** + * Get the full configuration properties object. + * + * @return + */ + @Deprecated + public Properties getFullConfigurationProperties(); + + /** + * Get the path to EAAFCore configuration that is internally used. + * + * @return + */ + @Deprecated + public URI getConfigurationFilePath(); + } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IModulInfo.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IModulInfo.java index 06aed047..3625de86 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IModulInfo.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IModulInfo.java @@ -1,99 +1,73 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.api.idp; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import at.gv.egiz.eaaf.core.api.IRequest; /** - * Basic interface of an authentication protocol implementation on IDP side - * + * Basic interface of an authentication protocol implementation on IDP side. + * * @author tlenz * */ public interface IModulInfo { - - /** - * Name of this IDP authentication module - * - * @return - */ - public String getName(); - - /** - * Authentication protocol identifier for this module - * - * @return - */ - public String getAuthProtocolIdentifier(); - - /** - * Generates a protocol specific error message - * - * - * @param e Exception that contains the error message - * @param request httpRequest object from servlet container - * @param response httpResponse object from servlet container - * @param protocolRequest incoming protocol request - * @return return true if a protocol specific error message was generated, otherwise false - * @throws Throwable - */ - public boolean generateErrorMessage(Throwable e, - HttpServletRequest request, HttpServletResponse response, - IRequest protocolRequest) throws Throwable; - - /** - * additional validation of a incoming authentication request - * - * @param request httpRequest object from servlet container - * @param response httpResponse object from servlet container - * @param pending incoming protocol request - * @return return true if the incoming request is valid, otherwise false - */ - public boolean validate(HttpServletRequest request, - HttpServletResponse response, IRequest pending); + + /** + * Name of this IDP authentication module. + * + * @return + */ + public String getName(); + + /** + * Authentication protocol identifier for this module. + * + * @return + */ + public String getAuthProtocolIdentifier(); + + /** + * Generates a protocol specific error message. + * + * + * @param e Exception that contains the error message + * @param request httpRequest object from servlet container + * @param response httpResponse object from servlet container + * @param protocolRequest incoming protocol request + * @return return true if a protocol specific error message was generated, otherwise + * false + * @throws Throwable In case of an internal error during error message generation + */ + public boolean generateErrorMessage(Throwable e, HttpServletRequest request, + HttpServletResponse response, IRequest protocolRequest) throws Throwable; + + /** + * additional validation of a incoming authentication request. + * + * @param request httpRequest object from servlet container + * @param response httpResponse object from servlet container + * @param pending incoming protocol request + * @return return true if the incoming request is valid, otherwise false + */ + public boolean validate(HttpServletRequest request, HttpServletResponse response, + IRequest pending); } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IPVPAttributeBuilder.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IPVPAttributeBuilder.java deleted file mode 100644 index eab7af9b..00000000 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IPVPAttributeBuilder.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.api.idp; - -import at.gv.egiz.eaaf.core.api.data.PVPAttributeDefinitions; - -public interface IPVPAttributeBuilder extends PVPAttributeDefinitions, IAttributeBuilder { - -} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IPvpAttributeBuilder.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IPvpAttributeBuilder.java new file mode 100644 index 00000000..c1cb38f7 --- /dev/null +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IPvpAttributeBuilder.java @@ -0,0 +1,26 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.api.idp; + +import at.gv.egiz.eaaf.core.api.data.PVPAttributeDefinitions; + +public interface IPvpAttributeBuilder extends PVPAttributeDefinitions, IAttributeBuilder { + +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/ISPConfiguration.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/ISPConfiguration.java deleted file mode 100644 index 9d92b713..00000000 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/ISPConfiguration.java +++ /dev/null @@ -1,168 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.api.idp; - -import java.io.Serializable; -import java.util.List; -import java.util.Map; - -import at.gv.egiz.eaaf.core.api.data.EAAFConstants; - -public interface ISPConfiguration extends Serializable { - - public static final String CONFIG_KEY_RESTRICTIONS_BASEID_INTERNAL = "configuration.restrictions.baseID.idpProcessing"; - public static final String CONFIG_KEY_RESTRICTIONS_BASEID_TRANSMISSION = "configuration.restrictions.baseID.spTransmission"; - - public static final String CONFIG_KEY_RESTRICTIONS_EID_DEMO_MODE = "configuration.restrictions.eIDTestMode"; - - /** - * Get the full key/value configuration for this Service Provider - * - * @return an unmodifiable map of key/value pairs - */ - public Map getFullConfiguration(); - - /** - * Get a configuration value from Service Provider key/value configuration - * - * @param key The key identifier of a configuration value - * @return The configuration value {String} or null if the key does not exist - */ - public String getConfigurationValue(String key); - - /** - * Get a configuration value from Service Provider key/value configuration - * - * @param key The key identifier of a configuration value - * @param defaultValue Default value if key does not exist - * @return The configuration value {String} or defaultValue if the key does not exist - */ - public String getConfigurationValue(String key, String defaultValue); - - /** - * Get a boolean configuration value from Service Provider key/value configuration - * - * @param key The key identifier of a configuration value - * @return true / false, or null if the key does not exist - */ - public Boolean isConfigurationValue(String key); - - - /** - * Get a boolean configuration value from Service Provider key/value configuration - * - * @param key The key identifier of a configuration value - * @param defaultValue Default value if key does not exist - * @return true / false, or defaultValue if the key does not exist - */ - public boolean isConfigurationValue(String key, boolean defaultValue); - - /** - * Check if a configuration key is available in this Service Provider configuration - * - * @param key The key identifier of a configuration value - * @return true if the configuration key exists, otherwise false - */ - boolean containsConfigurationKey(String key); - - /** - * Return the unique identifier of this Service Provider - * - * @return - */ - public String getUniqueIdentifier(); - - /** - * Return the unique identifier of this Service Provider - * - * @return - */ - public String getFriendlyName(); - - /** - * Indicates if this service provider has private area restrictions that disallow baseId processing in general - * * - * @return true if there is a restriction, otherwise false - */ - public boolean hasBaseIdInternalProcessingRestriction(); - - - /** - * Indicates if this service provider has private area restrictions that disallow baseId transfer to SP - * - * @return true if there is a restriction, otherwise false - */ - public boolean hasBaseIdTransferRestriction(); - - /** - * Get the {@link List} of identifier's that indicates no baseID processing restriction exists.
    - * This list can be configured by key: "configuration.restrictions.baseID.idpProcessing" - * - * @return - */ - public List getTargetsWithNoBaseIdInternalProcessingRestriction(); - - /** - * Get the {@link List} of identifier's that indicates no baseID transfer restriction exists.
    - * This list can be configured by key: "configuration.restrictions.baseID.spTransmission" - * - * @return - */ - public List getTargetsWithNoBaseIdTransferRestriction(); - - /** - * Get the List eIDAS LoA that are required by this service provider - * - * {@link EAAFConstants.EIDAS_LOA_LOW} - * {@link EAAFConstants.EIDAS_LOA_SUBSTANTIAL} - * {@link EAAFConstants.EIDAS_LOA_HIGH} - * or any other non-notified LoA scheme - * - * @return return List of eIDAS LoAs - */ - public List getRequiredLoA(); - - /** - * Get required matching mode for LoAs - * {@link EIDAS_LOA_MATCHING_MINIMUM} - * {@link EIDAS_LOA_MATCHING_EXACT} - * - * @return - */ - public String getLoAMatchingMode(); - - - /** - * Get the full area-identifier for this service provider to calculate the - * area-specific unique person identifier (bPK, wbPK, eIDAS unique identifier, ...). - * This identifier always contains the full prefix - * - * @return area identifier with prefix - */ - public String getAreaSpecificTargetIdentifier(); - -} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IspConfiguration.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IspConfiguration.java new file mode 100644 index 00000000..37ca4779 --- /dev/null +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/IspConfiguration.java @@ -0,0 +1,163 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.api.idp; + +import java.io.Serializable; +import java.util.List; +import java.util.Map; +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; + +public interface IspConfiguration extends Serializable { + + public static final String CONFIG_KEY_RESTRICTIONS_BASEID_INTERNAL = + "configuration.restrictions.baseID.idpProcessing"; + public static final String CONFIG_KEY_RESTRICTIONS_BASEID_TRANSMISSION = + "configuration.restrictions.baseID.spTransmission"; + + public static final String CONFIG_KEY_RESTRICTIONS_EID_DEMO_MODE = + "configuration.restrictions.eIDTestMode"; + + /** + * Get the full key/value configuration for this Service Provider. + * + * @return an unmodifiable map of key/value pairs + */ + public Map getFullConfiguration(); + + /** + * Get a configuration value from Service Provider key/value configuration. + * + * @param key The key identifier of a configuration value + * @return The configuration value {String} or null if the key does not exist + */ + public String getConfigurationValue(String key); + + /** + * Get a configuration value from Service Provider key/value configuration. + * + * @param key The key identifier of a configuration value + * @param defaultValue Default value if key does not exist + * @return The configuration value {String} or defaultValue if the key does not exist + */ + public String getConfigurationValue(String key, String defaultValue); + + /** + * Get a boolean configuration value from Service Provider key/value configuration. + * + * @param key The key identifier of a configuration value + * @return true / false, or false if the key does not exist + */ + public boolean isConfigurationValue(String key); + + + /** + * Get a boolean configuration value from Service Provider key/value configuration. + * + * @param key The key identifier of a configuration value + * @param defaultValue Default value if key does not exist + * @return true / false, or defaultValue if the key does not exist + */ + public boolean isConfigurationValue(String key, boolean defaultValue); + + /** + * Check if a configuration key is available in this Service Provider configuration. + * + * @param key The key identifier of a configuration value + * @return true if the configuration key exists, otherwise false + */ + boolean containsConfigurationKey(String key); + + /** + * Return the unique identifier of this Service Provider. + * + * @return + */ + public String getUniqueIdentifier(); + + /** + * Return the unique identifier of this Service Provider. + * + * @return + */ + public String getFriendlyName(); + + /** + * Indicates if this service provider has private area restrictions that disallow baseId. + * processing in general * + * + * @return true if there is a restriction, otherwise false + */ + public boolean hasBaseIdInternalProcessingRestriction(); + + + /** + * Indicates if this service provider has private area restrictions that disallow baseId transfer. + * to SP + * + * @return true if there is a restriction, otherwise false + */ + public boolean hasBaseIdTransferRestriction(); + + /** + * Get the {@link List} of identifier's that indicates no baseID processing restriction + * exists.
    + * This list can be configured by key: "configuration.restrictions.baseID.idpProcessing" + * + * @return + */ + public List getTargetsWithNoBaseIdInternalProcessingRestriction(); + + /** + * Get the {@link List} of identifier's that indicates no baseID transfer restriction exists.
    + * This list can be configured by key: "configuration.restrictions.baseID.spTransmission" + * + * @return + */ + public List getTargetsWithNoBaseIdTransferRestriction(); + + /** + * Get the List eIDAS LoA that are required by this service provider. + * + * {@link EAAFConstants.EIDAS_LOA_LOW} {@link EAAFConstants.EIDAS_LOA_SUBSTANTIAL} + * {@link EAAFConstants.EIDAS_LOA_HIGH} or any other non-notified LoA scheme + * + * @return return List of eIDAS LoAs + */ + public List getRequiredLoA(); + + /** + * Get required matching mode for LoAs {@link EIDAS_LOA_MATCHING_MINIMUM}. + * {@link EIDAS_LOA_MATCHING_EXACT} + * + * @return + */ + public String getLoAMatchingMode(); + + + /** + * Get the full area-identifier for this service provider to calculate the area-specific unique + * person identifier (bPK, wbPK, eIDAS unique identifier, ...). This identifier always contains + * the full prefix + * + * @return area identifier with prefix + */ + public String getAreaSpecificTargetIdentifier(); + +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/IAuthenticationManager.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/IAuthenticationManager.java index 4381211d..1f95bd57 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/IAuthenticationManager.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/IAuthenticationManager.java @@ -1,94 +1,92 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.api.idp.auth; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.core.api.idp.slo.ISLOInformationContainer; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.api.idp.slo.ISloInformationContainer; +import at.gv.egiz.eaaf.core.exceptions.EaafException; public interface IAuthenticationManager { - - public static int EVENT_AUTHENTICATION_PROCESS_FOR_SP = 4003; - public static int EVENT_AUTHENTICATION_PROCESS_STARTED = 4000; - public static int EVENT_AUTHENTICATION_PROCESS_FINISHED = 4001; - public static int EVENT_AUTHENTICATION_PROCESS_ERROR = 4002; - - - /** - * Add a request parameter to whitelist. All parameters that are part of the white list are added into {@link ExecutionContext} - * - * @param httpReqParam http parameter name, but never null - */ - void addParameterNameToWhiteList(String httpReqParam); - /** - * Add a request header to whitelist. All parameters that are part of the white list are added into {@link ExecutionContext} - * - * @param httpReqParam http header name, but never null - */ - void addHeaderNameToWhiteList(String httpReqParam); - + public static int EVENT_AUTHENTICATION_PROCESS_FOR_SP = 4003; + public static int EVENT_AUTHENTICATION_PROCESS_STARTED = 4000; + public static int EVENT_AUTHENTICATION_PROCESS_FINISHED = 4001; + public static int EVENT_AUTHENTICATION_PROCESS_ERROR = 4002; + + + /** + * Add a request parameter to whitelist. All parameters that are part of the white list are added + * into {@link ExecutionContext} + * + * @param httpReqParam http parameter name, but never null + */ + void addParameterNameToWhiteList(String httpReqParam); + + /** + * Add a request header to whitelist. All parameters that are part of the white list are added + * into {@link ExecutionContext} + * + * @param httpReqParam http header name, but never null + */ + void addHeaderNameToWhiteList(String httpReqParam); + + + /** + * Starts an authentication process for a specific pending request. + * + * @param httpReq http servlet request + * @param httpResp http servlet response + * @param pendingReq Pending request for that an authentication is required + * @return true if the pending request is already authenticated, otherwise false + * @throws EaafException In case of an authentication error + */ + boolean doAuthentication(HttpServletRequest httpReq, HttpServletResponse httpResp, + IRequest pendingReq) throws EaafException; + + /** + * Close an active authenticated session on IDP side. + * + * @param request http servlet request + * @param response http servlet response + * @param pendingReq ReqPending request for that an authentication session should be closed + */ + void performOnlyIdpLogOut(HttpServletRequest request, HttpServletResponse response, + IRequest pendingReq); + + + /** + * Close an active authenticated session on IDP side and get a list authenticated service + * providers. + * + * @param httpReq http servlet request + * @param httpResp http servlet response + * @param pendingReq ReqPending request for that an authentication session should be closed + * @param internalSsoId internal SSO session identifier + * @return A container that contains all active SP sessions + * @throws EaafException In case of an internal SLO error + */ + ISloInformationContainer performSingleLogOut(HttpServletRequest httpReq, + HttpServletResponse httpResp, IRequest pendingReq, String internalSsoId) throws EaafException; - /** - * Starts an authentication process for a specific pending request - * - * @param httpReq http servlet request - * @param httpResp http servlet response - * @param pendingReq Pending request for that an authentication is required - * @return true if the pending request is already authenticated, otherwise false - * @throws EAAFException - */ - boolean doAuthentication(HttpServletRequest httpReq, HttpServletResponse httpResp, - IRequest pendingReq) throws EAAFException; - - /** - * Close an active authenticated session on IDP side - * - * @param request http servlet request - * @param response http servlet response - * @param pendingReq ReqPending request for that an authentication session should be closed - */ - void performOnlyIDPLogOut(HttpServletRequest request, HttpServletResponse response, IRequest pendingReq); - - - /** - * Close an active authenticated session on IDP side and get a list authenticated service providers - * - * @param request http servlet request - * @param response http servlet response - * @param pendingReq ReqPending request for that an authentication session should be closed - * @param internalSSOId internal SSO session identifier - * @return A container that contains all active SP sessions - * @throws EAAFException - */ - ISLOInformationContainer performSingleLogOut(HttpServletRequest httpReq, HttpServletResponse httpResp, IRequest pendingReq, String internalSSOId) throws EAAFException; - -} \ No newline at end of file +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/ISSOManager.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/ISSOManager.java deleted file mode 100644 index 5481fd52..00000000 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/ISSOManager.java +++ /dev/null @@ -1,130 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.api.idp.auth; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.core.api.idp.slo.SLOInformationInterface; -import at.gv.egiz.eaaf.core.exceptions.EAAFSSOException; - -public interface ISSOManager { - - //TODO - public static int EVENT_SSO_SESSION_INVALID = -1; - public static int EVENT_SSO_SESSION_VALID = -1; - - - public static final String PROCESS_ENGINE_SSO_CONSENTS_EVALUATION = "ssoconsentsevaluation"; - public static final String AUTH_DATA_SSO_SESSIONID = "eaaf_authdata_sso_sessionId"; - - - /** - * Check if there is an active and valid SSO session for the current pending request. - *
    - * If there is an active SSO session, the pending request will be populated with eID information from SSO session - * - * @param pendingReq Current incoming pending request - * @param httpReq http Servlet request - * @param httpResp http Servlet response - * @return true if there is a valid SSO session, otherwise false - * @throws EAAFSSOException - */ - public boolean checkAndValidateSSOSession(IRequest pendingReq, HttpServletRequest httpReq, HttpServletResponse httpResp) throws EAAFSSOException; - - /** - * Populate service provider specific SSO settings - * - * Check if Single Sign-On is allowed for the current pending request and the requested service provider - * Set IRequest.needSingleSignOnFunctionality() to true if SSO is allowed - * - * @param pendingReq Current incoming pending request - * @param httpReq http Servlet request - */ - public void isSSOAllowedForSP(IRequest pendingReq, HttpServletRequest httpReq); - - - /** - * Populate the current pending request with eID information from an existing SSO session - * - * @param pendingReq pending request that should be populated by SSO session - * @throws EAAFSSOException if pending request contains no SSO information or population failed - */ - public void populatePendingRequestWithSSOInformation(IRequest pendingReq) throws EAAFSSOException; - - - /** - * Destroy an active SSO session on IDP site only - * - * @param httpReq http servlet request - * @param httpResp http servlet response - * @param pendingReq - * @return true if a SSO session was closed successfully, otherwise false - * @throws EAAFSSOException in case of an internal processing error - */ - public boolean destroySSOSessionOnIDPOnly(HttpServletRequest httpReq, HttpServletResponse httpResp, IRequest pendingReq) throws EAAFSSOException; - - - - /** - * Create a new SSO session-cookie for a specific pendingRequest and add it into http response - * - * @param req http Request - * @param resp http Response - * @param pendingReq Current open PendingRequest - * @return new created SSO identifier - * @throws EAAFSSOException - */ - public String createNewSSOSessionCookie(HttpServletRequest req, HttpServletResponse resp, IRequest pendingReq) throws EAAFSSOException; - - - /** - * Create a new SSO session in database - * - * @param pendingReq - * @param newSSOSessionId - * @throws EAAFSSOException - */ - public void createNewSSOSession(IRequest pendingReq, String newSSOSessionId) throws EAAFSSOException; - - - /** - * Updateing an existing SSO session in database - * - * @param pendingReq - * @param newSSOSessionId - * @param sloInformation - * @throws EAAFSSOException - */ - public void updateSSOSession(IRequest pendingReq, String newSSOSessionId, SLOInformationInterface sloInformation) throws EAAFSSOException; - - - - - -} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/ISsoManager.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/ISsoManager.java new file mode 100644 index 00000000..a0734684 --- /dev/null +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/ISsoManager.java @@ -0,0 +1,127 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.api.idp.auth; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.idp.slo.SloInformationInterface; +import at.gv.egiz.eaaf.core.exceptions.EaafSsoException; + +public interface ISsoManager { + + // TODO + public static int EVENT_SSO_SESSION_INVALID = -1; + public static int EVENT_SSO_SESSION_VALID = -1; + + + public static final String PROCESS_ENGINE_SSO_CONSENTS_EVALUATION = "ssoconsentsevaluation"; + public static final String AUTH_DATA_SSO_SESSIONID = "eaaf_authdata_sso_sessionId"; + + + /** + * Check if there is an active and valid SSO session for the current pending request.
    + * If there is an active SSO session, the pending request will be populated with eID information + * from SSO session + * + * @param pendingReq Current incoming pending request + * @param httpReq http Servlet request + * @param httpResp http Servlet response + * @return true if there is a valid SSO session, otherwise false + * @throws EaafSsoException In case of an internal error + */ + public boolean checkAndValidateSsoSession(IRequest pendingReq, HttpServletRequest httpReq, + HttpServletResponse httpResp) throws EaafSsoException; + + /** + * Populate service provider specific SSO settings. + * + *

    + * Check if Single Sign-On is allowed for the current pending request and the requested service + * provider Set IRequest.needSingleSignOnFunctionality() to true if SSO is allowed + *

    + * + * @param pendingReq Current incoming pending request + * @param httpReq http Servlet request + */ + public void isSsoAllowedForSp(IRequest pendingReq, HttpServletRequest httpReq); + + + /** + * Populate the current pending request with eID information from an existing SSO session. + * + * @param pendingReq pending request that should be populated by SSO session + * @throws EaafSsoException if pending request contains no SSO information or population failed + */ + public void populatePendingRequestWithSsoInformation(IRequest pendingReq) throws EaafSsoException; + + + /** + * Destroy an active SSO session on IDP site only. + * + * @param httpReq http servlet request + * @param httpResp http servlet response + * @param pendingReq current pending request + * @return true if a SSO session was closed successfully, otherwise false + * @throws EaafSsoException in case of an internal processing error + */ + public boolean destroySsoSessionOnIdpOnly(HttpServletRequest httpReq, + HttpServletResponse httpResp, IRequest pendingReq) throws EaafSsoException; + + + + /** + * Create a new SSO session-cookie for a specific pendingRequest and add it into http response. + * + * @param req http Request + * @param resp http Response + * @param pendingReq Current open PendingRequest + * @return new created SSO identifier + * @throws EaafSsoException In case of an internal error + */ + public String createNewSsoSessionCookie(HttpServletRequest req, HttpServletResponse resp, + IRequest pendingReq) throws EaafSsoException; + + + /** + * Create a new SSO session in database. + * + * @param pendingReq current pending request + * @param newSsoSessionId new SSO sessionId + * @throws EaafSsoException In case of an internal error + */ + public void createNewSsoSession(IRequest pendingReq, String newSsoSessionId) + throws EaafSsoException; + + + /** + * Updateing an existing SSO session in database. + * + * @param pendingReq current pending request + * @param newSsoSessionId new SSO session Id + * @param sloInformation SLO information container + * @throws EaafSsoException In case of an internal error + */ + public void updateSsoSession(IRequest pendingReq, String newSsoSessionId, + SloInformationInterface sloInformation) throws EaafSsoException; + + + +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/data/IAuthProcessDataContainer.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/data/IAuthProcessDataContainer.java index 17ec6445..77fc025c 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/data/IAuthProcessDataContainer.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/data/IAuthProcessDataContainer.java @@ -1,24 +1,20 @@ /******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ /******************************************************************************* *******************************************************************************/ @@ -29,157 +25,158 @@ package at.gv.egiz.eaaf.core.api.idp.auth.data; import java.util.Date; import java.util.Map; -import at.gv.egiz.eaaf.core.exceptions.EAAFStorageException; +import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; public interface IAuthProcessDataContainer { - /** - * Returns the issuing time of the AUTH-Block SAML assertion. - * - * @return The issuing time of the AUTH-Block SAML assertion. - */ - String getIssueInstant(); - - /** - * Sets the issuing time of the AUTH-Block SAML assertion. - * - * @param issueInstant - * The issueInstant to set. - */ - void setIssueInstant(String issueInstant); - - /** - * Indicate if the authentication process is finished - * - * @return - */ - boolean isAuthenticated(); - - /** - * Mark the authentication as authenticated, which means that the authenication process is completed - * - * @param authenticated - */ - void setAuthenticated(boolean authenticated); - - /** - * Returns the identityLink. - * - * @return IdentityLink - */ - @Deprecated - IIdentityLink getIdentityLink(); - - /** - * Sets the identityLink. - * - * @param identityLink - * The identityLink to set - */ - @Deprecated - void setIdentityLink(IIdentityLink identityLink); - - - /** - * Flag marks the authentication process as new E-ID process - * - * @return true if E-ID process, otherwise false - */ - boolean isEIDProcess(); - - - /** - * Set the flag to make the process as new E-ID process - * - * @param value true if new E-ID process, otherwise false - */ - void setEIDProcess(boolean value); - - /** - * Indicate that mandates was used in this auth. process - * - * @return - */ - boolean isMandateUsed(); - - /** - * Mark that mandates was used in this auth. process - * - * @param useMandates - */ - void setUseMandates(boolean useMandates); - - /** - * Indicate that the auth. process was performed by a foreigner - * - * @return - */ - boolean isForeigner(); - - /** - * Mark that the auth. process was done by a foreigner - * - * @param isForeigner - */ - void setForeigner(boolean isForeigner); - - /** - * Indicate that the auth. process was performed by an official representatives - * - * @return is official representatives - */ - boolean isOW(); - - /** - * Mark that the auth. process was done by an official representatives - * - */ - void setOW(boolean isOW); - - /** - * eIDAS QAA level - * - * @return the qAALevel - */ - String getQAALevel(); - - /** - * set QAA level in eIDAS form - * - * @param qAALevel the qAALevel to set - */ - void setQAALevel(String qAALevel); - - /** - * @return the sessionCreated - */ - Date getSessionCreated(); - - Map getGenericSessionDataStorage(); - - /** - * Returns a generic session-data object with is stored with a specific identifier - * - * @param key The specific identifier of the session-data object - * @return The session-data object or null if no data is found with this key - */ - Object getGenericDataFromSession(String key); - - /** - * Returns a generic session-data object with is stored with a specific identifier - * - * @param key The specific identifier of the session-data object - * @param clazz The class type which is stored with this key - * @return The session-data object or null if no data is found with this key - */ - T getGenericDataFromSession(String key, Class clazz); - - /** - * Store a generic data-object to session with a specific identifier - * - * @param key Identifier for this data-object - * @param object Generic data-object which should be stored. This data-object had to be implement the 'java.io.Serializable' interface - * @throws EAAFStorageException Error message if the data-object can not stored to generic session-data storage - */ - void setGenericDataToSession(String key, Object object) throws EAAFStorageException; + /** + * Returns the issuing time of the AUTH-Block SAML assertion. + * + * @return The issuing time of the AUTH-Block SAML assertion. + */ + String getIssueInstant(); + + /** + * Sets the issuing time of the AUTH-Block SAML assertion. + * + * @param issueInstant The issueInstant to set. + */ + void setIssueInstant(String issueInstant); + + /** + * Indicate if the authentication process is finished + * + * @return + */ + boolean isAuthenticated(); + + /** + * Mark the authentication as authenticated, which means that the authenication process is + * completed + * + * @param authenticated + */ + void setAuthenticated(boolean authenticated); + + /** + * Returns the identityLink. + * + * @return IdentityLink + */ + @Deprecated + IIdentityLink getIdentityLink(); + + /** + * Sets the identityLink. + * + * @param identityLink The identityLink to set + */ + @Deprecated + void setIdentityLink(IIdentityLink identityLink); + + + /** + * Flag marks the authentication process as new E-ID process + * + * @return true if E-ID process, otherwise false + */ + boolean isEIDProcess(); + + + /** + * Set the flag to make the process as new E-ID process + * + * @param value true if new E-ID process, otherwise false + */ + void setEIDProcess(boolean value); + + /** + * Indicate that mandates was used in this auth. process + * + * @return + */ + boolean isMandateUsed(); + + /** + * Mark that mandates was used in this auth. process + * + * @param useMandates + */ + void setUseMandates(boolean useMandates); + + /** + * Indicate that the auth. process was performed by a foreigner + * + * @return + */ + boolean isForeigner(); + + /** + * Mark that the auth. process was done by a foreigner + * + * @param isForeigner + */ + void setForeigner(boolean isForeigner); + + /** + * Indicate that the auth. process was performed by an official representatives + * + * @return is official representatives + */ + boolean isOW(); + + /** + * Mark that the auth. process was done by an official representatives + * + */ + void setOW(boolean isOW); + + /** + * eIDAS QAA level + * + * @return the qAALevel + */ + String getQAALevel(); + + /** + * set QAA level in eIDAS form + * + * @param qAALevel the qAALevel to set + */ + void setQAALevel(String qAALevel); + + /** + * @return the sessionCreated + */ + Date getSessionCreated(); + + Map getGenericSessionDataStorage(); + + /** + * Returns a generic session-data object with is stored with a specific identifier + * + * @param key The specific identifier of the session-data object + * @return The session-data object or null if no data is found with this key + */ + Object getGenericDataFromSession(String key); + + /** + * Returns a generic session-data object with is stored with a specific identifier + * + * @param key The specific identifier of the session-data object + * @param clazz The class type which is stored with this key + * @return The session-data object or null if no data is found with this key + */ + T getGenericDataFromSession(String key, Class clazz); + + /** + * Store a generic data-object to session with a specific identifier + * + * @param key Identifier for this data-object + * @param object Generic data-object which should be stored. This data-object had to be implement + * the 'java.io.Serializable' interface + * @throws EaafStorageException Error message if the data-object can not stored to generic + * session-data storage + */ + void setGenericDataToSession(String key, Object object) throws EaafStorageException; } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/data/IIdentityLink.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/data/IIdentityLink.java index df71b30a..b37d41e3 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/data/IIdentityLink.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/data/IIdentityLink.java @@ -1,24 +1,20 @@ /******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ /******************************************************************************* *******************************************************************************/ @@ -39,144 +35,163 @@ import org.w3c.dom.Element; */ public interface IIdentityLink { - /** - * Returns the dateOfBirth. - * @return Calendar - */ - String getDateOfBirth(); - - /** - * Returns the familyName. - * @return String - */ - String getFamilyName(); - - /** - * Returns the givenName. - * @return String - */ - String getGivenName(); - - /** - * Return the name as 'givenName + " " + familyName'
    - * This method should be used any more. Use getFamilyName() and getGivenName() separately. - * - * @return The name. - */ - @Deprecated - String getName(); - - /** - * Returns the identificationValue. - * "identificationValue" is the translation of "Stammzahl". - * @return String - */ - String getIdentificationValue(); - - /** - * Returns the identificationType. - * "identificationType" type of the identificationValue in the IdentityLink. - * @return String - */ - String getIdentificationType(); - - /** - * Sets the dateOfBirth. - * @param dateOfBirth The dateOfBirth to set - */ - void setDateOfBirth(String dateOfBirth); - - /** - * Sets the familyName. - * @param familyName The familyName to set - */ - void setFamilyName(String familyName); - - /** - * Sets the givenName. - * @param givenName The givenName to set - */ - void setGivenName(String givenName); - - /** - * Sets the identificationValue. - * "identificationValue" is the translation of "Stammzahl". - * @param identificationValue The identificationValue to set - */ - void setIdentificationValue(String identificationValue); - - /** - * Sets the Type of the identificationValue. - * @param identificationType The type of identificationValue to set - */ - void setIdentificationType(String identificationType); - - /** - * Returns the samlAssertion. - * @return Element - */ - Element getSamlAssertion(); - - /** - * Returns the samlAssertion. - * @return Element - */ - String getSerializedSamlAssertion(); - - /** - * Sets the samlAssertion and the serializedSamlAssertion. - * @param samlAssertion The samlAssertion to set - */ - void setSamlAssertion(Element samlAssertion) throws TransformerException, IOException; - - /** - * Returns the dsigReferenceTransforms. - * @return Element[] - */ - Element[] getDsigReferenceTransforms(); - - /** - * Sets the dsigReferenceTransforms. - * @param dsigReferenceTransforms The dsigReferenceTransforms to set - */ - void setDsigReferenceTransforms(Element[] dsigReferenceTransforms); - - /** - * Returns the publicKey. - * @return PublicKey[] - */ - PublicKey[] getPublicKey(); - - /** - * Sets the publicKey. - * @param publicKey The publicKey to set - */ - void setPublicKey(PublicKey[] publicKey); - - /** - * Returns the prPerson. - * @return Element - */ - Element getPrPerson(); - - /** - * Sets the prPerson. - * @param prPerson The prPerson to set - */ - void setPrPerson(Element prPerson); - - /** - * Returns the issuing time of the identity link SAML assertion. - * - * @return The issuing time of the identity link SAML assertion. - */ - String getIssueInstant(); - - /** - * Sets the issuing time of the identity link SAML assertion. - * - * @param issueInstant The issueInstant to set. - */ - void setIssueInstant(String issueInstant); - -} \ No newline at end of file + /** + * Returns the dateOfBirth. + * + * @return Calendar + */ + String getDateOfBirth(); + + /** + * Returns the familyName. + * + * @return String + */ + String getFamilyName(); + + /** + * Returns the givenName. + * + * @return String + */ + String getGivenName(); + + /** + * Return the name as 'givenName + " " + familyName'
    + * This method should be used any more. Use getFamilyName() and getGivenName() separately. + * + * @return The name. + */ + @Deprecated + String getName(); + + /** + * Returns the identificationValue. "identificationValue" is the translation of + * "Stammzahl". + * + * @return String + */ + String getIdentificationValue(); + + /** + * Returns the identificationType. "identificationType" type of the + * identificationValue in the IdentityLink. + * + * @return String + */ + String getIdentificationType(); + + /** + * Sets the dateOfBirth. + * + * @param dateOfBirth The dateOfBirth to set + */ + void setDateOfBirth(String dateOfBirth); + + /** + * Sets the familyName. + * + * @param familyName The familyName to set + */ + void setFamilyName(String familyName); + + /** + * Sets the givenName. + * + * @param givenName The givenName to set + */ + void setGivenName(String givenName); + + /** + * Sets the identificationValue. "identificationValue" is the translation of + * "Stammzahl". + * + * @param identificationValue The identificationValue to set + */ + void setIdentificationValue(String identificationValue); + + /** + * Sets the Type of the identificationValue. + * + * @param identificationType The type of identificationValue to set + */ + void setIdentificationType(String identificationType); + + /** + * Returns the samlAssertion. + * + * @return Element + */ + Element getSamlAssertion(); + + /** + * Returns the samlAssertion. + * + * @return Element + */ + String getSerializedSamlAssertion(); + + /** + * Sets the samlAssertion and the serializedSamlAssertion. + * + * @param samlAssertion The samlAssertion to set + */ + void setSamlAssertion(Element samlAssertion) throws TransformerException, IOException; + + /** + * Returns the dsigReferenceTransforms. + * + * @return Element[] + */ + Element[] getDsigReferenceTransforms(); + + /** + * Sets the dsigReferenceTransforms. + * + * @param dsigReferenceTransforms The dsigReferenceTransforms to set + */ + void setDsigReferenceTransforms(Element[] dsigReferenceTransforms); + + /** + * Returns the publicKey. + * + * @return PublicKey[] + */ + PublicKey[] getPublicKey(); + + /** + * Sets the publicKey. + * + * @param publicKey The publicKey to set + */ + void setPublicKey(PublicKey[] publicKey); + + /** + * Returns the prPerson. + * + * @return Element + */ + Element getPrPerson(); + + /** + * Sets the prPerson. + * + * @param prPerson The prPerson to set + */ + void setPrPerson(Element prPerson); + + /** + * Returns the issuing time of the identity link SAML assertion. + * + * @return The issuing time of the identity link SAML assertion. + */ + String getIssueInstant(); + + /** + * Sets the issuing time of the identity link SAML assertion. + * + * @param issueInstant The issueInstant to set. + */ + void setIssueInstant(String issueInstant); + +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/modules/AuthModule.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/modules/AuthModule.java index 7f5eef06..e74bed63 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/modules/AuthModule.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/modules/AuthModule.java @@ -1,29 +1,22 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.api.idp.auth.modules; import at.gv.egiz.eaaf.core.api.IRequest; @@ -34,36 +27,36 @@ import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; */ public interface AuthModule { - /** - * Returns the priority of the module. The priority defines the order of the respective module within the chain of - * discovered modules. Higher priorized modules are asked before lower priorized modules for a process that they can - * handle. - *

    - * Internal default modules are priorized neutral ({@code 0}. Use a higher priority ({@code 1...Integer.MAX_VALUE}) - * in order to have your module(s) priorized or a lower priority ({@code Integer.MIN_VALUE...-1}) in order to put - * your modules behind default modules. - * - * @return the priority of the module. - */ - int getPriority(); + /** + * Returns the priority of the module. The priority defines the order of the respective module + * within the chain of discovered modules. Higher priorized modules are asked before lower + * priorized modules for a process that they can handle. + *

    + * Internal default modules are priorized neutral ({@code 0}. Use a higher priority + * ({@code 1...Integer.MAX_VALUE}) in order to have your module(s) priorized or a lower priority + * ({@code Integer.MIN_VALUE...-1}) in order to put your modules behind default modules. + * + * @return the priority of the module. + */ + int getPriority(); - /** - * Selects a process (description), referenced by its unique id, which is able to perform authentication with the - * given {@link ExecutionContext}. Returns {@code null} if no appropriate process (description) was available within - * this module. - * - * @param context - * an ExecutionContext for a process. - * @param pendingReq the current processed pending request - * @return the process-ID of a process which is able to work with the given ExecutionContext, or {@code null}. - */ - String selectProcess(ExecutionContext context, IRequest pendingReq); + /** + * Selects a process (description), referenced by its unique id, which is able to perform + * authentication with the given {@link ExecutionContext}. Returns {@code null} if no appropriate + * process (description) was available within this module. + * + * @param context an ExecutionContext for a process. + * @param pendingReq the current processed pending request + * @return the process-ID of a process which is able to work with the given ExecutionContext, or + * {@code null}. + */ + String selectProcess(ExecutionContext context, IRequest pendingReq); - /** - * Returns the an Array of {@link ProcessDefinition}s of the processes included in this module. - * - * @return an array of resource uris of the processes included in this module. - */ - String[] getProcessDefinitions(); + /** + * Returns the an Array of {@link ProcessDefinition}s of the processes included in this module. + * + * @return an array of resource uris of the processes included in this module. + */ + String[] getProcessDefinitions(); } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/services/IProtocolAuthenticationService.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/services/IProtocolAuthenticationService.java index de5eb036..14ce0989 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/services/IProtocolAuthenticationService.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/auth/services/IProtocolAuthenticationService.java @@ -1,89 +1,89 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. + */ + package at.gv.egiz.eaaf.core.api.idp.auth.services; import java.io.IOException; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.logging.IStatisticLogger; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; public interface IProtocolAuthenticationService { - public String PARAM_GUI_ERROMSG = "errorMsg"; - public String PARAM_GUI_ERRORCODE = "errorCode"; - public String PARAM_GUI_ERRORCODEPARAMS = "errorParams"; - public String PARAM_GUI_ERRORSTACKTRACE = "stacktrace"; - - - /** - * Initialize an authentication process for this protocol request - * - * @param httpReq HttpServletRequest - * @param httpResp HttpServletResponse - * @param protocolRequest Authentication request which is actually in process - * @throws IOException - * @throws EAAFException - */ - void performAuthentication(HttpServletRequest req, HttpServletResponse resp, IRequest pendingReq) - throws IOException, EAAFException; + public String PARAM_GUI_ERROMSG = "errorMsg"; + public String PARAM_GUI_ERRORCODE = "errorCode"; + public String PARAM_GUI_ERRORCODEPARAMS = "errorParams"; + public String PARAM_GUI_ERRORSTACKTRACE = "stacktrace"; + + + /** + * Initialize an authentication process for this protocol request. + * + * @param httpReq HttpServletRequest + * @param httpResp HttpServletResponse + * @param pendingReq Authentication request which is actually in process + * @throws IOException In case of a communication error + * @throws EaafException In case of an application error + */ + void performAuthentication(HttpServletRequest httpReq, HttpServletResponse httpResp, IRequest pendingReq) + throws IOException, EaafException; - /** - * Finalize the requested protocol operation - * - * @param httpReq HttpServletRequest - * @param httpResp HttpServletResponse - * @param protocolRequest Authentication request which is actually in process - * @throws IOException If response can not be written into {@link HttpServletResponse} - * @throws EAAFException If an internal error occur - */ - void finalizeAuthentication(HttpServletRequest req, HttpServletResponse resp, IRequest pendingReq) throws EAAFException, IOException; + /** + * Finalize the requested protocol operation. + * + * @param httpReq HttpServletRequest + * @param httpResp HttpServletResponse + * @param pendingReq Authentication request which is actually in process + * @throws IOException If response can not be written into {@link HttpServletResponse} + * @throws EaafException If an internal error occur + */ + void finalizeAuthentication(HttpServletRequest httpReq, HttpServletResponse httpResp, IRequest pendingReq) + throws EaafException, IOException; - /** - * @param throwable Exception that should be handled - * @param req Current open http request as {@link HttpServletRequest} - * @param resp Current open http response as {@link HttpServletResponse} - * @param pendingReq Authentication request which is actually in process - * @throws IOException If response can not be written into {@link HttpServletResponse} - * @throws EAAFException If an internal error occur - */ - void buildProtocolSpecificErrorResponse(Throwable throwable, HttpServletRequest req, HttpServletResponse resp, - IRequest pendingReq) throws IOException, EAAFException; + /** + * Build protocol-specific error message. + * + * @param throwable Exception that should be handled + * @param req Current open http request as {@link HttpServletRequest} + * @param resp Current open http response as {@link HttpServletResponse} + * @param pendingReq Authentication request which is actually in process + * @throws IOException If response can not be written into {@link HttpServletResponse} + * @throws EaafException If an internal error occur + */ + void buildProtocolSpecificErrorResponse(Throwable throwable, HttpServletRequest req, + HttpServletResponse resp, IRequest pendingReq) throws IOException, EaafException; - /** - * Handles all exceptions with no pending request. - * Therefore, the error is written to the users browser - * - * @param throwable Exception that should be handled - * @param req Current open http request as {@link HttpServletRequest} - * @param resp Current open http response as {@link HttpServletResponse} - * @param writeExceptionToStatisticLog if true, the exception get logged into {@link IStatisticLogger} - * @throws IOException If response can not be written into {@link HttpServletResponse} - * @throws EAAFException If an internal error occure - */ - void handleErrorNoRedirect(Throwable throwable, HttpServletRequest req, HttpServletResponse resp, boolean writeExceptionToStatisticLog) throws IOException, EAAFException; + /** + * Handles all exceptions with no pending request. Therefore, the error is written to the users + * browser + * + * @param throwable Exception that should be handled + * @param req Current open http request as {@link HttpServletRequest} + * @param resp Current open http response as {@link HttpServletResponse} + * @param writeExceptionToStatisticLog if true, the exception get logged into + * {@link IStatisticLogger} + * @throws IOException If response can not be written into {@link HttpServletResponse} + * @throws EaafException If an internal error occure + */ + void handleErrorNoRedirect(Throwable throwable, HttpServletRequest req, HttpServletResponse resp, + boolean writeExceptionToStatisticLog) throws IOException, EaafException; -} \ No newline at end of file +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/ExecutionContext.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/ExecutionContext.java index 319db027..3c2136aa 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/ExecutionContext.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/process/ExecutionContext.java @@ -1,29 +1,22 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.api.idp.process; import java.io.Serializable; @@ -31,74 +24,73 @@ import java.util.Set; /** * Encapsulates data needed for or provided by task execution. - * + * * @author tknall - * + * */ public interface ExecutionContext extends Serializable { - /** - * Flag that indicates that a Task canceled the current {@link ExecutionContext} - * - * @return true if the process-flow was marked as canceled, otherwise false - */ - boolean isProcessCancelled(); - - /** - * Mark this {@link ExecutionContext} as cancelled - * - * The process-flow engine will stop execution when the task that sets this flag is finished - * - */ - void setCanceleProcessFlag(); - - /** - * Returns the identifier of underlying process instance. - * - * @return The identifier of the process instance. - */ - String getProcessInstanceId(); + /** + * Flag that indicates that a Task canceled the current {@link ExecutionContext}. + * + * @return true if the process-flow was marked as canceled, otherwise false + */ + boolean isProcessCancelled(); + + /** + * Mark this {@link ExecutionContext} as cancelled. + * + *

    + * The process-flow engine will stop execution when the task that sets this flag is finished + *

    + */ + void setCanceleProcessFlag(); + + /** + * Returns the identifier of underlying process instance. + * + * @return The identifier of the process instance. + */ + String getProcessInstanceId(); + + /** + * Sets the identifier of underlying process instance. + * + * @param processInstanceId The identifier of the process instance. + */ + void setProcessInstanceId(String processInstanceId); - /** - * Sets the identifier of underlying process instance. - * - * @param processInstanceId - * The identifier of the process instance. - */ - void setProcessInstanceId(String processInstanceId); + /** + * Stores a serializable object using {@code key}. + * + * @param key The key under that the {@code object} should be stored. + * @param object The object to be stored. + */ + void put(String key, Serializable object); - /** - * Stores a serializable object using {@code key}. - * - * @param key - * The key under that the {@code object} should be stored. - * @param object The object to be stored. - */ - void put(String key, Serializable object); + /** + * Returns an serializable object stored within this process context using {@code key}. + * + * @param key The key that has been used to store the serializable object (may be {@code null}). + * @return The object or {@code null} in case the key does not relate to a stored object or the + * stored object itself was {@code null}. + */ + Serializable get(String key); - /** - * Returns an serializable object stored within this process context using {@code key}. - * - * @param key - * The key that has been used to store the serializable object (may be {@code null}). - * @return The object or {@code null} in case the key does not relate to a stored object or the stored object itself - * was {@code null}. - */ - Serializable get(String key); - - /** - * Removes the object stored using {@code key}. - * @param key - * The key that has been used to store the serializable object (may be {@code null}). - * @return The object that has been removed or {@code null} there was no object stored using {@code key}. - */ - Serializable remove(String key); + /** + * Removes the object stored using {@code key}. + * + * @param key The key that has been used to store the serializable object (may be {@code null}). + * @return The object that has been removed or {@code null} there was no object stored using + * {@code key}. + */ + Serializable remove(String key); - /** - * Returns an unmodifiable set containing the stored keys. - * - * @return The keyset (never {@code null}). - */ - Set keySet(); + /** + * Returns an unmodifiable set containing the stored keys. + * + * @return The keyset (never {@code null}). + */ + Set keySet(); } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/slo/ISLOInformationContainer.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/slo/ISLOInformationContainer.java deleted file mode 100644 index 419765c4..00000000 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/slo/ISLOInformationContainer.java +++ /dev/null @@ -1,93 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/** - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egiz.eaaf.core.api.idp.slo; - -import java.io.Serializable; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; -import java.util.Set; - -import at.gv.egiz.eaaf.core.api.IRequest; - -/** - * @author tlenz - * - */ -public interface ISLOInformationContainer extends Serializable { - - boolean hasFrontChannelOA(); - - Set> getFrontChannelOASessionDescriptions(); - - void removeFrontChannelOA(String oaID); - - Iterator getNextBackChannelOA(); - - SLOInformationInterface getBackChannelOASessionDescripten(String oaID); - - void removeBackChannelOA(String oaID); - - /** - * @return the sloRequest - */ - IRequest getSloRequest(); - - /** - * @param sloRequest the sloRequest to set - */ - void setSloRequest(IRequest sloRequest); - - /** - * @return the sloFailedOAs - */ - List getSloFailedOAs(); - - void putFailedOA(String oaID); - - public String getTransactionID(); - - public String getSessionID(); -} \ No newline at end of file diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/slo/ISloInformationContainer.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/slo/ISloInformationContainer.java new file mode 100644 index 00000000..154d64d3 --- /dev/null +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/slo/ISloInformationContainer.java @@ -0,0 +1,75 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.api.idp.slo; + +import java.io.Serializable; +import java.util.Iterator; +import java.util.List; +import java.util.Map.Entry; +import java.util.Set; +import at.gv.egiz.eaaf.core.api.IRequest; + +/** + * Container object to process Single Log-Out operations. + * + * @author tlenz + * + */ +public interface ISloInformationContainer extends Serializable { + + boolean hasFrontChannelOA(); + + Set> getFrontChannelOaSessionDescriptions(); + + void removeFrontChannelOA(String oaID); + + Iterator getNextBackChannelOA(); + + SloInformationInterface getBackChannelOaSessionDescripten(String oaID); + + void removeBackChannelOA(String oaID); + + /** + * Single Log-out request that starts the process. + * + * @return the sloRequest + */ + IRequest getSloRequest(); + + /** + * Single Log-out request that starts the process. + * + * @param sloRequest the sloRequest to set + */ + void setSloRequest(IRequest sloRequest); + + /** + * List of Service-provider Ids for which SLO failed. + * + * @return the sloFailedOAs + */ + List getSloFailedOAs(); + + void putFailedOA(String oaID); + + public String getTransactionID(); + + public String getSessionID(); +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/slo/SLOInformationInterface.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/slo/SLOInformationInterface.java deleted file mode 100644 index f17745f3..00000000 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/slo/SLOInformationInterface.java +++ /dev/null @@ -1,104 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/** - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egiz.eaaf.core.api.idp.slo; - -/** - * @author tlenz - * - */ -public interface SLOInformationInterface{ - - - /** - * get AssertionID which was used for Service Provider Single LogOut request - * - * @return - * SessionID (SessionIndex in case of SAML2) - */ - public String getSessionIndex(); - - /** - * get user identifier which was used - * - * @return - * bPK / wbPK (nameID in case of SAML2) - */ - public String getUserNameIdentifier(); - - - /** - * get protocol type which was used for authentication - * - * @return - * return authentication protocol type - */ - public String getProtocolType(); - - /** - * @return - */ - public String getUserNameIDFormat(); - - /** - * Get the unique entityID of this Service-Provider - * - * @return unique identifier, but never null - */ - public String getSpEntityID(); - - public String getAuthURL(); - - public String getServiceURL(); - - public String getBinding(); - - public void setUserNameIdentifier(String subjectNameId); - - public void setNameIDFormat(String format); - - public void setSessionIndex(String sessionIndex); - - -} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/slo/SloInformationInterface.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/slo/SloInformationInterface.java new file mode 100644 index 00000000..fd4f9e12 --- /dev/null +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/idp/slo/SloInformationInterface.java @@ -0,0 +1,80 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.api.idp.slo; + +/** + * Container that holds information for Single Log-Out. + * + * @author tlenz + * + */ +public interface SloInformationInterface { + + + /** + * get AssertionID which was used for Service Provider Single LogOut request. + * + * @return SessionID (SessionIndex in case of SAML2) + */ + public String getSessionIndex(); + + /** + * get user identifier which was used. + * + * @return bPK / wbPK (nameID in case of SAML2) + */ + public String getUserNameIdentifier(); + + + /** + * get protocol type which was used for authentication. + * + * @return return authentication protocol type + */ + public String getProtocolType(); + + /** + * Format of the User NameId. + * + * @return + */ + public String getUserNameIdFormat(); + + /** + * Get the unique entityID of this Service-Provider. + * + * @return unique identifier, but never null + */ + public String getSpEntityID(); + + public String getAuthUrl(); + + public String getServiceUrl(); + + public String getBinding(); + + public void setUserNameIdentifier(String subjectNameId); + + public void setNameIdFormat(String format); + + public void setSessionIndex(String sessionIndex); + + +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/logging/IRevisionLogger.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/logging/IRevisionLogger.java index 9ef17684..9fc8cf5a 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/logging/IRevisionLogger.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/logging/IRevisionLogger.java @@ -1,62 +1,64 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.api.logging; import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; public interface IRevisionLogger { - - - //TODO: - public static final int AUTHPROTOCOL_TYPE = 3000; - - void logEvent(ISPConfiguration oaConfig, int eventCode, String message); - - void logEvent(IRequest pendingRequest, int eventCode); - - void logEvent(IRequest pendingRequest, int eventCode, String message); - - /** - * @param sessionCreated - * @param uniqueSessionIdentifier - */ - void logEvent(int eventCode, String message); - - /** - * @param sessionCreated - * @param uniqueSessionIdentifier - */ - void logEvent(String sessionID, String transactionID, int eventCode, String message); - - /** - * @param sessionCreated - * @param uniqueSessionIdentifier - */ - void logEvent(String sessionID, String transactionID, int eventCode); - -} \ No newline at end of file + + + // TODO: + public static final int AUTHPROTOCOL_TYPE = 3000; + + void logEvent(IspConfiguration oaConfig, int eventCode, String message); + + void logEvent(IRequest pendingRequest, int eventCode); + + void logEvent(IRequest pendingRequest, int eventCode, String message); + + /** + * Log event. + * + * @param eventCode EventCode to Log + * @param message Message + */ + void logEvent(int eventCode, String message); + + /** + * Log event. + * + * @param sessionID Id of this session + * @param transactionID Id of this trasaction + * @param eventCode EventCode to Log + * @param message Message + */ + void logEvent(String sessionID, String transactionID, int eventCode, String message); + + /** + * Log event. + * + * @param sessionID Id of this session + * @param transactionID Id of this trasaction + * @param eventCode EventCode to Log + */ + void logEvent(String sessionID, String transactionID, int eventCode); + +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/logging/IStatisticLogger.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/logging/IStatisticLogger.java index dfafe091..42c49d3c 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/logging/IStatisticLogger.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/logging/IStatisticLogger.java @@ -1,29 +1,22 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.api.logging; import at.gv.egiz.eaaf.core.api.IRequest; @@ -32,13 +25,14 @@ import at.gv.egiz.eaaf.core.api.idp.IAuthData; public interface IStatisticLogger { - - public void logSuccessOperation(IRequest protocolRequest, IAuthData authData, boolean isSSOSession); - - public void logErrorOperation(Throwable throwable); - - public void logErrorOperation(Throwable throwable, IRequest errorRequest); - - public void internalTesting() throws Exception; - + + public void logSuccessOperation(IRequest protocolRequest, IAuthData authData, + boolean isSsoSession); + + public void logErrorOperation(Throwable throwable); + + public void logErrorOperation(Throwable throwable, IRequest errorRequest); + + public void internalTesting() throws Exception; + } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/storage/ITransactionStorage.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/storage/ITransactionStorage.java index ad424329..b8438a79 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/storage/ITransactionStorage.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/storage/ITransactionStorage.java @@ -1,138 +1,135 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.api.storage; import java.util.Date; import java.util.List; - -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.core.exceptions.EAAFStorageException; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; /** + * Interface to store arbitrary data. + * * @author tlenz * */ public interface ITransactionStorage { - /** - * Check if transaction storage contains a data object with a specific key - * - * @param key Key, which identifies a data object - * @return true if key is found, otherwise false - */ - public boolean containsKey(String key); - - /** - * Store a data object with a key to transaction storage - * - * @param key Id which identifiers the data object - * @param value Data object which should be stored. - * This data must implement the java.io.Serializable interface - * @param timeout_ms Defines the period of time a data object is kept within the storage - * @throws EAAFStorageException In case of store operation failed - */ - public void put(String key, Object value, int timeout_ms) throws EAAFException; - - /** - * Get a data object from transaction storage - * - * @param key key Id which identifiers the data object - * @return The transaction-data object, or null - * @throws EAAFStorageException In case of load operation failed - */ - public Object get(String key) throws EAAFException; - - /** - * Get a data object from transaction storage - * - * @param key Id which identifiers the data object - * @param clazz The class type which is stored with this key - * @return The transaction-data object from type class, or null - * @throws EAAFStorageException In case of load operation failed - */ - public T get(String key, final Class clazz) throws EAAFException; - - /** - * Get a data object from transaction storage - * - * @param key Id which identifiers the data object - * @param clazz The class type which is stored with this key - * @param Data-object timeout in [ms] - * @return The transaction-data object from type class, or null - * @throws EAAFStorageException In case of load operation failed - */ - public T get(String key, final Class clazz, long dataTimeOut) throws EAAFException; - - - /** - * Change the key of a data object and store it under the new key - * - * @param oldKey Old key of the data object - * @param newKey New key, which should be used to store the data object - * @param value Data object which should be stored - * @throws EAAFStorageException In case of store operation failed - */ - public void changeKey(String oldKey, String newKey, Object value) throws EAAFException; - - /** - * Remove a data object from transaction storage - * - * @param key Id which identifiers the data object - */ - public void remove(String key); - - /** - * Get all entries for Clean-up the transaction storage - * - * @param now Current time - * @param dataTimeOut Data-object timeout in [ms] - * @return List of entry-keys which as a timeout - */ - public List clean(Date now, long dataTimeOut); - - - /** - * Get a raw object from storage by using this key - * - * @param key - * @return - * @throws EAAFException - */ - public Object getRaw(String key) throws EAAFException; - - - /** - * Set a raw object to storage - * - * @param key - * @param element - * @throws EAAFException - */ - public void putRaw(String key, Object element) throws EAAFException; - - + /** + * Check if transaction storage contains a data object with a specific key. + * + * @param key Key, which identifies a data object + * @return true if key is found, otherwise false + */ + public boolean containsKey(String key); + + /** + * Store a data object with a key to transaction storage. + * + * @param key Id which identifiers the data object + * @param value Data object which should be stored. This data must implement the + * java.io.Serializable interface + * @param timeoutMs Defines the period of time a data object is kept within the storage + * @throws EaafStorageException In case of store operation failed + */ + public void put(String key, Object value, int timeoutMs) throws EaafException; + + /** + * Get a data object from transaction storage. + * + * @param key key Id which identifiers the data object + * @return The transaction-data object, or null + * @throws EaafStorageException In case of load operation failed + */ + public Object get(String key) throws EaafException; + + /** + * Get a data object from transaction storage. + * + * @param key Id which identifiers the data object + * @param clazz The class type which is stored with this key + * @return The transaction-data object from type class, or null + * @throws EaafStorageException In case of load operation failed + */ + public T get(String key, final Class clazz) throws EaafException; + + /** + * Get a data object from transaction storage. + * + * @param key Id which identifiers the data object + * @param clazz The class type which is stored with this key + * @param dataTimeOut Data-object timeout in [ms] + * @return The transaction-data object from type class, or null + * @throws EaafStorageException In case of load operation failed + */ + public T get(String key, final Class clazz, long dataTimeOut) throws EaafException; + + + /** + * Change the key of a data object and store it under the new key. + * + * @param oldKey Old key of the data object + * @param newKey New key, which should be used to store the data object + * @param value Data object which should be stored + * @throws EaafStorageException In case of store operation failed + */ + public void changeKey(String oldKey, String newKey, Object value) throws EaafException; + + /** + * Remove a data object from transaction storage. + * + * @param key Id which identifiers the data object + */ + public void remove(String key); + + /** + * Get all entries for Clean-up the transaction storage. + * + * @param now Current time + * @param dataTimeOut Data-object timeout in [ms] + * @return List of entry-keys which as a timeout + */ + public List clean(Date now, long dataTimeOut); + + + /** + * Get a raw object from storage by using this key. + * + * @param key Storagekey + * @return Object stored with this key, or null + * @throws EaafException In case of a storage error + */ + @Nullable + public Object getRaw(String key) throws EaafException; + + + /** + * Set a raw object to storage. + * + * @param key Storagekey + * @param element Object to store + * @throws EaafException In case of a storage error + */ + public void putRaw(@Nonnull String key, @Nonnull Object element) throws EaafException; + + } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/utils/IPendingRequestIdGenerationStrategy.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/utils/IPendingRequestIdGenerationStrategy.java index 5fe3fea6..2129568a 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/utils/IPendingRequestIdGenerationStrategy.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/api/utils/IPendingRequestIdGenerationStrategy.java @@ -2,40 +2,41 @@ package at.gv.egiz.eaaf.core.api.utils; import javax.annotation.Nonnull; import javax.annotation.Nullable; - -import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.exceptions.PendingReqIdValidationException; public interface IPendingRequestIdGenerationStrategy { - /** - * Generate a new external pending-request id - * - * @return - * @throws EAAFException - */ - @Nonnull - public String generateExternalPendingRequestId() throws EAAFException; - - /** - * Validate a pendingRequestId according to implemented strategy - * - * @param pendingReqId pending-request Id that should be validated - * @return internalPendingRequestId - * @throws PendingReqIdValidationException - */ - @Nonnull - public String validateAndGetPendingRequestId(@Nullable String pendingReqId) throws PendingReqIdValidationException; + /** + * Generate a new external pending-request id. + * + * @return TransactionToken that can be used for pendingRequests + * @throws EaafException In case of a token generation error + */ + @Nonnull + public String generateExternalPendingRequestId() throws EaafException; + + /** + * Validate a pendingRequestId according to implemented strategy. + * + * @param pendingReqId pending-request Id that should be validated + * @return internalPendingRequestId + * @throws PendingReqIdValidationException In case of a token validation error + */ + @Nonnull + public String validateAndGetPendingRequestId(@Nullable String pendingReqId) + throws PendingReqIdValidationException; - /** - * Get the internal pendingReqId without any validation - * - * @param pendingReqId pending-request Id that should be validated - * @return internalPendingRequestId - * @throws PendingReqIdValidationException - */ - @Nonnull - public String getPendingRequestIdWithOutChecks(@Nullable String externalPendingReqId) throws PendingReqIdValidationException; + /** + * Get the internal pendingReqId without any validation. + * + * @param externalPendingReqId pending-request Id that should be validated + * @return internalPendingRequestId + * @throws PendingReqIdValidationException In case of token processing error + */ + @Nonnull + public String getPendingRequestIdWithOutChecks(@Nullable String externalPendingReqId) + throws PendingReqIdValidationException; } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/AttributeBuilderException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/AttributeBuilderException.java index f02b3bf6..2a96490b 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/AttributeBuilderException.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/AttributeBuilderException.java @@ -1,37 +1,30 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.exceptions; -public class AttributeBuilderException extends EAAFIDPException { +public class AttributeBuilderException extends EaafIdpException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public AttributeBuilderException(String attrName) { - super("builder.12", new Object[] {attrName}); - } + public AttributeBuilderException(final String attrName) { + super("builder.12", new Object[] {attrName}); + } } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/AttributePolicyException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/AttributePolicyException.java index 4a0e2fc1..abbe56aa 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/AttributePolicyException.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/AttributePolicyException.java @@ -1,44 +1,38 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + + package at.gv.egiz.eaaf.core.exceptions; public class AttributePolicyException extends AttributeBuilderException { - - private static final long serialVersionUID = 1L; - - private String attributeName; - - public AttributePolicyException(String attributeName) { - super("Attribute " + attributeName + " is restricted by IDP policy."); - this.attributeName = attributeName; - } - - public String getAttributeName() { - return attributeName; - } - + + private static final long serialVersionUID = 1L; + + private final String attributeName; + + public AttributePolicyException(final String attributeName) { + super("Attribute " + attributeName + " is restricted by IDP policy."); + this.attributeName = attributeName; + } + + public String getAttributeName() { + return attributeName; + } + } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/AuthnRequestValidatorException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/AuthnRequestValidatorException.java index 30db0b09..32ad97b7 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/AuthnRequestValidatorException.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/AuthnRequestValidatorException.java @@ -1,84 +1,98 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.exceptions; import at.gv.egiz.eaaf.core.api.IRequest; /** + * Authentication request validation error. + * * @author tlenz * */ -public class AuthnRequestValidatorException extends EAAFProtocolException { - - private IRequest errorRequest = null; - protected String statusCodeValue; - - /** - * - */ - private static final long serialVersionUID = 4939651000658508576L; - - /** - * @param messageId - * @param parameters - */ - public AuthnRequestValidatorException(String internalMsgId, Object[] params) { - super(internalMsgId, params); - - } - - public AuthnRequestValidatorException(String internalMsgId, Object[] params, Throwable e) { - super(internalMsgId, params,e); - - } - - public AuthnRequestValidatorException(String internalMsgId, Object[] params, IRequest errorRequest) { - super(internalMsgId, params); - this.errorRequest = errorRequest; - - } - - public AuthnRequestValidatorException(String internalMsgId, Object[] params, IRequest errorRequest, Throwable e) { - super(internalMsgId, params, e); - this.errorRequest = errorRequest; - - } - - /** - * @return the errorRequest - */ - public IRequest getErrorRequest() { - return errorRequest; - } - - public String getStatusCodeValue() { - return statusCodeValue; - } - - +public class AuthnRequestValidatorException extends EaafProtocolException { + + private IRequest errorRequest = null; + protected String statusCodeValue; + + private static final long serialVersionUID = 4939651000658508576L; + + public AuthnRequestValidatorException(final String internalMsgId, final Object[] params) { + super(internalMsgId, params); + + } + + public AuthnRequestValidatorException(final String internalMsgId, final Object[] params, + final Throwable e) { + super(internalMsgId, params, e); + + } + + /** + * Protocol validation error. + * + * @param internalMsgId Internal error-code + * @param params Message parameters + * @param errorRequest Pending-Request that generates the error + */ + public AuthnRequestValidatorException(final String internalMsgId, final Object[] params, + final IRequest errorRequest) { + super(internalMsgId, params); + this.errorRequest = errorRequest; + + } + + /** + * Protocol validation error. + * + * @param internalMsgId Internal error-code + * @param params Message parameters + * @param errorRequest Pending-Request that generates the error + * @param e error + */ + public AuthnRequestValidatorException(final String internalMsgId, final Object[] params, + final IRequest errorRequest, final Throwable e) { + super(internalMsgId, params, e); + this.errorRequest = errorRequest; + + } + + /** + * PendingRequest object that generates the error. + * + * @return the errorRequest + */ + public IRequest getErrorRequest() { + return errorRequest; + } + + public String getStatusCodeValue() { + return statusCodeValue; + } + + public void setStatusCodeValue(String statusCodeValue) { + this.statusCodeValue = statusCodeValue; + } + + + + } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFAuthenticationException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFAuthenticationException.java deleted file mode 100644 index e6bdb804..00000000 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFAuthenticationException.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.exceptions; - -public class EAAFAuthenticationException extends EAAFException { - - - - private static final long serialVersionUID = -4793625336456467005L; - - public EAAFAuthenticationException(String internalMsgId, Object[] params) { - super(internalMsgId, params); - - } - - public EAAFAuthenticationException(String internalMsgId, Object[] params, Throwable e) { - super(internalMsgId, params, e); - - } - -} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFBuilderException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFBuilderException.java deleted file mode 100644 index dc2b61f7..00000000 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFBuilderException.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.exceptions; - -public class EAAFBuilderException extends EAAFException { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public EAAFBuilderException(String errorId, Object[] params, String msg) { - super(errorId, params); - } - - public EAAFBuilderException(String errorId, Object[] objects, String message, Throwable ex) { - super(errorId, objects, ex); - } - -} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFConfigurationException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFConfigurationException.java deleted file mode 100644 index 71f46cb5..00000000 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFConfigurationException.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.exceptions; - -public class EAAFConfigurationException extends EAAFException { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public EAAFConfigurationException(String msg, Object[] params) { - super(msg, params); - } - - public EAAFConfigurationException(String msg, Object[] params, Throwable e) { - super(msg, params, e); - } - -} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFException.java deleted file mode 100644 index affd1dab..00000000 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFException.java +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.exceptions; - -import at.gv.egiz.eaaf.core.impl.logging.LogMessageProviderFactory; - -public class EAAFException extends Exception { - - private static final long serialVersionUID = 1L; - - private String errorId = null; - private Object[] params = null; - - public EAAFException(String errorId) { - super(LogMessageProviderFactory.getMessager().getMessage(errorId, null)); - this.errorId = errorId; - } - - public EAAFException(String errorId, Object[] params) { - super(LogMessageProviderFactory.getMessager().getMessage(errorId, params)); - this.errorId = errorId; - this.params = params; - - } - - public EAAFException(String errorId, Object[] params, Throwable e) { - super(LogMessageProviderFactory.getMessager().getMessage(errorId, params), e); - this.errorId = errorId; - this.params = params; - - } - - public String getErrorId() { - return this.errorId; - - } - - public Object[] getParams() { - return this.params; - - } -} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFIDPException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFIDPException.java deleted file mode 100644 index 7f504a5a..00000000 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFIDPException.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.exceptions; - -public class EAAFIDPException extends EAAFException { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public EAAFIDPException(String msg) { - super(msg, null); - - } - - public EAAFIDPException(String msg, Object[] params) { - super(msg, params); - - } - -} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFIllegalStateException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFIllegalStateException.java deleted file mode 100644 index 95688260..00000000 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFIllegalStateException.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.exceptions; - -import at.gv.egiz.eaaf.core.api.IStatusMessenger; - -public class EAAFIllegalStateException extends EAAFException { - private static final long serialVersionUID = 261484121729891927L; - - public EAAFIllegalStateException(Object[] params) { - super(IStatusMessenger.CODES_INTERNAL_ILLEGAL_STATE, params); - - } - - public EAAFIllegalStateException(Object[] params, Throwable e) { - super(IStatusMessenger.CODES_INTERNAL_ILLEGAL_STATE, params, e); - - } - -} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFJsonMapperException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFJsonMapperException.java deleted file mode 100644 index 41431d02..00000000 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFJsonMapperException.java +++ /dev/null @@ -1,16 +0,0 @@ -package at.gv.egiz.eaaf.core.exceptions; - -public class EAAFJsonMapperException extends EAAFParserException { - - - private static final long serialVersionUID = 2278865064672630267L; - - public EAAFJsonMapperException(String reason) { - super("parser.03", new Object[] {reason}); - } - - public EAAFJsonMapperException(String reason, Throwable ex) { - super("parser.03", new Object[] {reason}, ex); - } - -} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFParserException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFParserException.java deleted file mode 100644 index 07987f92..00000000 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFParserException.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.exceptions; - -public class EAAFParserException extends EAAFException { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public EAAFParserException(String errorId, Object[] params) { - super(errorId, params); - } - - public EAAFParserException(String errorId, Object[] objects, Throwable ex) { - super(errorId, objects, ex); - } - -} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFProtocolException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFProtocolException.java deleted file mode 100644 index da529c29..00000000 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFProtocolException.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.exceptions; - -public class EAAFProtocolException extends EAAFException { - - private static final long serialVersionUID = 7982298114399440473L; - - public EAAFProtocolException(String errorId, Object[] params) { - super(errorId, params); - - } - - public EAAFProtocolException(String errorId, Object[] params, Throwable e) { - super(errorId, params, e); - } -} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFSSOException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFSSOException.java deleted file mode 100644 index 27afcd4a..00000000 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFSSOException.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.exceptions; - -public class EAAFSSOException extends EAAFException { - - /** - * - */ - private static final long serialVersionUID = -5942886204347860148L; - - public EAAFSSOException(String errorId, Object[] params, Throwable e) { - super(errorId, params, e); - - } - -} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFServiceException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFServiceException.java deleted file mode 100644 index 7094c270..00000000 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFServiceException.java +++ /dev/null @@ -1,30 +0,0 @@ -package at.gv.egiz.eaaf.core.exceptions; - -import javax.annotation.Nonnull; - -public abstract class EAAFServiceException extends EAAFException { - - private static final long serialVersionUID = -867758153828290337L; - - public EAAFServiceException(String errorId, Object[] params) { - super(errorId, params); - - } - - public EAAFServiceException(String errorId, Object[] params, Throwable e) { - super(errorId, params, e); - - } - - /** - * Get a textual identifier of the service that throws this exception - * - * @return - */ - @Nonnull - protected abstract String getServiceIdentifier(); - - - - -} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFStorageException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFStorageException.java deleted file mode 100644 index b99472c3..00000000 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EAAFStorageException.java +++ /dev/null @@ -1,42 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.exceptions; - -public class EAAFStorageException extends EAAFException { - - private static final long serialVersionUID = 1L; - - public EAAFStorageException(String msg) { - super("internal.02", new Object[] {msg}); - } - - public EAAFStorageException(String msg, Throwable e) { - super("internal.02", new Object[] {msg}, e); - } - - -} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafAuthenticationException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafAuthenticationException.java new file mode 100644 index 00000000..7dbf0a5d --- /dev/null +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafAuthenticationException.java @@ -0,0 +1,38 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.exceptions; + +public class EaafAuthenticationException extends EaafException { + + + + private static final long serialVersionUID = -4793625336456467005L; + + public EaafAuthenticationException(final String internalMsgId, final Object[] params) { + super(internalMsgId, params); + + } + + public EaafAuthenticationException(final String internalMsgId, final Object[] params, final Throwable e) { + super(internalMsgId, params, e); + + } + +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafBuilderException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafBuilderException.java new file mode 100644 index 00000000..008d24a7 --- /dev/null +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafBuilderException.java @@ -0,0 +1,34 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.exceptions; + +public class EaafBuilderException extends EaafException { + + private static final long serialVersionUID = 1L; + + public EaafBuilderException(final String errorId, final Object[] params, final String msg) { + super(errorId, params); + } + + public EaafBuilderException(final String errorId, final Object[] objects, final String message, final Throwable ex) { + super(errorId, objects, ex); + } + +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafConfigurationException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafConfigurationException.java new file mode 100644 index 00000000..c40dc2a4 --- /dev/null +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafConfigurationException.java @@ -0,0 +1,35 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.exceptions; + +public class EaafConfigurationException extends EaafException { + + + private static final long serialVersionUID = 1L; + + public EaafConfigurationException(final String msg, final Object[] params) { + super(msg, params); + } + + public EaafConfigurationException(final String msg, final Object[] params, final Throwable e) { + super(msg, params, e); + } + +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafException.java new file mode 100644 index 00000000..89011a87 --- /dev/null +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafException.java @@ -0,0 +1,89 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.exceptions; + +import java.util.Arrays; +import javax.annotation.Nullable; +import at.gv.egiz.eaaf.core.impl.logging.LogMessageProviderFactory; + +public class EaafException extends Exception { + + private static final long serialVersionUID = 1L; + + private String errorId = null; + private Object[] params = null; + + public EaafException(final String errorId) { + super(LogMessageProviderFactory.getMessager().getMessage(errorId, null)); + this.errorId = errorId; + } + + /** + * Generic processing-error in EAAF framework. + * + * @param errorId Internal error-code that is also used to generate i18n messages + * @param params Message parameters + */ + public EaafException(final String errorId, final Object[] params) { + super(LogMessageProviderFactory.getMessager().getMessage(errorId, params)); + this.errorId = errorId; + this.params = makeCopyIfNotNull(params); + + } + + + /** + * Generic processing-error in EAAF framework. + * + * @param errorId Internal error-code that is also used to generate i18n messages + * @param params Message parameters + * @param e Exception + */ + public EaafException(final String errorId, final Object[] params, final Throwable e) { + super(LogMessageProviderFactory.getMessager().getMessage(errorId, params), e); + this.errorId = errorId; + this.params = makeCopyIfNotNull(params); + + } + + public String getErrorId() { + return this.errorId; + + } + + /** + * Get a copy of message parameters. + * + * @return + */ + @Nullable + public Object[] getParams() { + return makeCopyIfNotNull(this.params); + + } + + private Object[] makeCopyIfNotNull(Object[] params) { + if (params != null) { + return Arrays.copyOf(params, params.length); + } else { + return null; + } + } +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafIdpException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafIdpException.java new file mode 100644 index 00000000..234a6971 --- /dev/null +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafIdpException.java @@ -0,0 +1,36 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.exceptions; + +public class EaafIdpException extends EaafException { + + private static final long serialVersionUID = 1L; + + public EaafIdpException(final String msg) { + super(msg, null); + + } + + public EaafIdpException(final String msg, final Object[] params) { + super(msg, params); + + } + +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafIllegalStateException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafIllegalStateException.java new file mode 100644 index 00000000..09414cab --- /dev/null +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafIllegalStateException.java @@ -0,0 +1,37 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.exceptions; + +import at.gv.egiz.eaaf.core.api.IStatusMessenger; + +public class EaafIllegalStateException extends EaafException { + private static final long serialVersionUID = 261484121729891927L; + + public EaafIllegalStateException(final Object[] params) { + super(IStatusMessenger.CODES_INTERNAL_ILLEGAL_STATE, params); + + } + + public EaafIllegalStateException(final Object[] params, final Throwable e) { + super(IStatusMessenger.CODES_INTERNAL_ILLEGAL_STATE, params, e); + + } + +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafJsonMapperException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafJsonMapperException.java new file mode 100644 index 00000000..0d24cb3a --- /dev/null +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafJsonMapperException.java @@ -0,0 +1,16 @@ +package at.gv.egiz.eaaf.core.exceptions; + +public class EaafJsonMapperException extends EaafParserException { + + + private static final long serialVersionUID = 2278865064672630267L; + + public EaafJsonMapperException(final String reason) { + super("parser.03", new Object[] {reason}); + } + + public EaafJsonMapperException(final String reason, final Throwable ex) { + super("parser.03", new Object[] {reason}, ex); + } + +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafParserException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafParserException.java new file mode 100644 index 00000000..51909d74 --- /dev/null +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafParserException.java @@ -0,0 +1,34 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.exceptions; + +public class EaafParserException extends EaafException { + + private static final long serialVersionUID = 1L; + + public EaafParserException(final String errorId, final Object[] params) { + super(errorId, params); + } + + public EaafParserException(final String errorId, final Object[] objects, final Throwable ex) { + super(errorId, objects, ex); + } + +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafProtocolException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafProtocolException.java new file mode 100644 index 00000000..1aab2e55 --- /dev/null +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafProtocolException.java @@ -0,0 +1,34 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.exceptions; + +public class EaafProtocolException extends EaafException { + + private static final long serialVersionUID = 7982298114399440473L; + + public EaafProtocolException(final String errorId, final Object[] params) { + super(errorId, params); + + } + + public EaafProtocolException(final String errorId, final Object[] params, final Throwable e) { + super(errorId, params, e); + } +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafServiceException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafServiceException.java new file mode 100644 index 00000000..2d26a8bf --- /dev/null +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafServiceException.java @@ -0,0 +1,29 @@ +package at.gv.egiz.eaaf.core.exceptions; + +import javax.annotation.Nonnull; + +public abstract class EaafServiceException extends EaafException { + + private static final long serialVersionUID = -867758153828290337L; + + public EaafServiceException(final String errorId, final Object[] params) { + super(errorId, params); + + } + + public EaafServiceException(final String errorId, final Object[] params, final Throwable e) { + super(errorId, params, e); + + } + + /** + * Get a textual identifier of the service that throws this exception. + * + * @return + */ + @Nonnull + protected abstract String getServiceIdentifier(); + + + +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafSsoException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafSsoException.java new file mode 100644 index 00000000..fc740e6a --- /dev/null +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafSsoException.java @@ -0,0 +1,31 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.exceptions; + +public class EaafSsoException extends EaafException { + + private static final long serialVersionUID = -5942886204347860148L; + + public EaafSsoException(final String errorId, final Object[] params, final Throwable e) { + super(errorId, params, e); + + } + +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafStorageException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafStorageException.java new file mode 100644 index 00000000..1df2e5dc --- /dev/null +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/EaafStorageException.java @@ -0,0 +1,35 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.exceptions; + +public class EaafStorageException extends EaafException { + + private static final long serialVersionUID = 1L; + + public EaafStorageException(final String msg) { + super("internal.02", new Object[] {msg}); + } + + public EaafStorageException(final String msg, final Throwable e) { + super("internal.02", new Object[] {msg}, e); + } + + +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/GUIBuildException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/GUIBuildException.java deleted file mode 100644 index 011488f7..00000000 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/GUIBuildException.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.exceptions; - -/** - * @author tlenz - * - */ -public class GUIBuildException extends Exception { - - private static final long serialVersionUID = -278663750102498205L; - - /** - * @param string - */ - public GUIBuildException(String msg) { - super(msg); - - } - - public GUIBuildException(String msg, Throwable e) { - super(msg, e); - - } - -} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/GuiBuildException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/GuiBuildException.java new file mode 100644 index 00000000..9e9c08a7 --- /dev/null +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/GuiBuildException.java @@ -0,0 +1,47 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.exceptions; + +/** + * GUI generation error. + * + * @author tlenz + * + */ +public class GuiBuildException extends Exception { + + private static final long serialVersionUID = -278663750102498205L; + + /** + * GUI generation error. + * + * @param msg error message + */ + public GuiBuildException(final String msg) { + super(msg); + + } + + public GuiBuildException(final String msg, final Throwable e) { + super(msg, e); + + } + +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/InvalidDateFormatAttributeException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/InvalidDateFormatAttributeException.java index 5d35ac84..9ae02e07 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/InvalidDateFormatAttributeException.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/InvalidDateFormatAttributeException.java @@ -1,39 +1,32 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.exceptions; public class InvalidDateFormatAttributeException extends AttributeBuilderException { - private static final long serialVersionUID = 1L; - - public InvalidDateFormatAttributeException() { - super("Date format is invalid."); - } + private static final long serialVersionUID = 1L; + + public InvalidDateFormatAttributeException() { + super("Date format is invalid."); + } + + - - } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/InvalidProtocolRequestException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/InvalidProtocolRequestException.java index 8ed09525..2d1847af 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/InvalidProtocolRequestException.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/InvalidProtocolRequestException.java @@ -1,47 +1,34 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.exceptions; -/** - * @author tlenz - * - */ -public class InvalidProtocolRequestException extends EAAFProtocolException { - /** - * - */ - private static final long serialVersionUID = -7866198705324084601L; +public class InvalidProtocolRequestException extends EaafProtocolException { + + private static final long serialVersionUID = -7866198705324084601L; - public InvalidProtocolRequestException(String internalMsgId, Object[] params) { - super(internalMsgId, params); - } + public InvalidProtocolRequestException(final String internalMsgId, final Object[] params) { + super(internalMsgId, params); + } - public InvalidProtocolRequestException(String internalMsgId, Object[] params, Throwable e) { - super(internalMsgId, params, e); - } + public InvalidProtocolRequestException(final String internalMsgId, final Object[] params, final Throwable e) { + super(internalMsgId, params, e); + } } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/NoPassivAuthenticationException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/NoPassivAuthenticationException.java index 495d61bc..bf7a15c6 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/NoPassivAuthenticationException.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/NoPassivAuthenticationException.java @@ -1,42 +1,32 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.exceptions; import at.gv.egiz.eaaf.core.api.IStatusMessenger; -public class NoPassivAuthenticationException extends EAAFAuthenticationException { +public class NoPassivAuthenticationException extends EaafAuthenticationException { - public NoPassivAuthenticationException() { - super(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_REQUEST_INVALID, null); - } + public NoPassivAuthenticationException() { + super(IStatusMessenger.CODES_INTERNAL_ERROR_AUTH_REQUEST_INVALID, null); + } - /** - * - */ - private static final long serialVersionUID = 596920452166197688L; + private static final long serialVersionUID = 596920452166197688L; } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/PendingReqIdValidationException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/PendingReqIdValidationException.java index e558c3cb..124881c2 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/PendingReqIdValidationException.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/PendingReqIdValidationException.java @@ -2,59 +2,65 @@ package at.gv.egiz.eaaf.core.exceptions; import javax.annotation.Nonnull; - import at.gv.egiz.eaaf.core.api.IRequest; -public class PendingReqIdValidationException extends EAAFException { - - /** - * - */ - private static final long serialVersionUID = -6886402432880791308L; - - private final String invalidInternalPendingReqId; - private IRequest invalidPendingReq; - - /** - * - * @param pendingReqId - * @param reason - */ - public PendingReqIdValidationException(String internalPendingReqId, @Nonnull String reason) { - super("process.99", new Object[] {internalPendingReqId, reason}); - this.invalidInternalPendingReqId = internalPendingReqId; - - } - - public PendingReqIdValidationException(String internalPendingReqId, @Nonnull String reason, Throwable e) { - super("process.99", new Object[] {internalPendingReqId, reason}, e ); - this.invalidInternalPendingReqId = internalPendingReqId; - } - - /** - * Get the invalid pending-request - * - * @return - */ - public IRequest getInvalidPendingReq() { - return invalidPendingReq; - } - - - /** - * Get the internal invalid pending-request id - * - * @return - */ - public String getInvalidInternalPendingReqId() { - return invalidInternalPendingReqId; - } - - public void setInvalidPendingReq(IRequest invalidPendingReq) { - this.invalidPendingReq = invalidPendingReq; - - } - - +public class PendingReqIdValidationException extends EaafException { + + private static final long serialVersionUID = -6886402432880791308L; + + private final String invalidInternalPendingReqId; + private IRequest invalidPendingReq; + + /** + * Pending-Request Id validation error. + * + * @param internalPendingReqId Internal Pending-Request Id + * @param reason error-message + */ + public PendingReqIdValidationException(final String internalPendingReqId, + @Nonnull final String reason) { + super("process.99", new Object[] {internalPendingReqId, reason}); + this.invalidInternalPendingReqId = internalPendingReqId; + + } + + /** + * Pending-Request Id validation error. + * + * @param internalPendingReqId Internal Pending-Request Id + * @param reason error-message + * @param e error + */ + public PendingReqIdValidationException(final String internalPendingReqId, + @Nonnull final String reason, final Throwable e) { + super("process.99", new Object[] {internalPendingReqId, reason}, e); + this.invalidInternalPendingReqId = internalPendingReqId; + } + + /** + * Get the invalid pending-request. + * + * @return + */ + public IRequest getInvalidPendingReq() { + return invalidPendingReq; + } + + + /** + * Get the internal invalid pending-request id. + * + * @return + */ + public String getInvalidInternalPendingReqId() { + return invalidInternalPendingReqId; + } + + public void setInvalidPendingReq(final IRequest invalidPendingReq) { + this.invalidPendingReq = invalidPendingReq; + + } + + } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/ProcessExecutionException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/ProcessExecutionException.java index b72237b2..d24a438d 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/ProcessExecutionException.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/ProcessExecutionException.java @@ -1,62 +1,52 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.exceptions; /** * Indicates a problem when executing a process. - * + * * @author tknall - * + * */ public class ProcessExecutionException extends Exception { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - /** - * Creates a new process execution exception providing a {@code message} describing the reason and the respective - * {@code cause}. - * - * @param message - * The message. - * @param cause - * The cause. - */ - public ProcessExecutionException(String message, Throwable cause) { - super(message, cause); - } + /** + * Creates a new process execution exception providing a {@code message} describing the reason and + * the respective {@code cause}. + * + * @param message The message. + * @param cause The cause. + */ + public ProcessExecutionException(final String message, final Throwable cause) { + super(message, cause); + } - /** - * Creates a new process execution exception providing a {@code message} describing the reason. - * - * @param message - * The message. - */ - public ProcessExecutionException(String message) { - super(message); - } + /** + * Creates a new process execution exception providing a {@code message} describing the reason. + * + * @param message The message. + */ + public ProcessExecutionException(final String message) { + super(message); + } } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/ProtocolNotActiveException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/ProtocolNotActiveException.java index 79c94c7b..014ec9b2 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/ProtocolNotActiveException.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/ProtocolNotActiveException.java @@ -1,44 +1,36 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.exceptions; /** + * Protocol not-active error. + * * @author tlenz * */ -public class ProtocolNotActiveException extends EAAFProtocolException { +public class ProtocolNotActiveException extends EaafProtocolException { - /** - * - */ - private static final long serialVersionUID = 1832697083163940710L; + private static final long serialVersionUID = 1832697083163940710L; - public ProtocolNotActiveException(String internalMsgId, Object[] params) { - super(internalMsgId, params); - } + public ProtocolNotActiveException(final String internalMsgId, final Object[] params) { + super(internalMsgId, params); + } } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/ProtocolResponseExceptions.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/ProtocolResponseExceptions.java index 194505d3..7a1af227 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/ProtocolResponseExceptions.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/ProtocolResponseExceptions.java @@ -1,14 +1,14 @@ package at.gv.egiz.eaaf.core.exceptions; -public class ProtocolResponseExceptions extends EAAFProtocolException { +public class ProtocolResponseExceptions extends EaafProtocolException { - private static final long serialVersionUID = -7866198705324084601L; + private static final long serialVersionUID = -7866198705324084601L; - public ProtocolResponseExceptions(String internalMsgId, Object[] params) { - super(internalMsgId, params); - } + public ProtocolResponseExceptions(final String internalMsgId, final Object[] params) { + super(internalMsgId, params); + } - public ProtocolResponseExceptions(String internalMsgId, Object[] params, Throwable e) { - super(internalMsgId, params, e); - } + public ProtocolResponseExceptions(final String internalMsgId, final Object[] params, final Throwable e) { + super(internalMsgId, params, e); + } } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/SLOException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/SLOException.java deleted file mode 100644 index 4a52e7a2..00000000 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/SLOException.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.exceptions; - -/** - * @author tlenz - * - */ -public class SLOException extends EAAFException { - private static final long serialVersionUID = -5284624715788385022L; - - /** - * @param messageId - * @param parameters - */ - public SLOException(String messageId, Object[] parameters) { - super(messageId, parameters); - - } - -} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/SloException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/SloException.java new file mode 100644 index 00000000..4924fa6a --- /dev/null +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/SloException.java @@ -0,0 +1,36 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.exceptions; + +/** + * Single Log-Out processing error. + * + * @author tlenz + * + */ +public class SloException extends EaafException { + private static final long serialVersionUID = -5284624715788385022L; + + public SloException(final String messageId, final Object[] parameters) { + super(messageId, parameters); + + } + +} diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/TaskExecutionException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/TaskExecutionException.java index 773cbc4a..61149691 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/TaskExecutionException.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/TaskExecutionException.java @@ -1,77 +1,75 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.exceptions; import at.gv.egiz.eaaf.core.api.IRequest; /** + * Task execution error. + * * @author tlenz * */ public class TaskExecutionException extends ProcessExecutionException { - private static final long serialVersionUID = 1L; - Throwable originalException = null; - String pendingRequestID = null; - - /** - * @param message - * @param cause - */ - public TaskExecutionException(IRequest pendingReq, String message, Throwable cause) { - super(message, cause); - this.originalException = cause; - - if (pendingReq.getPendingRequestId() != null && !pendingReq.getPendingRequestId().isEmpty()) - this.pendingRequestID = pendingReq.getPendingRequestId(); - - } + private static final long serialVersionUID = 1L; + Throwable originalException = null; + String pendingRequestID = null; + + /** + * Task execution error. + * + * @param pendingReq Current processed pending-request + * @param message error message + * @param cause error reason + */ + public TaskExecutionException(final IRequest pendingReq, final String message, + final Throwable cause) { + super(message, cause); + this.originalException = cause; + + if (pendingReq.getPendingRequestId() != null && !pendingReq.getPendingRequestId().isEmpty()) { + this.pendingRequestID = pendingReq.getPendingRequestId(); + } + + } + + /** + * Get the original internal exception from task. + * + * @return the originalException + */ + public Throwable getOriginalException() { + return originalException; + + } + + /** + * Get the pending-request ID of that request, which was processed when the exception occurs. + * + * @return the pendingRequestID + */ + public String getPendingRequestID() { + return pendingRequestID; + } + - /** - * Get the original internal exception from task - * - * @return the originalException - */ - public Throwable getOriginalException() { - return originalException; - - } - /** - * Get the pending-request ID of that request, which was processed when the exception occurs - * - * @return the pendingRequestID - */ - public String getPendingRequestID() { - return pendingRequestID; - } - - - - - } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/UnavailableAttributeException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/UnavailableAttributeException.java index 626cbea7..5bc0880b 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/UnavailableAttributeException.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/UnavailableAttributeException.java @@ -1,46 +1,37 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.exceptions; public class UnavailableAttributeException extends AttributeBuilderException { - /** - * - */ - private static final long serialVersionUID = -1114323185905118432L; - private final String attributeName; - - public UnavailableAttributeException(String attributeName) { - super(attributeName); - this.attributeName = attributeName; - } + private static final long serialVersionUID = -1114323185905118432L; + + private final String attributeName; + + public UnavailableAttributeException(final String attributeName) { + super(attributeName); + this.attributeName = attributeName; + } - public String getAttributeName() { - return attributeName; - } + public String getAttributeName() { + return attributeName; + } } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/XPathException.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/XPathException.java index fe3a96e6..d3c41994 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/XPathException.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/exceptions/XPathException.java @@ -1,29 +1,22 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.exceptions; @@ -33,34 +26,32 @@ import java.io.PrintWriter; /** * An exception occurred evaluating an XPath. - * + * */ public class XPathException extends RuntimeException { - /** - * - */ - private static final long serialVersionUID = 1736311265333034392L; -/** The wrapped exception. */ + + private static final long serialVersionUID = 1736311265333034392L; + /** The wrapped exception. */ private Throwable wrapped; - + /** * Create a XPathException. - * + * * @param message The exception message. * @param wrapped The exception being the likely cause of this exception. */ - public XPathException(String message, Throwable wrapped) { + public XPathException(final String message, final Throwable wrapped) { super(message); - this.wrapped = wrapped; + this.wrapped = wrapped; } - - public XPathException(String string) { - super(string); -} -/** + public XPathException(final String string) { + super(string); + } + + /** * Return the wrapped exception. - * + * * @return The wrapped exception being the likely cause of this exception. */ public Throwable getWrapped() { @@ -68,9 +59,12 @@ public class XPathException extends RuntimeException { } /** + * Print error message. + * * @see java.lang.Throwable#printStackTrace(java.io.PrintStream) */ - public void printStackTrace(PrintStream s) { + @Override + public void printStackTrace(final PrintStream s) { super.printStackTrace(s); if (getWrapped() != null) { s.print("Caused by: "); @@ -79,14 +73,17 @@ public class XPathException extends RuntimeException { } /** + * Print error message. + * * @see java.lang.Throwable#printStackTrace(java.io.PrintWriter) */ - public void printStackTrace(PrintWriter s) { + @Override + public void printStackTrace(final PrintWriter s) { super.printStackTrace(s); if (getWrapped() != null) { s.print("Caused by: "); getWrapped().printStackTrace(s); } } - + } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/impl/data/Pair.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/impl/data/Pair.java index 1e2f6994..48a35cb7 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/impl/data/Pair.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/impl/data/Pair.java @@ -1,55 +1,51 @@ /******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ + package at.gv.egiz.eaaf.core.impl.data; -public class Pair { - private final P1 first; - private final P2 second; - - private Pair(final P1 newFirst, final P2 newSecond) { - this.first = newFirst; - this.second = newSecond; - } - - public P1 getFirst() { - return this.first; - } - - public P2 getSecond() { - return this.second; - } - - public static Pair newInstance(final P1 newFirst, final P2 newSecond) { - return new Pair(newFirst, newSecond); - } - - @Override - public String toString() { - return "[bPK-Value: " + getFirst() + " bPK-Type: " + getSecond() + "]"; - - } +import java.io.Serializable; + +public class Pair implements Serializable { + private static final long serialVersionUID = 1022855782082259449L; + private final P1 first; + private final P2 second; + + private Pair(final P1 newFirst, final P2 newSecond) { + this.first = newFirst; + this.second = newSecond; + } + + public P1 getFirst() { + return this.first; + } + + public P2 getSecond() { + return this.second; + } + + public static Pair newInstance(final P1 newFirst, final P2 newSecond) { + return new Pair<>(newFirst, newSecond); + } + + @Override + public String toString() { + return "[bPK-Value: " + getFirst() + " bPK-Type: " + getSecond() + "]"; + + } } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/impl/data/Trible.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/impl/data/Trible.java index 1aa61a87..597f0d1e 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/impl/data/Trible.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/impl/data/Trible.java @@ -1,24 +1,20 @@ /******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ /******************************************************************************* *******************************************************************************/ @@ -27,29 +23,30 @@ package at.gv.egiz.eaaf.core.impl.data; public class Trible { - private final P1 first; - private final P2 second; - private final P3 third; - - private Trible(final P1 newFirst, final P2 newSecond, final P3 newThird) { - this.first = newFirst; - this.second = newSecond; - this.third = newThird; - } - - public P1 getFirst() { - return this.first; - } - - public P2 getSecond() { - return this.second; - } - - public P3 getThird() { - return this.third; - } - - public static Trible newInstance(final P1 newFirst, final P2 newSecond, final P3 newThird) { - return new Trible(newFirst, newSecond, newThird); - } + private final P1 first; + private final P2 second; + private final P3 third; + + private Trible(final P1 newFirst, final P2 newSecond, final P3 newThird) { + this.first = newFirst; + this.second = newSecond; + this.third = newThird; + } + + public P1 getFirst() { + return this.first; + } + + public P2 getSecond() { + return this.second; + } + + public P3 getThird() { + return this.third; + } + + public static Trible newInstance(final P1 newFirst, final P2 newSecond, + final P3 newThird) { + return new Trible<>(newFirst, newSecond, newThird); + } } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/impl/logging/DummyStatusMessager.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/impl/logging/DummyStatusMessager.java index 19bc9951..6cb6d5e4 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/impl/logging/DummyStatusMessager.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/impl/logging/DummyStatusMessager.java @@ -1,61 +1,54 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.logging; import java.util.Arrays; - import at.gv.egiz.eaaf.core.api.IStatusMessenger; public class DummyStatusMessager implements IStatusMessenger { - @Override - public String getMessage(String messageId, Object[] parameters) { - return "No StatusMessager-Backend available! " - + "StatusCode:" + messageId - + " Params:" + Arrays.toString(parameters); - - } - - @Override - public String getMessageWithoutDefault(String messageId, Object[] parameters) { - return getMessage(messageId, parameters); - - } - - - @Override - public String getResponseErrorCode(Throwable throwable) { - return "No StatusMessager-Backend available!"; - - } - - @Override - public String mapInternalErrorToExternalError(String intErrorCode) { - return "No StatusCode Mapper available! StatusCode:" + intErrorCode; - - } + @Override + public String getMessage(final String messageId, final Object[] parameters) { + return "No StatusMessager-Backend available! " + "StatusCode:" + messageId + " Params:" + + Arrays.toString(parameters); + + } + + @Override + public String getMessageWithoutDefault(final String messageId, final Object[] parameters) { + return getMessage(messageId, parameters); + + } + + + @Override + public String getResponseErrorCode(final Throwable throwable) { + return "No StatusMessager-Backend available!"; + + } + + @Override + public String mapInternalErrorToExternalError(final String intErrorCode) { + return "No StatusCode Mapper available! StatusCode:" + intErrorCode; + + } } diff --git a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/impl/logging/LogMessageProviderFactory.java b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/impl/logging/LogMessageProviderFactory.java index eb21edb0..a768b1d2 100644 --- a/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/impl/logging/LogMessageProviderFactory.java +++ b/eaaf_core_api/src/main/java/at/gv/egiz/eaaf/core/impl/logging/LogMessageProviderFactory.java @@ -1,56 +1,56 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.logging; +import at.gv.egiz.eaaf.core.api.IStatusMessenger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import at.gv.egiz.eaaf.core.api.IStatusMessenger; - +/** + * Static Holder to get Spring-based messenger-implementation in non-Spring applications-code. + * + * @author tlenz + * + */ public class LogMessageProviderFactory { - private static final Logger log = LoggerFactory.getLogger(LogMessageProviderFactory.class); - private static IStatusMessenger internalMessager = new DummyStatusMessager(); - - /** - * Get the implementation specific StatusCode messager - * - * @return - */ - public static IStatusMessenger getMessager() { - return internalMessager; - - } - - /** - * Set the implementation specific status messanger. - * - * @param messanger - */ - public static void setStatusMessager(IStatusMessenger messanger) { - internalMessager = messanger; - log.info("Set StatusMessanger to '" + messanger.getClass().getName() + "'"); - - } + private static final Logger log = LoggerFactory.getLogger(LogMessageProviderFactory.class); + private static IStatusMessenger internalMessager = new DummyStatusMessager(); + + /** + * Get the implementation specific StatusCode messager. + * + * @return + */ + public static IStatusMessenger getMessager() { + return internalMessager; + + } + + /** + * Set the implementation specific status messanger. + * + * @param messanger Status messager implementation + */ + public static void setStatusMessager(final IStatusMessenger messanger) { + internalMessager = messanger; + log.info("Set StatusMessanger to '" + messanger.getClass().getName() + "'"); + + } } diff --git a/eaaf_core_utils/pom.xml b/eaaf_core_utils/pom.xml index adf8afa8..84ab46f5 100644 --- a/eaaf_core_utils/pom.xml +++ b/eaaf_core_utils/pom.xml @@ -1,17 +1,19 @@ - + 4.0.0 at.gv.egiz eaaf - 1.1.0-SNAPSHOT + 1.1.0-SNAPSHOT at.gv.egiz.eaaf eaaf_core_utils Utils for EAAF core components Core component Utils for identity managment implementations - + European Union Public License, version 1.2 (EUPL-1.2) @@ -28,74 +30,79 @@ https://www.egiz.gv.at - + UTF-8 - - - - at.gv.egiz.eaaf - eaaf_core_api - - - org.springframework - spring-webmvc - - - - org.slf4j - slf4j-api - - - org.apache.commons - commons-lang3 - - - org.apache.httpcomponents - httpclient - - - org.apache.httpcomponents - httpcore - - - com.google.code.findbugs - jsr305 - - - joda-time - joda-time - - - javax.servlet - javax.servlet-api - provided - - - - junit - junit - test - - - org.springframework - spring-test - test - - + + + at.gv.egiz.eaaf + eaaf_core_api + + + + org.springframework + spring-webmvc + + + + org.slf4j + slf4j-api + + + org.apache.commons + commons-lang3 + + + org.apache.httpcomponents + httpclient + + + org.apache.httpcomponents + httpcore + + + com.google.code.findbugs + jsr305 + + + joda-time + joda-time + + + javax.servlet + javax.servlet-api + provided + + + + junit + junit + test + + + org.springframework + spring-test + test + + + com.google.guava + guava + test + + - - - eaaf_core_utils - - - - src/main/resources - - - + + + eaaf_core_utils + + + + src/main/resources + + + org.apache.maven.plugins @@ -106,45 +113,45 @@ 1.8 - - - compile - testCompile - - + + + compile + testCompile + + - org.apache.maven.plugins - maven-jar-plugin - 3.1.0 - - - - test-jar - - - - - + org.apache.maven.plugins + maven-jar-plugin + 3.1.0 + + + + test-jar + + + + + - - maven-surefire-plugin - ${surefire.version} - - 1 - - - - org.apache.maven.surefire - surefire-junit47 - ${surefire.version} - - - - + + maven-surefire-plugin + ${surefire.version} + + 1 + + + + org.apache.maven.surefire + surefire-junit47 + ${surefire.version} + + + + - - + + diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/support/SecureRandomHolder.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/support/SecureRandomHolder.java index a297367f..8584d63f 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/support/SecureRandomHolder.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/idp/process/support/SecureRandomHolder.java @@ -1,61 +1,57 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.idp.process.support; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; /** - * Holder for a secure random instance following the initialization on demand holder design pattern. The secure random - * instance is a singleton that is initialized on first usage. - * + * Holder for a secure random instance following the initialization on demand holder design pattern. + * The secure random instance is a singleton that is initialized on first usage. + * * @author tknall - * + * */ public class SecureRandomHolder { - private SecureRandomHolder() { - } - - private static final SecureRandom SRND_INSTANCE; - static { - try { - SRND_INSTANCE = SecureRandom.getInstance("SHA1PRNG"); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException("Unable to instantiate SHA1PRNG.", e); - } - } - - /** - * Returns a secure random generator instance. - * @return The secure random instance. - */ - public static SecureRandom getInstance() { - return SecureRandomHolder.SRND_INSTANCE; - } - -} \ No newline at end of file + private SecureRandomHolder() { + + } + + private static final SecureRandom SRND_INSTANCE; + + static { + try { + SRND_INSTANCE = SecureRandom.getInstance("SHA1PRNG"); + } catch (final NoSuchAlgorithmException e) { + throw new RuntimeException("Unable to instantiate SHA1PRNG.", e); + } + } + + /** + * Returns a secure random generator instance. + * + * @return The secure random instance. + */ + public static SecureRandom getInstance() { + return SecureRandomHolder.SRND_INSTANCE; + } + +} diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/logging/SimpleStatusMessager.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/logging/SimpleStatusMessager.java index d36c79b9..5715a7b6 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/logging/SimpleStatusMessager.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/logging/SimpleStatusMessager.java @@ -1,44 +1,44 @@ package at.gv.egiz.eaaf.core.impl.logging; import java.text.MessageFormat; - import at.gv.egiz.eaaf.core.api.IStatusMessenger; /** - * Simple {@link IStatusMessenger} implementation that formats messages by using {@link MessageFormat} - * + * Simple {@link IStatusMessenger} implementation that formats messages by using. + * {@link MessageFormat} + * * @author tlenz * */ public class SimpleStatusMessager implements IStatusMessenger { - private static final String NOTSUPPORTED = "Error response-codes not supported"; - private static final String NULLMESSAGE = "No error-message provided"; - - @Override - public String getMessage(String messageId, Object[] parameters) { - return getMessageWithoutDefault(messageId, parameters); - - } - - @Override - public String getMessageWithoutDefault(String messageId, Object[] parameters) { - if (messageId != null) { - return MessageFormat.format(messageId, parameters); - - } - - return NULLMESSAGE; - } - - @Override - public String getResponseErrorCode(Throwable throwable) { - return NOTSUPPORTED; - } - - @Override - public String mapInternalErrorToExternalError(String intErrorCode) { - return NOTSUPPORTED; - } + private static final String NOTSUPPORTED = "Error response-codes not supported"; + private static final String NULLMESSAGE = "No error-message provided"; + + @Override + public String getMessage(final String messageId, final Object[] parameters) { + return getMessageWithoutDefault(messageId, parameters); + + } + + @Override + public String getMessageWithoutDefault(final String messageId, final Object[] parameters) { + if (messageId != null) { + return MessageFormat.format(messageId, parameters); + + } + + return NULLMESSAGE; + } + + @Override + public String getResponseErrorCode(final Throwable throwable) { + return NOTSUPPORTED; + } + + @Override + public String mapInternalErrorToExternalError(final String intErrorCode) { + return NOTSUPPORTED; + } } diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/ArrayUtils.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/ArrayUtils.java index 8585bc05..1da82f43 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/ArrayUtils.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/ArrayUtils.java @@ -1,44 +1,42 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. + */ + package at.gv.egiz.eaaf.core.impl.utils; import java.util.List; public class ArrayUtils { - /** - * Check if a String 's' is part of a List 'l' in qualsIgnoreCase mode - * - * @param s Search String - * @param l List of String elements - * @return true if 's' is in 'l', otherwise false - */ - public static boolean containsCaseInsensitive(String s, List l){ - if (l == null || s == null) - return false; - - return l.stream().anyMatch(x -> x.equalsIgnoreCase(s)); - + /** + * Check if a String 's' is part of a List 'l' in qualsIgnoreCase mode. + * + * @param s Search String + * @param l List of String elements + * @return true if 's' is in 'l', otherwise false + */ + public static boolean containsCaseInsensitive(final String s, final List l) { + if (l == null || s == null) { + return false; } + return l.stream().anyMatch(x -> x.equalsIgnoreCase(s)); + + } + } diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/DataURLBuilder.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/DataURLBuilder.java deleted file mode 100644 index a81fafbc..00000000 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/DataURLBuilder.java +++ /dev/null @@ -1,113 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * Copyright 2003 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ - - -package at.gv.egiz.eaaf.core.impl.utils; - -import org.apache.commons.lang3.StringUtils; - -import at.gv.egiz.eaaf.core.api.data.EAAFConstants; - -/** - * Builds a DataURL parameter meant for the security layer implementation - * to respond to. - * - * @author Paul Ivancsics - * @version $Id$ - */ -public class DataURLBuilder { - - /** - * Constructor for DataURLBuilder. - */ - public DataURLBuilder() { - super(); - } - - /** - * Constructs a data URL for VerifyIdentityLink or VerifyAuthenticationBlock, - * including the MOASessionID as a parameter. - * - * @param authBaseURL base URL (context path) of the MOA ID Authentication component, - * including a trailing '/' - * @param authServletName request part of the data URL - * @param pendingReqId sessionID to be included in the dataURL - * @return String - */ - public String buildDataURL(String authBaseURL, String authServletName, String pendingReqId) { - String dataURL; - if (!authBaseURL.endsWith("/")) - authBaseURL += "/"; - - if (authServletName.startsWith("/")) - authServletName = authServletName.substring(1); - - dataURL = authBaseURL + authServletName; - - if (StringUtils.isNotEmpty(pendingReqId)) - dataURL = addParameter(dataURL, EAAFConstants.PARAM_HTTP_TARGET_PENDINGREQUESTID, pendingReqId); - - return dataURL; - } - - /** - * Method addParameter. - * @param urlString represents the url - * @param paramname is the parameter to be added - * @param value is the value of that parameter - * @return String - */ - private String addParameter(String urlString, String paramname, String value) { - String url = urlString; - if (paramname != null) { - if (url.indexOf("?") < 0) - url += "?"; - else - url += "&"; - url += paramname + "=" + value; - } - return url; - } -} diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/DataUrlBuilder.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/DataUrlBuilder.java new file mode 100644 index 00000000..a72e07dd --- /dev/null +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/DataUrlBuilder.java @@ -0,0 +1,91 @@ +/* + * Copyright 2014 Federal Chancellery Austria MOA-ID has been developed in a cooperation between + * BRZ, the Federal Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. + */ + +package at.gv.egiz.eaaf.core.impl.utils; + +import org.apache.commons.lang3.StringUtils; + +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; + +/** + * Builds a DataURL parameter meant for the security layer implementation to respond to. + * + * @author Paul Ivancsics + * @version $Id$ + */ +public class DataUrlBuilder { + + /** + * Constructor for DataURLBuilder. + */ + public DataUrlBuilder() { + super(); + } + + /** + * Constructs a data URL for VerifyIdentityLink or + * VerifyAuthenticationBlock, including the MOASessionID as a parameter. + * + * @param authBaseUrl base URL (context path) of the MOA ID Authentication component, including a + * trailing '/' + * @param authServletName request part of the data URL + * @param pendingReqId sessionID to be included in the dataURL + * @return String + */ + public String buildDataUrl(String authBaseUrl, String authServletName, + final String pendingReqId) { + String dataUrl; + if (!authBaseUrl.endsWith("/")) { + authBaseUrl += "/"; + } + + if (authServletName.startsWith("/")) { + authServletName = authServletName.substring(1); + } + + dataUrl = authBaseUrl + authServletName; + + if (StringUtils.isNotEmpty(pendingReqId)) { + dataUrl = + addParameter(dataUrl, EAAFConstants.PARAM_HTTP_TARGET_PENDINGREQUESTID, pendingReqId); + } + + return dataUrl; + } + + /** + * Method addParameter. + * + * @param urlString represents the url + * @param paramname is the parameter to be added + * @param value is the value of that parameter + * @return String + */ + private String addParameter(final String urlString, final String paramname, final String value) { + String url = urlString; + if (paramname != null) { + if (url.indexOf("?") < 0) { + url += "?"; + } else { + url += "&"; + } + url += paramname + "=" + value; + } + return url; + } +} diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/FileUtils.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/FileUtils.java index 6ac51ac4..943d3dad 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/FileUtils.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/FileUtils.java @@ -1,29 +1,22 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. + */ + package at.gv.egiz.eaaf.core.impl.utils; @@ -38,22 +31,22 @@ import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; - import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FileUtils { - private static final Logger log = LoggerFactory.getLogger(FileUtils.class); - - + private static final Logger log = LoggerFactory.getLogger(FileUtils.class); + + /** * Reads a file, given by URL, into a byte array. + * * @param urlString file URL * @return file content * @throws IOException on any exception thrown */ - public static byte[] readURL(String urlString) throws IOException { + public static byte[] readUrl(final String urlString) throws IOException { final URL url = new URL(urlString); final InputStream in = new BufferedInputStream(url.openStream()); final byte[] content = StreamUtils.readStream(in); @@ -63,114 +56,142 @@ public class FileUtils { /** * Reads a file from a resource. + * * @param name resource name * @return file content as a byte array * @throws IOException on any exception thrown */ - public static byte[] readResource(String name) throws IOException { + public static byte[] readResource(final String name) throws IOException { final ClassLoader cl = FileUtils.class.getClassLoader(); final BufferedInputStream in = new BufferedInputStream(cl.getResourceAsStream(name)); final byte[] content = StreamUtils.readStream(in); in.close(); return content; } + /** * Reads a file from a resource. + * * @param name filename * @param encoding character encoding * @return file content * @throws IOException on any exception thrown */ - public static String readResource(String name, String encoding) throws IOException { + public static String readResource(final String name, final String encoding) throws IOException { final byte[] content = readResource(name); return new String(content, encoding); } - - - /** - * Returns the absolute URL of a given url which is relative to the parameter root - * @param url - * @param root - * @return String - * @throws MalformedURLException - */ - public static String makeAbsoluteURL(String url, URI root) throws MalformedURLException { - if (root != null) - return makeAbsoluteURL(url, root.toURL().toString()); - else - return makeAbsoluteURL(url, StringUtils.EMPTY); - - } - - /** - * Returns the absolute URL of a given url which is relative to the parameter root - * @param url - * @param root - * @return String - */ - public static String makeAbsoluteURL(String url, String root) { - //if url is relative to rootConfigFileDirName make it absolute - - log.trace("Making AbsoluteURL URL: " + url + " Root-Path: " + root); - - if (StringUtils.isEmpty(root)) - root = null; - - File keyFile; - String newURL = url; - - if(null == url) return null; - - if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("file:") - || url.startsWith("ftp:") || url.startsWith("classpath:")) { - return url; - - } else { - // check if absolute - if not make it absolute - keyFile = new File(url); - if (!keyFile.isAbsolute()) { - keyFile = new File(root, url); - - if (keyFile.toString().startsWith("file:")) - newURL = keyFile.toString(); - - else - newURL = keyFile.toURI().toString(); - - } - return newURL; - } - } - - - private static void copy( InputStream fis, OutputStream fos ) - { - try - { - final byte[] buffer = new byte[ 0xFFFF ]; - for ( int len; (len = fis.read(buffer)) != -1; ) - fos.write( buffer, 0, len ); - } - catch( final IOException e ) { - System.err.println( e ); - } - finally { - if ( fis != null ) - try { fis.close(); } catch ( final IOException e ) { e.printStackTrace(); } - if ( fos != null ) - try { fos.close(); } catch ( final IOException e ) { e.printStackTrace(); } - } - } - - public static void copyFile(File src, File dest) - { - try - { - copy( new FileInputStream( src ), new FileOutputStream( dest ) ); - } - catch( final IOException e ) { - e.printStackTrace(); - } - } - + + + /** + * Returns the absolute URL of a given url which is relative to the parameter root. + * + * @param url Filepath + * @param root configuration root context + * @return absolut filepath + * @throws MalformedURLException In case of a filepath error + */ + public static String makeAbsoluteUrl(final String url, final URI root) + throws MalformedURLException { + if (root != null) { + return makeAbsoluteUrl(url, root.toURL().toString()); + } else { + return makeAbsoluteUrl(url, StringUtils.EMPTY); + } + + } + + /** + * Returns the absolute URL of a given url which is relative to the parameter root. + * + * @param url Filepath + * @param root configuration root context + * @return absolut filepath + */ + public static String makeAbsoluteUrl(final String url, String root) { + // if url is relative to rootConfigFileDirName make it absolute + + log.trace("Making AbsoluteURL URL: " + url + " Root-Path: " + root); + + if (StringUtils.isEmpty(root)) { + root = null; + } + + File keyFile; + String newUrl = url; + + if (null == url) { + return null; + } + + if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("file:") + || url.startsWith("ftp:") || url.startsWith("classpath:")) { + return url; + + } else { + // check if absolute - if not make it absolute + keyFile = new File(url); + if (!keyFile.isAbsolute()) { + keyFile = new File(root, url); + + if (keyFile.toString().startsWith("file:")) { + newUrl = keyFile.toString(); + } else { + newUrl = keyFile.toURI().toString(); + } + + } + return newUrl; + } + } + + + private static void copy(final InputStream fis, final OutputStream fos) { + try { + final byte[] buffer = new byte[0xFFFF]; + for (int len; (len = fis.read(buffer)) != -1;) { + fos.write(buffer, 0, len); + } + } catch (final IOException e) { + System.err.println(e); + + } + } + + /** + * Copy file from source to destination. + * + * @param src File source + * @param dest file destination + */ + public static void copyFile(final File src, final File dest) { + InputStream fis = null; + OutputStream fos = null; + + try { + fis = new FileInputStream(src); + fos = new FileOutputStream(src); + copy(fis, fos); + + } catch (final IOException e) { + e.printStackTrace(); + + } finally { + if (fis != null) { + try { + fis.close(); + } catch (final IOException e) { + e.printStackTrace(); + } + } + if (fos != null) { + try { + fos.close(); + } catch (final IOException e) { + e.printStackTrace(); + } + } + } + } + } diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/HTTPUtils.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/HTTPUtils.java deleted file mode 100644 index cf1abaa7..00000000 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/HTTPUtils.java +++ /dev/null @@ -1,178 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * Copyright 2003 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ - - -package at.gv.egiz.eaaf.core.impl.utils; - -import javax.servlet.http.HttpServletRequest; - -import org.apache.commons.lang3.StringUtils; - - -/** - * - * @author Rudolf Schamberger - * - */ -public class HTTPUtils { - -// /** -// * Utility used to obtainin correct encoded HTTP content. -// * Reads a given Content adressed by HTTP-URL into String. -// * Content encoding is considered by using the Content-Type HTTP header charset value. -// * @param URL HTTP URL to read from. -// * @return String representation of content -// * @throws IOException on data-reading problems -// */ -// public static String readHttpURL(String URL) -// throws IOException { -// -// URL url = new URL(URL); -// HttpURLConnection conn = (HttpURLConnection)url.openConnection(); -// conn.setRequestMethod("GET"); -// String contentType = conn.getContentType(); -// RE regExp = null; -// try { -// regExp = new RE("(;.*charset=)(\"*)(.*[^\"])"); -// } catch (RESyntaxException e) { -// //RESyntaxException is not possible = expr. is costant -// } -// boolean charsetSupplied = regExp.match(contentType); -// String encoding = "ISO-8859-1"; //default HTTP encoding -// if (charsetSupplied) { -// encoding = regExp.getParen(3); -// } -// InputStream instream = new BufferedInputStream(conn.getInputStream()); -// InputStreamReader isr = new InputStreamReader(instream, encoding); -// Reader in = new BufferedReader(isr); -// int ch; -// StringBuffer buffer = new StringBuffer(); -// while ((ch = in.read()) > -1) { -// buffer.append((char)ch); -// } -// in.close(); -// conn.disconnect(); -// return buffer.toString(); -// } - - /** - * Helper method to retrieve server URL including context path - * @param request HttpServletRequest - * @return Server URL including context path (e.g. http://localhost:8443/moa-id-auth - */ - public static String getBaseURL(HttpServletRequest request) { - StringBuffer buffer = new StringBuffer(getServerURL(request)); - - // add context path if available - String contextPath = request.getContextPath(); - if (!StringUtils.isEmpty(contextPath)) { - buffer.append(contextPath); - } - - return buffer.toString(); - } - - /** - * Helper method to retrieve server URL - * @param request HttpServletRequest - * @return Server URL (e.g. http://localhost:8443) - */ - public static String getServerURL(HttpServletRequest request) { - StringBuffer buffer = new StringBuffer(); - - // get protocol - String protocol = request.getScheme(); - buffer.append(protocol).append("://"); - - // server name - buffer.append(request.getServerName()); - - // add port if necessary - int port = request.getServerPort(); - if ((protocol.equals("http") && port != 80) || (protocol.equals("https") && port != 443)) { - buffer.append(':'); - buffer.append(port); - } - - return buffer.toString(); - } - - /** - * Extract the IDP PublicURLPrefix from authrequest - * - * @param req HttpServletRequest - * @return PublicURLPrefix which ends always without / - */ - public static String extractAuthURLFromRequest(HttpServletRequest req) { - String authURL = req.getScheme() + "://" + req.getServerName(); - if ((req.getScheme().equalsIgnoreCase("https") && req.getServerPort()!=443) || (req.getScheme().equalsIgnoreCase("http") && req.getServerPort()!=80)) { - authURL = authURL.concat(":" + req.getServerPort()); - } - authURL = authURL.concat(req.getContextPath()); - return authURL; - - } - - /** - * Extract the IDP requested URL from authrequest - * - * @param req HttpServletRequest - * @return RequestURL which ends always without / - */ - public static String extractAuthServletPathFromRequest(HttpServletRequest req) { - return extractAuthURLFromRequest(req).concat(req.getServletPath()); - - } - - public static String addURLParameter(String url, String paramname, - String paramvalue) { - String param = paramname + "=" + paramvalue; - if (url.indexOf("?") < 0) - return url + "?" + param; - else - return url + "&" + param; - } - -} diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/HttpClientFactory.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/HttpClientFactory.java index a8cfa7c1..4e8be52e 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/HttpClientFactory.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/HttpClientFactory.java @@ -8,11 +8,11 @@ import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; - import javax.annotation.PostConstruct; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; - +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; @@ -44,339 +44,378 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; - public class HttpClientFactory implements IHttpClientFactory { - private static final Logger log = LoggerFactory.getLogger(HttpClientFactory.class); - @Autowired(required=true) private IConfiguration basicConfig; - @Autowired(required=true) ResourceLoader resourceLoader; - - public static final String PROP_CONFIG_CLIENT_HTTP_CONNECTION_POOL_USE = "client.http.connection.pool.use"; - public static final String PROP_CONFIG_CLIENT_HTTP_CONNECTION_POOL_MAXTOTAL = "client.http.connection.pool.maxtotal"; - public static final String PROP_CONFIG_CLIENT_HTTP_CONNECTION_POOL_MAXPERROUTE = "client.http.connection.pool.maxperroute"; - public static final String PROP_CONFIG_CLIENT_HTTP_CONNECTION_TIMEOUT_SOCKET = "client.http.connection.timeout.socket"; - public static final String PROP_CONFIG_CLIENT_HTTP_CONNECTION_TIMEOUT_CONNECTION = "client.http.connection.timeout.connection"; - public static final String PROP_CONFIG_CLIENT_HTTP_CONNECTION_TIMEOUT_REQUEST = "client.http.connection.timeout.request"; - public static final String PROP_CONFIG_CLIENT_HTTP_SSL_HOSTNAMEVERIFIER_TRUSTALL = "client.http.ssl.hostnameverifier.trustall"; - - public static final String PROP_CONFIG_CLIENT_MODE = "client.authmode"; - public static final String PROP_CONFIG_CLIENT_AUTH_HTTP_USERNAME = "client.auth.http.username"; - public static final String PROP_CONFIG_CLIENT_AUTH_HTTP_PASSORD = "client.auth.http.password"; - public static final String PROP_CONFIG_CLIENT_AUTH_SSL_KEYSTORE_PATH = "client.auth.ssl.keystore.path"; - public static final String PROP_CONFIG_CLIENT_AUTH_SSL_KEYSTORE_PASSORD = "client.auth.ssl.keystore.password"; - public static final String PROP_CONFIG_CLIENT_AUTH_SSL_KEYSTORE_TYPE = "client.auth.ssl.keystore.type"; - public static final String PROP_CONFIG_CLIENT_AUTH_SSL_KEY_PASSWORD = "client.auth.ssl.key.password"; - public static final String PROP_CONFIG_CLIENT_AUTH_SSL_KEY_ALIAS = "client.auth.ssl.key.alias"; - - // default configuration values - public static final String DEFAULT_CONFIG_CLIENT_HTTP_CONNECTION_TIMEOUT_SOCKET = "15"; - public static final String DEFAULT_CONFIG_CLIENT_HTTP_CONNECTION_TIMEOUT_CONNECTION = "15"; - public static final String DEFAULT_CONFIG_CLIENT_HTTP_CONNECTION_TIMEOUT_REQUEST = "30"; - public static final String DEFAULT_CONFIG_CLIENT_HTTP_CONNECTION_POOL_MAXTOTAL = "500"; - public static final String DEFAULT_CONFIG_CLIENT_HTTP_CONNECTION_POOL_MAXPERROUTE = "100"; - - public enum ClientAuthMode { - NONE("none"), - PASSWORD("password"), - SSL("ssl"); - - private final String mode; - - private ClientAuthMode(String mode) { - this.mode = mode; - } - - /** - * Get the PVP mode - * - * @return - */ - public String getMode() { - return this.mode; - } - - public static ClientAuthMode fromString(String s) { - try { - return ClientAuthMode.valueOf(s.toUpperCase()); - - } catch (IllegalArgumentException|NullPointerException e) { - return null; - } - } - - @Override - public String toString() { - return getMode(); - - } - - }; - - public enum KeyStoreType { - PKCS12("pkcs12"), - JKS("jks"); - - private final String type; - - private KeyStoreType (String type) { - this.type = type; - } - - /** - * Get the PVP mode - * - * @return - */ - public String getType() { - return this.type; - } - - public static KeyStoreType fromString(String s) { - try { - return KeyStoreType.valueOf(s.toUpperCase()); - - } catch (IllegalArgumentException|NullPointerException e) { - return null; - } - } - - @Override - public String toString() { - return getType(); - - } - - }; - - private HttpClientBuilder httpClientBuilder = null; - - /* (non-Javadoc) - * @see at.gv.egiz.eaaf.core.impl.utils.IHttpClientFactory#getHttpClient() - */ - @Override - public CloseableHttpClient getHttpClient() { - return getHttpClient(true); - - } - - @Override - public CloseableHttpClient getHttpClient(boolean followRedirects) { - RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); - if (!followRedirects) - redirectStrategy = new RedirectStrategy() { - - @Override - public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) - throws ProtocolException { - return false; - } - - @Override - public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) - throws ProtocolException { - return null; - } - }; - - return httpClientBuilder - .setRedirectStrategy(redirectStrategy) - .build(); - - } - - @PostConstruct - private void initalize() { - //initialize http client - log.trace("Initializing HTTP Client-builder ... "); - httpClientBuilder = HttpClients.custom(); - - //set default request configuration - final RequestConfig requestConfig = RequestConfig.custom() - .setConnectTimeout(Integer.valueOf(basicConfig.getBasicConfiguration( - PROP_CONFIG_CLIENT_HTTP_CONNECTION_TIMEOUT_CONNECTION, - DEFAULT_CONFIG_CLIENT_HTTP_CONNECTION_TIMEOUT_CONNECTION)) * 1000) - .setConnectionRequestTimeout(Integer.valueOf(basicConfig.getBasicConfiguration( - PROP_CONFIG_CLIENT_HTTP_CONNECTION_TIMEOUT_REQUEST, - DEFAULT_CONFIG_CLIENT_HTTP_CONNECTION_TIMEOUT_REQUEST)) * 1000) - .setSocketTimeout(Integer.valueOf(basicConfig.getBasicConfiguration( - PROP_CONFIG_CLIENT_HTTP_CONNECTION_TIMEOUT_SOCKET, - DEFAULT_CONFIG_CLIENT_HTTP_CONNECTION_TIMEOUT_SOCKET)) * 1000) - .build(); - httpClientBuilder.setDefaultRequestConfig(requestConfig); - - ClientAuthMode clientAuthMode = ClientAuthMode.fromString( - basicConfig.getBasicConfiguration(PROP_CONFIG_CLIENT_MODE, ClientAuthMode.NONE.getMode())); - if (clientAuthMode == null) { - log.warn("Can Not parse ClientAuthMode! Set mode to default value"); - clientAuthMode = ClientAuthMode.NONE; - - } - - //inject basic http authentication if required - log.info("Client authentication-mode is set to: {}", clientAuthMode); - injectBasicAuthenticationIfRequired(clientAuthMode); - - //inject authentication if required - final LayeredConnectionSocketFactory sslConnectionFactory = getSSLContext(clientAuthMode); - - //set pool connection if required - injectConnectionPoolIfRequired(sslConnectionFactory); - - - } - - private void injectBasicAuthenticationIfRequired(ClientAuthMode clientAuthMode) { - if (clientAuthMode.equals(ClientAuthMode.PASSWORD)) { - final CredentialsProvider provider = new BasicCredentialsProvider(); - - final String username = basicConfig.getBasicConfiguration(PROP_CONFIG_CLIENT_AUTH_HTTP_USERNAME); - final String password = basicConfig.getBasicConfiguration(PROP_CONFIG_CLIENT_AUTH_HTTP_PASSORD); - - if (StringUtils.isEmpty(username)) { - log.warn("Http basic authentication was activated but NOT username was set!"); - - } - - log.trace("Injecting basic authentication with username: {} and password: {}", username, password); - final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); - provider.setCredentials(AuthScope.ANY, credentials); - httpClientBuilder.setDefaultCredentialsProvider(provider); - log.info("Basic http authentication was injected with username: {}", username); - - } else { - log.trace("Injection of Http Basic authentication was skipped"); - - } - - } - - private SSLContext buildSSLContextWithSSLClientAuthentication() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, EAAFConfigurationException { - log.trace("Injecting SSL client-authentication into http client ... "); - final KeyStore keystore = getSSLAuthKeyStore(); - final String keyPasswordString = basicConfig.getBasicConfiguration(PROP_CONFIG_CLIENT_AUTH_SSL_KEY_PASSWORD); - log.trace("Open SSL Client-Auth keystore with password: {}", keyPasswordString); - final char[] keyPassword = (keyPasswordString == null) ? StringUtils.EMPTY.toCharArray() : keyPasswordString.toCharArray(); - return SSLContexts.custom().loadKeyMaterial(keystore, keyPassword).build(); - - } - - private KeyStore getSSLAuthKeyStore() throws EAAFConfigurationException { - final KeyStoreType keyStoreType = KeyStoreType.fromString( - basicConfig.getBasicConfiguration(PROP_CONFIG_CLIENT_AUTH_SSL_KEYSTORE_TYPE, KeyStoreType.PKCS12.getType())); - final String localKeyStorePath = basicConfig.getBasicConfiguration(PROP_CONFIG_CLIENT_AUTH_SSL_KEYSTORE_PATH, StringUtils.EMPTY); - final String keyStorePassword = basicConfig.getBasicConfiguration(PROP_CONFIG_CLIENT_AUTH_SSL_KEYSTORE_PASSORD, StringUtils.EMPTY); - - try { - log.debug("Open keyStore with type: {}", keyStoreType); - KeyStore clientStore; - if (keyStoreType.equals(KeyStoreType.PKCS12)) { - clientStore = KeyStore.getInstance("pkcs12"); - } else { - clientStore = KeyStore.getInstance("JKS"); - } - - - log.debug("Read keyStore path: {} from configuration", localKeyStorePath); - if (StringUtils.isNotEmpty(localKeyStorePath)) { - final String absFilePath = FileUtils.makeAbsoluteURL(localKeyStorePath, basicConfig.getConfigurationRootDirectory()); - final Resource ressource = resourceLoader.getResource(absFilePath); - final InputStream is = ressource.getInputStream(); - log.trace("Load keyStore: {} with password: {}", absFilePath, keyStorePassword); - clientStore.load(is, keyStorePassword.toCharArray()); - is.close(); - - return clientStore; - - } else { - log.warn("Path to keyStore for SSL Client-Authentication is empty or null"); - throw new EAAFConfigurationException("Path to keyStore for SSL Client-Authentication is empty or null", new Object[] {}); - - } - - } catch (final KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) { - log.warn("Can NOT read keyStore: {} from filesystem", localKeyStorePath, null, e); - throw new EAAFConfigurationException("Can NOT read keyStore: {} from filesystem", new Object[] {localKeyStorePath}, e); - - } - - } - - private LayeredConnectionSocketFactory getSSLContext(ClientAuthMode clientAuthMode) { - SSLContext sslContext = null; - try { - if (clientAuthMode.equals(ClientAuthMode.SSL)) { - sslContext = buildSSLContextWithSSLClientAuthentication(); - - } else { - log.trace("Initializing default SSL Context ... "); - sslContext = SSLContext.getDefault(); - - } - - //set hostname verifier - HostnameVerifier hostnameVerifier = null; - if (basicConfig.getBasicConfigurationBoolean( - PROP_CONFIG_CLIENT_HTTP_SSL_HOSTNAMEVERIFIER_TRUSTALL, - false)) { - hostnameVerifier = new NoopHostnameVerifier(); - log.warn("HTTP client-builder deactivates SSL Host-name verification!"); - - } - - final LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext , hostnameVerifier); - - return sslSocketFactory; - - } catch (final NoSuchAlgorithmException | KeyManagementException | UnrecoverableKeyException | KeyStoreException | EAAFConfigurationException e) { - log.warn("HTTP client-builder can NOT initialze SSL-Context", e); - - } - - log.info("HTTP client-builder successfuly initialized"); - return null; - - } - - private void injectConnectionPoolIfRequired(LayeredConnectionSocketFactory sslConnectionFactory) { - if (basicConfig.getBasicConfigurationBoolean( - PROP_CONFIG_CLIENT_HTTP_CONNECTION_POOL_USE, - true)) { - PoolingHttpClientConnectionManager pool; - - //set socketFactoryRegistry if SSLConnectionFactory is Set - if (sslConnectionFactory != null) { - final Registry socketFactoryRegistry = RegistryBuilder.create() - .register("http", PlainConnectionSocketFactory.getSocketFactory()) - .register("https", sslConnectionFactory) - .build(); - log.trace("Inject SSLSocketFactory into pooled connection"); - pool = new PoolingHttpClientConnectionManager(socketFactoryRegistry); - - } else { - pool = new PoolingHttpClientConnectionManager(); - - } - - pool.setDefaultMaxPerRoute(Integer.valueOf(basicConfig.getBasicConfiguration( - PROP_CONFIG_CLIENT_HTTP_CONNECTION_POOL_MAXPERROUTE, - DEFAULT_CONFIG_CLIENT_HTTP_CONNECTION_POOL_MAXPERROUTE))); - pool.setMaxTotal(Integer.valueOf(basicConfig.getBasicConfiguration( - PROP_CONFIG_CLIENT_HTTP_CONNECTION_POOL_MAXTOTAL, - DEFAULT_CONFIG_CLIENT_HTTP_CONNECTION_POOL_MAXTOTAL))); - - httpClientBuilder.setConnectionManager(pool); - log.debug("Initalize http-client pool with, maxTotal: {} maxPerRoute: {}", pool.getMaxTotal(), pool.getDefaultMaxPerRoute()); - - } else if (sslConnectionFactory != null) { - log.trace("Inject SSLSocketFactory without connection pool"); - httpClientBuilder.setSSLSocketFactory(sslConnectionFactory ); - - } - - - } - - - + private static final Logger log = LoggerFactory.getLogger(HttpClientFactory.class); + @Autowired(required = true) + private IConfiguration basicConfig; + @Autowired(required = true) + ResourceLoader resourceLoader; + + public static final String PROP_CONFIG_CLIENT_HTTP_CONNECTION_POOL_USE = + "client.http.connection.pool.use"; + public static final String PROP_CONFIG_CLIENT_HTTP_CONNECTION_POOL_MAXTOTAL = + "client.http.connection.pool.maxtotal"; + public static final String PROP_CONFIG_CLIENT_HTTP_CONNECTION_POOL_MAXPERROUTE = + "client.http.connection.pool.maxperroute"; + public static final String PROP_CONFIG_CLIENT_HTTP_CONNECTION_TIMEOUT_SOCKET = + "client.http.connection.timeout.socket"; + public static final String PROP_CONFIG_CLIENT_HTTP_CONNECTION_TIMEOUT_CONNECTION = + "client.http.connection.timeout.connection"; + public static final String PROP_CONFIG_CLIENT_HTTP_CONNECTION_TIMEOUT_REQUEST = + "client.http.connection.timeout.request"; + public static final String PROP_CONFIG_CLIENT_HTTP_SSL_HOSTNAMEVERIFIER_TRUSTALL = + "client.http.ssl.hostnameverifier.trustall"; + + public static final String PROP_CONFIG_CLIENT_MODE = "client.authmode"; + public static final String PROP_CONFIG_CLIENT_AUTH_HTTP_USERNAME = "client.auth.http.username"; + public static final String PROP_CONFIG_CLIENT_AUTH_HTTP_PASSORD = "client.auth.http.password"; + public static final String PROP_CONFIG_CLIENT_AUTH_SSL_KEYSTORE_PATH = + "client.auth.ssl.keystore.path"; + public static final String PROP_CONFIG_CLIENT_AUTH_SSL_KEYSTORE_PASSORD = + "client.auth.ssl.keystore.password"; + public static final String PROP_CONFIG_CLIENT_AUTH_SSL_KEYSTORE_TYPE = + "client.auth.ssl.keystore.type"; + public static final String PROP_CONFIG_CLIENT_AUTH_SSL_KEY_PASSWORD = + "client.auth.ssl.key.password"; + public static final String PROP_CONFIG_CLIENT_AUTH_SSL_KEY_ALIAS = "client.auth.ssl.key.alias"; + + // default configuration values + public static final String DEFAULT_CONFIG_CLIENT_HTTP_CONNECTION_TIMEOUT_SOCKET = "15"; + public static final String DEFAULT_CONFIG_CLIENT_HTTP_CONNECTION_TIMEOUT_CONNECTION = "15"; + public static final String DEFAULT_CONFIG_CLIENT_HTTP_CONNECTION_TIMEOUT_REQUEST = "30"; + public static final String DEFAULT_CONFIG_CLIENT_HTTP_CONNECTION_POOL_MAXTOTAL = "500"; + public static final String DEFAULT_CONFIG_CLIENT_HTTP_CONNECTION_POOL_MAXPERROUTE = "100"; + + public enum ClientAuthMode { + NONE("none"), PASSWORD("password"), SSL("ssl"); + + private final String mode; + + private ClientAuthMode(final String mode) { + this.mode = mode; + } + + /** + * Get the PVP mode. + * + * @return + */ + public String getMode() { + return this.mode; + } + + /** + * Get http-client authentication mode from String representation. + * + * @param s Config parameter + * @return + */ + public static ClientAuthMode fromString(final String s) { + try { + return ClientAuthMode.valueOf(s.toUpperCase()); + + } catch (IllegalArgumentException | NullPointerException e) { + return null; + } + } + + @Override + public String toString() { + return getMode(); + + } + + } + + public enum KeyStoreType { + PKCS12("pkcs12"), JKS("jks"); + + private final String type; + + private KeyStoreType(final String type) { + this.type = type; + } + + /** + * Get the KeyStore type. + * + * @return + */ + public String getType() { + return this.type; + } + + /** + * Get Keystore type from configuration. + * + * @param s String representation for keyStore type + * @return + */ + public static KeyStoreType fromString(final String s) { + try { + return KeyStoreType.valueOf(s.toUpperCase()); + + } catch (IllegalArgumentException | NullPointerException e) { + return null; + } + } + + @Override + public String toString() { + return getType(); + + } + + } + + private HttpClientBuilder httpClientBuilder = null; + + /* + * (non-Javadoc) + * + * @see at.gv.egiz.eaaf.core.impl.utils.IHttpClientFactory#getHttpClient() + */ + @Override + public CloseableHttpClient getHttpClient() { + return getHttpClient(true); + + } + + @Override + public CloseableHttpClient getHttpClient(final boolean followRedirects) { + RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); + if (!followRedirects) { + redirectStrategy = new RedirectStrategy() { + + @Override + public boolean isRedirected(final HttpRequest request, final HttpResponse response, + final HttpContext context) throws ProtocolException { + return false; + } + + @Override + public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response, + final HttpContext context) throws ProtocolException { + return null; + } + }; + } + + return httpClientBuilder.setRedirectStrategy(redirectStrategy).build(); + + } + + @PostConstruct + private void initalize() { + // initialize http client + log.trace("Initializing HTTP Client-builder ... "); + httpClientBuilder = HttpClients.custom(); + + // set default request configuration + final RequestConfig requestConfig = + RequestConfig.custom() + .setConnectTimeout( + Integer.parseInt(basicConfig.getBasicConfiguration( + PROP_CONFIG_CLIENT_HTTP_CONNECTION_TIMEOUT_CONNECTION, + DEFAULT_CONFIG_CLIENT_HTTP_CONNECTION_TIMEOUT_CONNECTION)) * 1000) + .setConnectionRequestTimeout(Integer.parseInt(basicConfig.getBasicConfiguration( + PROP_CONFIG_CLIENT_HTTP_CONNECTION_TIMEOUT_REQUEST, + DEFAULT_CONFIG_CLIENT_HTTP_CONNECTION_TIMEOUT_REQUEST)) * 1000) + .setSocketTimeout(Integer.parseInt( + basicConfig.getBasicConfiguration(PROP_CONFIG_CLIENT_HTTP_CONNECTION_TIMEOUT_SOCKET, + DEFAULT_CONFIG_CLIENT_HTTP_CONNECTION_TIMEOUT_SOCKET)) + * 1000) + .build(); + httpClientBuilder.setDefaultRequestConfig(requestConfig); + + ClientAuthMode clientAuthMode = ClientAuthMode.fromString( + basicConfig.getBasicConfiguration(PROP_CONFIG_CLIENT_MODE, ClientAuthMode.NONE.getMode())); + if (clientAuthMode == null) { + log.warn("Can Not parse ClientAuthMode! Set mode to default value"); + clientAuthMode = ClientAuthMode.NONE; + + } + + // inject basic http authentication if required + log.info("Client authentication-mode is set to: {}", clientAuthMode); + injectBasicAuthenticationIfRequired(clientAuthMode); + + // inject authentication if required + final LayeredConnectionSocketFactory sslConnectionFactory = getSslContext(clientAuthMode); + + // set pool connection if required + injectConnectionPoolIfRequired(sslConnectionFactory); + + + } + + private void injectBasicAuthenticationIfRequired(final ClientAuthMode clientAuthMode) { + if (clientAuthMode.equals(ClientAuthMode.PASSWORD)) { + final CredentialsProvider provider = new BasicCredentialsProvider(); + + final String username = + basicConfig.getBasicConfiguration(PROP_CONFIG_CLIENT_AUTH_HTTP_USERNAME); + final String password = + basicConfig.getBasicConfiguration(PROP_CONFIG_CLIENT_AUTH_HTTP_PASSORD); + + if (StringUtils.isEmpty(username)) { + log.warn("Http basic authentication was activated but NOT username was set!"); + + } + + log.trace("Injecting basic authentication with username: {} and password: {}", username, + password); + final UsernamePasswordCredentials credentials = + new UsernamePasswordCredentials(username, password); + provider.setCredentials(AuthScope.ANY, credentials); + httpClientBuilder.setDefaultCredentialsProvider(provider); + log.info("Basic http authentication was injected with username: {}", username); + + } else { + log.trace("Injection of Http Basic authentication was skipped"); + + } + + } + + private SSLContext buildSslContextWithSslClientAuthentication() + throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, + KeyStoreException, EaafConfigurationException { + log.trace("Injecting SSL client-authentication into http client ... "); + final KeyStore keystore = getSslAuthKeyStore(); + final String keyPasswordString = + basicConfig.getBasicConfiguration(PROP_CONFIG_CLIENT_AUTH_SSL_KEY_PASSWORD); + log.trace("Open SSL Client-Auth keystore with password: {}", keyPasswordString); + final char[] keyPassword = (keyPasswordString == null) ? StringUtils.EMPTY.toCharArray() + : keyPasswordString.toCharArray(); + return SSLContexts.custom().loadKeyMaterial(keystore, keyPassword).build(); + + } + + private KeyStore getSslAuthKeyStore() throws EaafConfigurationException { + final KeyStoreType keyStoreType = KeyStoreType.fromString(basicConfig.getBasicConfiguration( + PROP_CONFIG_CLIENT_AUTH_SSL_KEYSTORE_TYPE, KeyStoreType.PKCS12.getType())); + final String localKeyStorePath = basicConfig + .getBasicConfiguration(PROP_CONFIG_CLIENT_AUTH_SSL_KEYSTORE_PATH, StringUtils.EMPTY); + final String keyStorePassword = basicConfig + .getBasicConfiguration(PROP_CONFIG_CLIENT_AUTH_SSL_KEYSTORE_PASSORD, StringUtils.EMPTY); + + try { + log.debug("Open keyStore with type: {}", keyStoreType); + KeyStore clientStore; + if (keyStoreType.equals(KeyStoreType.PKCS12)) { + clientStore = KeyStore.getInstance("pkcs12"); + } else { + clientStore = KeyStore.getInstance("JKS"); + } + + + log.debug("Read keyStore path: {} from configuration", localKeyStorePath); + if (StringUtils.isNotEmpty(localKeyStorePath)) { + final String absFilePath = FileUtils.makeAbsoluteUrl(localKeyStorePath, + basicConfig.getConfigurationRootDirectory()); + final Resource ressource = resourceLoader.getResource(absFilePath); + final InputStream is = ressource.getInputStream(); + log.trace("Load keyStore: {} with password: {}", absFilePath, keyStorePassword); + clientStore.load(is, keyStorePassword.toCharArray()); + is.close(); + + return clientStore; + + } else { + log.warn("Path to keyStore for SSL Client-Authentication is empty or null"); + throw new EaafConfigurationException( + "Path to keyStore for SSL Client-Authentication is empty or null", new Object[] {}); + + } + + } catch (final KeyStoreException | NoSuchAlgorithmException | CertificateException + | IOException e) { + log.warn("Can NOT read keyStore: {} from filesystem", localKeyStorePath, null, e); + throw new EaafConfigurationException("Can NOT read keyStore: {} from filesystem", + new Object[] {localKeyStorePath}, e); + + } + + } + + private LayeredConnectionSocketFactory getSslContext(final ClientAuthMode clientAuthMode) { + SSLContext sslContext = null; + try { + if (clientAuthMode.equals(ClientAuthMode.SSL)) { + sslContext = buildSslContextWithSslClientAuthentication(); + + } else { + log.trace("Initializing default SSL Context ... "); + sslContext = SSLContext.getDefault(); + + } + + // set hostname verifier + HostnameVerifier hostnameVerifier = null; + if (basicConfig.getBasicConfigurationBoolean( + PROP_CONFIG_CLIENT_HTTP_SSL_HOSTNAMEVERIFIER_TRUSTALL, false)) { + hostnameVerifier = new NoopHostnameVerifier(); + log.warn("HTTP client-builder deactivates SSL Host-name verification!"); + + } + + final LayeredConnectionSocketFactory sslSocketFactory = + new SSLConnectionSocketFactory(sslContext, hostnameVerifier); + + return sslSocketFactory; + + } catch (final NoSuchAlgorithmException | KeyManagementException | UnrecoverableKeyException + | KeyStoreException | EaafConfigurationException e) { + log.warn("HTTP client-builder can NOT initialze SSL-Context", e); + + } + + log.info("HTTP client-builder successfuly initialized"); + return null; + + } + + private void injectConnectionPoolIfRequired( + final LayeredConnectionSocketFactory sslConnectionFactory) { + if (basicConfig.getBasicConfigurationBoolean(PROP_CONFIG_CLIENT_HTTP_CONNECTION_POOL_USE, + true)) { + PoolingHttpClientConnectionManager pool; + + // set socketFactoryRegistry if SSLConnectionFactory is Set + if (sslConnectionFactory != null) { + final Registry socketFactoryRegistry = + RegistryBuilder.create() + .register("http", PlainConnectionSocketFactory.getSocketFactory()) + .register("https", sslConnectionFactory).build(); + log.trace("Inject SSLSocketFactory into pooled connection"); + pool = new PoolingHttpClientConnectionManager(socketFactoryRegistry); + + } else { + pool = new PoolingHttpClientConnectionManager(); + + } + + pool.setDefaultMaxPerRoute(Integer.parseInt( + basicConfig.getBasicConfiguration(PROP_CONFIG_CLIENT_HTTP_CONNECTION_POOL_MAXPERROUTE, + DEFAULT_CONFIG_CLIENT_HTTP_CONNECTION_POOL_MAXPERROUTE))); + pool.setMaxTotal(Integer.parseInt( + basicConfig.getBasicConfiguration(PROP_CONFIG_CLIENT_HTTP_CONNECTION_POOL_MAXTOTAL, + DEFAULT_CONFIG_CLIENT_HTTP_CONNECTION_POOL_MAXTOTAL))); + + httpClientBuilder.setConnectionManager(pool); + log.debug("Initalize http-client pool with, maxTotal: {} maxPerRoute: {}", pool.getMaxTotal(), + pool.getDefaultMaxPerRoute()); + + } else if (sslConnectionFactory != null) { + log.trace("Inject SSLSocketFactory without connection pool"); + httpClientBuilder.setSSLSocketFactory(sslConnectionFactory); + + } + + + } + + + } diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/HttpUtils.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/HttpUtils.java new file mode 100644 index 00000000..394d2843 --- /dev/null +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/HttpUtils.java @@ -0,0 +1,119 @@ +/* + * Copyright 2014 Federal Chancellery Austria MOA-ID has been developed in a cooperation between + * BRZ, the Federal Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.impl.utils; + +import javax.servlet.http.HttpServletRequest; +import org.apache.commons.lang3.StringUtils; + + + +public class HttpUtils { + + + /** + * Helper method to retrieve server URL including context path. + * + * @param request HttpServletRequest + * @return Server URL including context path (e.g. http://localhost:8443/moa-id-auth + */ + public static String getBaseUrl(final HttpServletRequest request) { + final StringBuffer buffer = new StringBuffer(getServerUrl(request)); + + // add context path if available + final String contextPath = request.getContextPath(); + if (!StringUtils.isEmpty(contextPath)) { + buffer.append(contextPath); + } + + return buffer.toString(); + } + + /** + * Helper method to retrieve server URL. + * + * @param request HttpServletRequest + * @return Server URL (e.g. http://localhost:8443) + */ + public static String getServerUrl(final HttpServletRequest request) { + final StringBuffer buffer = new StringBuffer(); + + // get protocol + final String protocol = request.getScheme(); + buffer.append(protocol).append("://"); + + // server name + buffer.append(request.getServerName()); + + // add port if necessary + final int port = request.getServerPort(); + if ((protocol.equals("http") && port != 80) || (protocol.equals("https") && port != 443)) { + buffer.append(':'); + buffer.append(port); + } + + return buffer.toString(); + } + + /** + * Extract the IDP PublicURLPrefix from authrequest. + * + * @param req HttpServletRequest + * @return PublicURLPrefix which ends always without / + */ + public static String extractAuthUrlFromRequest(final HttpServletRequest req) { + String authUrl = req.getScheme() + "://" + req.getServerName(); + if ((req.getScheme().equalsIgnoreCase("https") && req.getServerPort() != 443) + || (req.getScheme().equalsIgnoreCase("http") && req.getServerPort() != 80)) { + authUrl = authUrl.concat(":" + req.getServerPort()); + } + authUrl = authUrl.concat(req.getContextPath()); + return authUrl; + + } + + /** + * Extract the IDP requested URL from authrequest. + * + * @param req HttpServletRequest + * @return RequestURL which ends always without / + */ + public static String extractAuthServletPathFromRequest(final HttpServletRequest req) { + return extractAuthUrlFromRequest(req).concat(req.getServletPath()); + + } + + /** + * Add a http GET parameter to URL. + * + * @param url URL + * @param paramname Name of the parameter. + * @param paramvalue Value of the parameter. + * @return + */ + public static String addUrlParameter(final String url, final String paramname, + final String paramvalue) { + final String param = paramname + "=" + paramvalue; + if (url.indexOf("?") < 0) { + return url + "?" + param; + } else { + return url + "&" + param; + } + } + +} diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/IHttpClientFactory.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/IHttpClientFactory.java index 1975fb52..0dc00573 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/IHttpClientFactory.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/IHttpClientFactory.java @@ -4,18 +4,19 @@ import org.apache.http.impl.client.CloseableHttpClient; public interface IHttpClientFactory { - /** - * Return an instance of a Apache HTTP client that follows http redirects automatically - * - * @return - */ - CloseableHttpClient getHttpClient(); + /** + * Return an instance of a Apache HTTP client that follows http redirects automatically. + * + * @return + */ + CloseableHttpClient getHttpClient(); - /** - * Return an instance of a Apache HTTP client - * @param followRedirects - * @return - */ - CloseableHttpClient getHttpClient(boolean followRedirects); - -} \ No newline at end of file + /** + * Return an instance of a Apache HTTP client. + * + * @param followRedirects if false, the client does not flow 30x http redirects + * @return + */ + CloseableHttpClient getHttpClient(boolean followRedirects); + +} diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/KeyStoreUtils.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/KeyStoreUtils.java index e3d74066..18ddf422 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/KeyStoreUtils.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/KeyStoreUtils.java @@ -1,36 +1,28 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. + */ + package at.gv.egiz.eaaf.core.impl.utils; import java.io.BufferedInputStream; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; @@ -42,27 +34,27 @@ import java.security.cert.CertificateFactory; /** * Utility for creating and loading key stores. - * + * * @author Paul Ivancsics * @version $Id$ */ public class KeyStoreUtils { - - /** - * JAVA KeyStore - */ - private static final String KEYSTORE_TYPE_JKS = "JKS"; - - /** - * PKCS12 KeyStore - */ - private static final String KEYSTORE_TYPE_PKCS12 = "PKCS12"; - - + + /** + * JAVA KeyStore. + */ + private static final String KEYSTORE_TYPE_JKS = "JKS"; + + /** + * PKCS12 KeyStore. + */ + private static final String KEYSTORE_TYPE_PKCS12 = "PKCS12"; + + /** * Loads a key store from file. - * + * * @param keystoreType key store type * @param urlString URL of key store * @param password password protecting the key store @@ -70,20 +62,35 @@ public class KeyStoreUtils { * @throws IOException thrown while reading the key store from file * @throws GeneralSecurityException thrown while creating the key store */ - public static KeyStore loadKeyStore( - String keystoreType, - String urlString, - String password) - throws IOException, GeneralSecurityException { - - URL keystoreURL = new URL(urlString); - InputStream in = keystoreURL.openStream(); + public static KeyStore loadKeyStore(final String keystoreType, final String urlString, + final String password) throws IOException, GeneralSecurityException { + + final URL keystoreUrl = new URL(urlString); + final InputStream in = keystoreUrl.openStream(); return loadKeyStore(keystoreType, in, password); } + /** - * Loads a key store from an InputStream, and - * closes the InputStream. - * + * Load a KeyStore from Filesystem. + * + * @param keyStorePath Path to KeyStore + * @param password KeyStore password + * @return KeyStore + * @throws KeyStoreException In case of a keystore error + * @throws IOException In case of a general read error + */ + public static KeyStore loadKeyStore(final String keyStorePath, final String password) + throws KeyStoreException, IOException { + final URL keystoreUrl = new URL(keyStorePath); + final InputStream in = keystoreUrl.openStream(); + final InputStream isBuffered = new BufferedInputStream(in); + return loadKeyStore(isBuffered, password); + + } + + /** + * Loads a key store from an InputStream, and closes the InputStream. + * * @param keystoreType key store type * @param in input stream * @param password password protecting the key store @@ -91,39 +98,63 @@ public class KeyStoreUtils { * @throws IOException thrown while reading the key store from the stream * @throws GeneralSecurityException thrown while creating the key store */ - public static KeyStore loadKeyStore( - String keystoreType, - InputStream in, - String password) - throws IOException, GeneralSecurityException { + public static KeyStore loadKeyStore(final String keystoreType, final InputStream in, + final String password) throws IOException, GeneralSecurityException { char[] chPassword = null; - if (password != null) + if (password != null) { chPassword = password.toCharArray(); - KeyStore ks = KeyStore.getInstance(keystoreType); + } + final KeyStore ks = KeyStore.getInstance(keystoreType); ks.load(in, chPassword); in.close(); return ks; } + /** - * Creates a key store from X509 certificate files, aliasing them with - * the index in the String[], starting with "0". - * + * Loads a keyStore without knowing the keyStore type. + * + * @param is input stream + * @param password Password protecting the keyStore + * @return keyStore loaded + * @throws KeyStoreException thrown if keyStore cannot be loaded + * @throws IOException In case of a general error + */ + public static KeyStore loadKeyStore(final InputStream is, final String password) + throws KeyStoreException, IOException { + is.mark(1024 * 1024); + KeyStore ks = null; + try { + try { + ks = loadKeyStore(KEYSTORE_TYPE_PKCS12, is, password); + } catch (final IOException e2) { + is.reset(); + ks = loadKeyStore(KEYSTORE_TYPE_JKS, is, password); + } + } catch (final Exception e) { + e.printStackTrace(); + + } + return ks; + + } + + /** + * Creates a key store from X509 certificate files, aliasing them with the index in the + * String[], starting with "0". + * * @param keyStoreType key store type * @param certFilenames certificate filenames * @return key store created - * @throws IOException thrown while reading the certificates from file - * @throws GeneralSecurityException thrown while creating the key store + * @throws Exception In case of an error */ - public static KeyStore createKeyStore( - String keyStoreType, - String[] certFilenames) - throws IOException, GeneralSecurityException { + public static KeyStore createKeyStore(final String keyStoreType, final String[] certFilenames) + throws Exception { - KeyStore ks = KeyStore.getInstance(keyStoreType); + final KeyStore ks = KeyStore.getInstance(keyStoreType); ks.load(null, null); for (int i = 0; i < certFilenames.length; i++) { - Certificate cert = loadCertificate(certFilenames[i]); + final Certificate cert = loadCertificate(certFilenames[i]); ks.setCertificateEntry("" + i, cert); } return ks; @@ -131,69 +162,36 @@ public class KeyStoreUtils { /** * Loads an X509 certificate from file. + * * @param certFilename filename * @return the certificate loaded - * @throws IOException thrown while reading the certificate from file - * @throws GeneralSecurityException thrown while creating the certificate + * @throws Exception In case of an IO exception */ - private static Certificate loadCertificate(String certFilename) - throws IOException, GeneralSecurityException { + private static Certificate loadCertificate(final String certFilename) + throws Exception { + FileInputStream in = null; + try { + in = new FileInputStream(certFilename); + final CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); + final Certificate cert = certFactory.generateCertificate(in); + in.close(); + return cert; - FileInputStream in = new FileInputStream(certFilename); - CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); - Certificate cert = certFactory.generateCertificate(in); - in.close(); - return cert; + } catch (final Exception e) { + throw e; + + } finally { + if (in != null) { + try { + in.close(); + } catch (final IOException e) { + e.printStackTrace(); + } + + } + } } - - - /** - * Loads a keyStore without knowing the keyStore type - * @param keyStorePath URL to the keyStore - * @param password Password protecting the keyStore - * @return keyStore loaded - * @throws KeyStoreException thrown if keyStore cannot be loaded - * @throws FileNotFoundException - * @throws IOException - */ - public static KeyStore loadKeyStore(String keyStorePath, String password) throws KeyStoreException, IOException{ - - //InputStream is = new FileInputStream(keyStorePath); - URL keystoreURL = new URL(keyStorePath); - InputStream in = keystoreURL.openStream(); - InputStream isBuffered = new BufferedInputStream(in); - return loadKeyStore(isBuffered, password); - - } - - /** - * Loads a keyStore without knowing the keyStore type - * @param in input stream - * @param password Password protecting the keyStore - * @return keyStore loaded - * @throws KeyStoreException thrown if keyStore cannot be loaded - * @throws FileNotFoundException - * @throws IOException - */ -public static KeyStore loadKeyStore(InputStream is, String password) throws KeyStoreException, IOException{ - is.mark(1024*1024); - KeyStore ks = null; - try { - try { - ks = loadKeyStore(KEYSTORE_TYPE_PKCS12, is, password); - } catch (IOException e2) { - is.reset(); - ks = loadKeyStore(KEYSTORE_TYPE_JKS, is, password); - } - } catch(Exception e) { - e.printStackTrace(); - - } - return ks; - - } - - + } diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/KeyValueUtils.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/KeyValueUtils.java index e753f19f..929d2994 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/KeyValueUtils.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/KeyValueUtils.java @@ -1,29 +1,22 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.utils; import java.util.ArrayList; @@ -35,341 +28,347 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; - import javax.annotation.Nonnull; import javax.annotation.Nullable; - import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** + * Utils to operate on Key/Value based configurations. + * * @author tlenz * */ public class KeyValueUtils { - private static final Logger log = LoggerFactory.getLogger(KeyValueUtils.class); - - public static final String KEY_DELIMITER = "."; - public static final String CSV_DELIMITER = ","; - public static final String KEYVVALUEDELIMITER = "="; - public static final String DEFAULT_VALUE = "default"; - - /** - * Convert Java properties into a Map - *

    - * Important: The key/values from properties must be of type String! - * - * @param properties - * @return - */ - public static Map convertPropertiesToMap(Properties properties) { - return new HashMap((Map) properties); - - //INFO Java8 solution ;) -// return properties.entrySet().stream().collect( -// Collectors.toMap( -// e -> e.getKey().toString(), -// e -> e.getValue().toString() -// ) -// ); - - } - - /** - * Extract the first child of an input key after a the prefix - * - * @param key Full input key - * @param prefix Prefix - * @return Child key {String} if it exists or null - */ - public static String getFirstChildAfterPrefix(String key, String prefix) { - final String idAfterPrefix = removePrefixFromKey(key, prefix); - if (idAfterPrefix != null) { - final int index = idAfterPrefix.indexOf(KEY_DELIMITER); - if (index > 0) { - final String adding = idAfterPrefix.substring(0, index); - if (!(adding.isEmpty())) { - return adding; - - } - } else if (!(idAfterPrefix.isEmpty())) { - return idAfterPrefix; - - } - - } - return null; - } - - /** - * Extract the prefix from an input key - * - * @param key Full input key - * @param suffix Suffix of this key - * @return Prefix {String} of the key or null if input key does not ends with postfix string - */ - public static String getPrefixFromKey(String key, String suffix) { - if (key != null && suffix != null && key.endsWith(suffix)) { - final String idPreforeSuffix = key.substring(0, key.length()-suffix.length()); - if (idPreforeSuffix.endsWith(KEY_DELIMITER)) - return idPreforeSuffix.substring(0, idPreforeSuffix.length()-1); - else - return idPreforeSuffix; - } - return null; - - } - - /** - * Remove a prefix string from a key - * - * @param key Full input key - * @param prefix Prefix, which should be removed - * @return The suffix of the input key or null if the input does not starts with the prefix - */ - public static String removePrefixFromKey(String key, String prefix) { - if (prefix == null) - prefix = new String(); - - if (key!=null && key.startsWith(prefix)) { - String afterPrefix = key.substring(prefix.length()); - final int index = afterPrefix.indexOf(KEY_DELIMITER); - - if (index == 0) { - afterPrefix = afterPrefix.substring(1); - - } - return afterPrefix; - - } - return null; - } - - /** - * Remove a prefix string from all keys in {Map} of key/value pairs - * - * @param keys Input data of key/value pairs - * @param prefix Prefix which should be removed - * @return {Map} of key/value pairs without prefix in key, but never null - */ - public static Map removePrefixFromKeys(Map keys, String prefix) { - final Map result = new HashMap(); - final Iterator> interator = keys.entrySet().iterator(); - while(interator.hasNext()) { - final Entry el = interator.next(); - final String newKey = removePrefixFromKey(el.getKey(), prefix); - if (StringUtils.isNotEmpty(newKey)) { - result.put(newKey, el.getValue()); - } - } - - return result; - } - - /** - * Get a subset of key/value pairs which starts with a prefix string - * The Prefix is removed from the key - * - * @param keys Input data of key/value pairs - * @param prefix Prefix string - * @return {Map} of key/value pairs without prefix in key, but never null - */ - public static Map getSubSetWithPrefix(Map keys, String prefix) { - return removePrefixFromKeys(keys, prefix); - } - - - /** - * Add a prefix to key/value pairs to make the key absolute according to key namespace convention - * - * @param input Input key/value pairs which should be updated - * @param prefix Key prefix, which should be added if the key is not absolute - * @param absolutIdentifier Key identifier, which indicates an absolute key - * @return {Map} of key/value pairs in which all keys are absolute but never null - */ - public static Map makeKeysAbsolut(Map input, String prefix, String absolutIdentifier) { - final Map result = new HashMap(); - final Iterator> interator = input.entrySet().iterator(); - while(interator.hasNext()) { - final Entry el = interator.next(); - if (!el.getKey().startsWith(absolutIdentifier)) { - //key is not absolute -> add prefix - result.put(prefix - + KEY_DELIMITER - + el.getKey(), - el.getValue()); - - } else { - //key is absolute - result.put(el.getKey(), el.getValue()); - } - } - return result; - } - - /** - * Get the parent key string from an input key - * - * @param key input key - * @return parent key or the empty String if no parent exists - */ - public static String getParentKey(String key) { - if (StringUtils.isNotEmpty(key)) { - final int index = key.lastIndexOf(KEY_DELIMITER); - if (index > 0) { - return key.substring(0, index); - - } - } - - return new String(); - } - - /** - * Find the highest free list counter - * - * @param input Array of list keys - * @param listPrefix {String} prefix of the list - * @return {int} highest free list counter - */ - public static int findNextFreeListCounter(String[] input, - String listPrefix) { - final List counters = new ArrayList(); - if (input == null || input.length == 0) - return 0; - - else { - for (final String key : input) { - final String listIndex = getFirstChildAfterPrefix(key, listPrefix); - counters.add(Integer.parseInt(listIndex)); - - } - Collections.sort(counters); - return counters.get(counters.size()-1) + 1; - } - } - - /** - * Find the highest free list counter - * - * @param keySet {Set} of list keys - * @param listPrefix {String} prefix of the list - * @return {int} highest free list counter - */ - public static int findNextFreeListCounter(Set keySet, - String listPrefix) { - if (keySet.isEmpty()) - return 0; - - final String[] array = new String[keySet.size()]; - keySet.toArray(array); - return findNextFreeListCounter(array, listPrefix); - } - - - /** - * Normalize a CSV encoded list of value of an key/value pair - * - * This method removes all whitespace at the begin or the - * end of CSV values and remove newLine signs at the end of value. - * The ',' is used as list delimiter - * - * @param value CSV encoded input data - * @return normalized CSV encoded data or null if {value} is null or empty - */ - public static String normalizeCSVValueString(String value) { - String normalizedCodes = null; - if (StringUtils.isNotEmpty(value)) { - final String[] codes = value.split(CSV_DELIMITER); - for (final String el: codes) { - if (normalizedCodes == null) - normalizedCodes = StringUtils.chomp(el.trim()); - else - normalizedCodes += "," + StringUtils.chomp(el.trim()); - - } - } - return normalizedCodes; - } - - - /** - * Check a String if it is a comma separated list of values - * - * This method uses the ',' as list delimiter. - * - * @param value CSV encoded input data - * @return true if the input data contains a ',' and has more then 1 list element, otherwise false - */ - public static boolean isCSVValueString(String value) { - if (StringUtils.isNotEmpty(value)) { - final String[] codes = value.split(CSV_DELIMITER); - if (codes.length >= 2) { - if (StringUtils.isNotEmpty(codes[1].trim())) - return true; - - } - } - - return false; - } - - /** - * Convert a CSV list to a List of CSV values - *

    - * This method removes all whitespace at the begin or the - * end of CSV values and remove newLine signs at the end of value. - * The ',' is used as list delimiter - * - * @param csv CSV encoded input data - * @return List of CSV normalized values, but never null - */ - @Nonnull - public static List getListOfCSVValues(@Nullable String csv) { - final List list = new ArrayList(); - if (StringUtils.isNotEmpty(csv)) { - final String[] values = csv.split(CSV_DELIMITER); - for (final String el: values) - list.add(el.trim()); - - } - - return list; - } - - /** - * Convert a List of String elements to a Map of Key/Value pairs - *
    - * Every List element used as a key/value pair and the '=' sign represents the delimiter between key and value - * - * @param elements List of key/value elements - * @return Map of Key / Value pairs, but never null - */ - public static Map convertListToMap(List elements) { - final Map map = new HashMap(); - for (final String el : elements) { - if (el.contains(KEYVVALUEDELIMITER)) { - final String[] split = el.split(KEYVVALUEDELIMITER); - map.put(split[0], split[1]); - - } else - log.debug("Key/Value Mapper: '" + el + "' contains NO '='. Ignore it."); - - } - - return map; - } - - /** - * This method remove all newline delimiter (\n or \r\n) from input data - * - * @param value Input String - * @return Input String without newline characters - */ - public static String removeAllNewlineFromString(String value) { - return value.replaceAll("(\\t|\\r?\\n)+", ""); - - } - + private static final Logger log = LoggerFactory.getLogger(KeyValueUtils.class); + + public static final String KEY_DELIMITER = "."; + public static final String CSV_DELIMITER = ","; + public static final String KEYVVALUEDELIMITER = "="; + public static final String DEFAULT_VALUE = "default"; + + /** + * Convert Java properties into a Map String/String. + *
    + * Important: The key/values from properties must be of type String! + * + * @param properties Java {@link Properties} that should be converted + * @return + */ + public static Map convertPropertiesToMap(final Properties properties) { + return new HashMap((Map) properties); + + // INFO Java8 solution ;) + // return properties.entrySet().stream().collect( + // Collectors.toMap( + // e -> e.getKey().toString(), + // e -> e.getValue().toString() + // ) + // ); + + } + + /** + * Extract the first child of an input key after a the prefix. + * + * @param key Full input key + * @param prefix Prefix + * @return Child key {String} if it exists or null + */ + public static String getFirstChildAfterPrefix(final String key, final String prefix) { + final String idAfterPrefix = removePrefixFromKey(key, prefix); + if (idAfterPrefix != null) { + final int index = idAfterPrefix.indexOf(KEY_DELIMITER); + if (index > 0) { + final String adding = idAfterPrefix.substring(0, index); + if (!(adding.isEmpty())) { + return adding; + + } + } else if (!(idAfterPrefix.isEmpty())) { + return idAfterPrefix; + + } + + } + return null; + } + + /** + * Extract the prefix from an input key. + * + * @param key Full input key + * @param suffix Suffix of this key + * @return Prefix {String} of the key or null if input key does not ends with postfix string + */ + public static String getPrefixFromKey(final String key, final String suffix) { + if (key != null && suffix != null && key.endsWith(suffix)) { + final String idPreforeSuffix = key.substring(0, key.length() - suffix.length()); + if (idPreforeSuffix.endsWith(KEY_DELIMITER)) { + return idPreforeSuffix.substring(0, idPreforeSuffix.length() - 1); + } else { + return idPreforeSuffix; + } + } + return null; + + } + + /** + * Remove a prefix string from a key. + * + * @param key Full input key + * @param prefix Prefix, which should be removed + * @return The suffix of the input key or null if the input does not starts with the prefix + */ + public static String removePrefixFromKey(final String key, String prefix) { + if (prefix == null) { + prefix = StringUtils.EMPTY; + + } + + if (key != null && key.startsWith(prefix)) { + String afterPrefix = key.substring(prefix.length()); + final int index = afterPrefix.indexOf(KEY_DELIMITER); + + if (index == 0) { + afterPrefix = afterPrefix.substring(1); + + } + return afterPrefix; + + } + return null; + } + + /** + * Remove a prefix string from all keys in Map String/String of key/value pairs. + * + * @param keys Input data of key/value pairs + * @param prefix Prefix which should be removed + * @return Map String/String of key/value pairs without prefix in key, but never null + */ + public static Map removePrefixFromKeys(final Map keys, + final String prefix) { + final Map result = new HashMap<>(); + final Iterator> interator = keys.entrySet().iterator(); + while (interator.hasNext()) { + final Entry el = interator.next(); + final String newKey = removePrefixFromKey(el.getKey(), prefix); + if (StringUtils.isNotEmpty(newKey)) { + result.put(newKey, el.getValue()); + } + } + + return result; + } + + /** + * Get a subset of key/value pairs which starts with a prefix string The Prefix is removed from + * the key. + * + * @param keys Input data of key/value pairs + * @param prefix Prefix string + * @return Map String/String of key/value pairs without prefix in key, but never null + */ + public static Map getSubSetWithPrefix(final Map keys, + final String prefix) { + return removePrefixFromKeys(keys, prefix); + } + + + /** + * Add a prefix to key/value pairs to make the key absolute according to key namespace convention. + * + * @param input Input key/value pairs which should be updated + * @param prefix Key prefix, which should be added if the key is not absolute + * @param absolutIdentifier Key identifier, which indicates an absolute key + * @return Map String/String of key/value pairs in which all keys are absolute but never null + */ + public static Map makeKeysAbsolut(final Map input, + final String prefix, final String absolutIdentifier) { + final Map result = new HashMap<>(); + final Iterator> interator = input.entrySet().iterator(); + while (interator.hasNext()) { + final Entry el = interator.next(); + if (!el.getKey().startsWith(absolutIdentifier)) { + // key is not absolute -> add prefix + result.put(prefix + KEY_DELIMITER + el.getKey(), el.getValue()); + + } else { + // key is absolute + result.put(el.getKey(), el.getValue()); + } + } + return result; + } + + /** + * Get the parent key string from an input key. + * + * @param key input key + * @return parent key or the empty String if no parent exists + */ + public static String getParentKey(final String key) { + if (StringUtils.isNotEmpty(key)) { + final int index = key.lastIndexOf(KEY_DELIMITER); + if (index > 0) { + return key.substring(0, index); + + } + } + + return StringUtils.EMPTY; + } + + /** + * Find the highest free list counter. + * + * @param input Array of list keys + * @param listPrefix {String} prefix of the list + * @return {int} highest free list counter + */ + public static int findNextFreeListCounter(final String[] input, final String listPrefix) { + final List counters = new ArrayList<>(); + if (input == null || input.length == 0) { + return 0; + } else { + for (final String key : input) { + final String listIndex = getFirstChildAfterPrefix(key, listPrefix); + counters.add(Integer.parseInt(listIndex)); + + } + Collections.sort(counters); + return counters.get(counters.size() - 1) + 1; + } + } + + /** + * Find the highest free list counter. + * + * @param keySet Set of list keys + * @param listPrefix {String} prefix of the list + * @return {int} highest free list counter + */ + public static int findNextFreeListCounter(final Set keySet, final String listPrefix) { + if (keySet.isEmpty()) { + return 0; + } + + final String[] array = new String[keySet.size()]; + keySet.toArray(array); + return findNextFreeListCounter(array, listPrefix); + } + + + /** + * Normalize a CSV encoded list of value of an key/value pair. + * + *

    + * This method removes all whitespace at the begin or the end of CSV values and remove newLine + * signs at the end of value. The ',' is used as list delimiter + *

    + * + * @param value CSV encoded input data + * @return normalized CSV encoded data or null if {value} is null or empty + */ + public static String normalizeCsvValueString(final String value) { + String normalizedCodes = null; + if (StringUtils.isNotEmpty(value)) { + final String[] codes = value.split(CSV_DELIMITER); + for (final String el : codes) { + if (normalizedCodes == null) { + normalizedCodes = StringUtils.chomp(el.trim()); + } else { + normalizedCodes += "," + StringUtils.chomp(el.trim()); + } + + } + } + return normalizedCodes; + } + + + /** + * Check a String if it is a comma separated list of values. + * + *

    + * This method uses the ',' as list delimiter. + *

    + * + * @param value CSV encoded input data + * @return true if the input data contains a ',' and has more then 1 list element, otherwise false + */ + public static boolean isCsvValueString(final String value) { + if (StringUtils.isNotEmpty(value)) { + final String[] codes = value.split(CSV_DELIMITER); + if (codes.length >= 2 + && StringUtils.isNotEmpty(codes[1].trim())) { + return true; + + } + } + + return false; + } + + /** + * Convert a CSV list to a List of CSV values.
    + *
    + * This method removes all whitespace at the begin or the end of CSV values and remove newLine + * signs at the end of value. The ',' is used as list delimiter + * + * @param csv CSV encoded input data + * @return List of CSV normalized values, but never null + */ + @Nonnull + public static List getListOfCsvValues(@Nullable final String csv) { + final List list = new ArrayList<>(); + if (StringUtils.isNotEmpty(csv)) { + final String[] values = csv.split(CSV_DELIMITER); + for (final String el : values) { + list.add(el.trim()); + } + + } + + return list; + } + + /** + * Convert a List of String elements to a Map of Key/Value pairs.
    + * Every List element used as a key/value pair and the '=' sign represents the delimiter between + * key and value + * + * @param elements List of key/value elements + * @return Map of Key / Value pairs, but never null + */ + public static Map convertListToMap(final List elements) { + final Map map = new HashMap<>(); + for (final String el : elements) { + if (el.contains(KEYVVALUEDELIMITER)) { + final String[] split = el.split(KEYVVALUEDELIMITER); + map.put(split[0], split[1]); + + } else { + log.debug("Key/Value Mapper: '" + el + "' contains NO '='. Ignore it."); + } + + } + + return map; + } + + /** + * This method remove all newline delimiter (\n or \r\n) from input data. + * + * @param value Input String + * @return Input String without newline characters + */ + public static String removeAllNewlineFromString(final String value) { + return value.replaceAll("(\\t|\\r?\\n)+", ""); + + } + } diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/NodeIteratorAdapter.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/NodeIteratorAdapter.java index ec57b92a..755c4431 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/NodeIteratorAdapter.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/NodeIteratorAdapter.java @@ -1,92 +1,79 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.utils; import java.util.ListIterator; - import org.w3c.dom.DOMException; import org.w3c.dom.Node; import org.w3c.dom.traversal.NodeFilter; import org.w3c.dom.traversal.NodeIterator; /** - * A NodeIterator implementation based on a - * ListIterator. - * + * A NodeIterator implementation based on a ListIterator. + * * @see java.util.ListIterator * @see org.w3c.dom.traversal.NodeIterator - * + * */ public class NodeIteratorAdapter implements NodeIterator { /** The ListIterator to wrap. */ - private ListIterator nodeIterator; + private final ListIterator nodeIterator; /** * Create a new NodeIteratorAdapter. + * * @param nodeIterator The ListIterator to iterate over. */ - public NodeIteratorAdapter(ListIterator nodeIterator) { + public NodeIteratorAdapter(final ListIterator nodeIterator) { this.nodeIterator = nodeIterator; } - /** - * @see org.w3c.dom.traversal.NodeIterator#getRoot() - */ + + @Override public Node getRoot() { return null; } - /** - * @see org.w3c.dom.traversal.NodeIterator#getWhatToShow() - */ + + @Override public int getWhatToShow() { return NodeFilter.SHOW_ALL; } - /** - * @see org.w3c.dom.traversal.NodeIterator#getFilter() - */ + + @Override public NodeFilter getFilter() { return null; } - /** - * @see org.w3c.dom.traversal.NodeIterator#getExpandEntityReferences() - */ + + @Override public boolean getExpandEntityReferences() { return false; } - /** - * @see org.w3c.dom.traversal.NodeIterator#nextNode() - */ + + @Override public Node nextNode() throws DOMException { if (nodeIterator.hasNext()) { return (Node) nodeIterator.next(); @@ -94,9 +81,8 @@ public class NodeIteratorAdapter implements NodeIterator { return null; } - /** - * @see org.w3c.dom.traversal.NodeIterator#previousNode() - */ + + @Override public Node previousNode() throws DOMException { if (nodeIterator.hasPrevious()) { return (Node) nodeIterator.previous(); @@ -104,10 +90,10 @@ public class NodeIteratorAdapter implements NodeIterator { return null; } - /** - * @see org.w3c.dom.traversal.NodeIterator#detach() - */ + + @Override public void detach() { + } } diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/NodeListAdapter.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/NodeListAdapter.java index 69045aaa..a942f75e 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/NodeListAdapter.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/NodeListAdapter.java @@ -1,68 +1,58 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.core.impl.utils; import java.util.List; - import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * A NodeList implementation based on a List. - * + * * @see java.util.List * @see org.w3c.dom.NodeList */ public class NodeListAdapter implements NodeList { /** The List to wrap. */ - private List nodeList; - + private final List nodeList; + /** * Create a new NodeListAdapter. - * - * @param nodeList The List containing the nodes. + * + * @param nodeList The List containing the nodes. */ - public NodeListAdapter(List nodeList) { + public NodeListAdapter(final List nodeList) { this.nodeList = nodeList; } - /** - * @see org.w3c.dom.NodeList#item(int) - */ - public Node item(int index) { + + @Override + public Node item(final int index) { return (Node) nodeList.get(index); } - /** - * @see org.w3c.dom.NodeList#getLength() - */ + + @Override public int getLength() { return nodeList.size(); } diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/Random.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/Random.java index e236b3a9..14d54b0b 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/Random.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/Random.java @@ -1,176 +1,188 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. + */ package at.gv.egiz.eaaf.core.impl.utils; +import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; - +import at.gv.egiz.eaaf.core.impl.idp.process.support.SecureRandomHolder; import org.apache.commons.codec.binary.Hex; import org.apache.commons.lang3.ArrayUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import at.gv.egiz.eaaf.core.impl.idp.process.support.SecureRandomHolder; - /** - * Random number generator used to generate ID's + * Random number generator used to generate ID's. + * * @author Paul Ivancsics * @version $Id$ */ public class Random { - private static final Logger log = LoggerFactory.getLogger(Random.class); - - private final static char[] allowedPreFix = - {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z', - 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}; - private static final DateFormat dateFormater = new SimpleDateFormat("yyyyddMM"); - - /** random number generator used */ - private static SecureRandom random; - //private static SeedGenerator seedgenerator; - - static { - try { - random = SecureRandom.getInstance("SHA256PRNG-FIPS186"); - - } catch (NoSuchAlgorithmException e) { - log.warn("Can NOT initialize SecureRandom with: 'SHA256PRNG-FIPS186'. Use 'StrongSecureRandom' as backup"); - random = SecureRandomHolder.getInstance(); - - } - - - //random = iaik.security.random.SHA256FIPS186Random.getDefault(); - } - - /** - * Generate a unique process reference-value [160bit], which always starts with a letter - *
    - * This unique ID consists of single letter, a 64bit date String[yyyyddMM], - * and a 88bit random value. - * - * @return 160bit ID, which is hex encoded - */ - public static String nextProcessReferenceValue() { - //pre-process all three parts of a unique reference value - String now = dateFormater.format(new Date()); //8 bytes = 64bit - byte[] randValue = nextByteRandom(11); - char preFix = allowedPreFix[Math.abs(random.nextInt() % allowedPreFix.length)]; - - //generate ID - String returnValue = preFix + new String(Hex.encodeHex(ArrayUtils.addAll(now.getBytes(), randValue))); // 20 bytes = 160 bits - if (returnValue.length() > 40) - return returnValue.substring(0, 40); - else - return returnValue; - - } - - - - /** - * Creates a new random number [256bit], and encode it as hex value. - * - * @return random hex encoded value [256bit] - */ - public static String nextHexRandom32() { - return new String(Hex.encodeHex(nextByteRandom(32))); // 32 bytes = 256 bits - - } - - /** - * Creates a new random number [128bit], and encode it as hex value. - * - * @return random hex encoded value [128bit] - */ - public static String nextHexRandom16() { - return new String(Hex.encodeHex(nextByteRandom(16))); // 16 bytes = 128 bits - - } - - /** - * Creates a new random number [64bit], to be used as an ID. - * - * @return random long as a String [64bit] - */ - public static String nextLongRandom() { - return "".concat(String.valueOf(Math.abs(generateLongRandom(32)))); // 32 bytes = 256 bits - - } - + private static final Logger log = LoggerFactory.getLogger(Random.class); + + private static final char[] allowedPreFix = + {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', + 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', + 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; + + /** random number generator used. */ + private static SecureRandom random; + // private static SeedGenerator seedgenerator; + + static { + try { + random = SecureRandom.getInstance("SHA256PRNG-FIPS186"); + + } catch (final NoSuchAlgorithmException e) { + log.warn( + "Can NOT initialize SecureRandom with: 'SHA256PRNG-FIPS186'. Use 'StrongSecureRandom' as backup"); + random = SecureRandomHolder.getInstance(); + + } + + + // random = iaik.security.random.SHA256FIPS186Random.getDefault(); + } + + /** + * Generate a unique process reference-value [160bit], which always starts with a letter
    + * This unique ID consists of single letter, a 64bit date String[yyyyddMM], and a 88bit random + * value. + * + * @return 160bit ID, which is hex encoded + */ + public static String nextProcessReferenceValue() { + // pre-process all three parts of a unique reference value + final DateFormat dateFormater = new SimpleDateFormat("yyyyddMM"); + final String now = dateFormater.format(new Date()); // 8 bytes = 64bit + final byte[] randValue = nextByteRandom(11); + final char preFix = allowedPreFix[Math.abs(random.nextInt() % allowedPreFix.length)]; + + // generate ID + String returnValue; + try { + returnValue = preFix + new String(Hex.encodeHex(ArrayUtils.addAll(now.getBytes("UTF-8"), randValue))); + + // 20 bytes = 160 bits + if (returnValue.length() > 40) { + return returnValue.substring(0, 40); + } else { + return returnValue; + } + + } catch (final UnsupportedEncodingException e) { + throw new RuntimeException(e); + + } + + + + } + + + + /** + * Creates a new random number [256bit], and encode it as hex value. + * + * @return random hex encoded value [256bit] + */ + public static String nextHexRandom32() { + return new String(Hex.encodeHex(nextByteRandom(32))); // 32 bytes = 256 bits + + } + + /** + * Creates a new random number [128bit], and encode it as hex value. + * + * @return random hex encoded value [128bit] + */ + public static String nextHexRandom16() { + return new String(Hex.encodeHex(nextByteRandom(16))); // 16 bytes = 128 bits + + } + + /** + * Creates a new random number [64bit], to be used as an ID. + * + * @return random long as a String [64bit] + */ + public static String nextLongRandom() { + return "".concat(String.valueOf(Math.abs(generateLongRandom(32)))); // 32 bytes = 256 bits + + } + /** * Creates a new random number, to be used as an ID. - * + * * @return random long as a String [64bit] */ - @Deprecated - public static String nextRandom() { - long l = ByteBuffer.wrap(nextByteRandom(32)).getLong(); // 32 bytes = 256 bits - return "" + Math.abs(l); - + @Deprecated + public static String nextRandom() { + final long l = ByteBuffer.wrap(nextByteRandom(32)).getLong(); // 32 bytes = 256 bits + return "" + Math.abs(l); + } - -/** - * Creates a new random byte[] - * - * @param size Size of random number in byte - * @return - */ -public static byte[] nextBytes(int size) { - return nextByteRandom(size); - -} - + + /** + * Creates a new random byte[]. + * + * @param size Size of random number in byte + * @return + */ + public static byte[] nextBytes(final int size) { + return nextByteRandom(size); + + } + + /** + * initialize random-number generator. + */ public static void seedRandom() { - //TODO: implement reflection on IAIK Seed generator -// seedgenerator = iaik.security.random.AutoSeedGenerator.getDefault(); -// if (seedgenerator.seedAvailable()) -// random.setSeed(seedgenerator.getSeed()); - - random.setSeed(System.nanoTime()); + // TODO: implement reflection on IAIK Seed generator + // seedgenerator = iaik.security.random.AutoSeedGenerator.getDefault(); + // if (seedgenerator.seedAvailable()) + // random.setSeed(seedgenerator.getSeed()); + + random.setSeed(System.nanoTime()); } - - private static long generateLongRandom(int size) { - return ByteBuffer.wrap(nextByteRandom(size)).getLong(); - } - + + private static long generateLongRandom(final int size) { + return ByteBuffer.wrap(nextByteRandom(size)).getLong(); + } + /** - * Generate a new random number - * + * Generate a new random number. + * * @param size Size of random number in byte * @return */ - private static synchronized byte[] nextByteRandom(int size) { - byte[] b = new byte[size]; - random.nextBytes(b); - return b; - + private static synchronized byte[] nextByteRandom(final int size) { + final byte[] b = new byte[size]; + random.nextBytes(b); + return b; + } } diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/SecurePendingRequestIdGenerationStrategy.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/SecurePendingRequestIdGenerationStrategy.java index f0ef9b38..ee88c4bb 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/SecurePendingRequestIdGenerationStrategy.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/SecurePendingRequestIdGenerationStrategy.java @@ -1,19 +1,24 @@ package at.gv.egiz.eaaf.core.impl.utils; import java.io.UnsupportedEncodingException; +import java.nio.charset.Charset; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import java.util.Arrays; import java.util.Base64; - import javax.annotation.PostConstruct; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; - +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.api.utils.IPendingRequestIdGenerationStrategy; +import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.exceptions.EaafIllegalStateException; +import at.gv.egiz.eaaf.core.exceptions.PendingReqIdValidationException; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.joda.time.DurationFieldType; @@ -25,190 +30,209 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.lang.NonNull; import org.springframework.lang.Nullable; -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.api.utils.IPendingRequestIdGenerationStrategy; -import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.core.exceptions.EAAFIllegalStateException; -import at.gv.egiz.eaaf.core.exceptions.PendingReqIdValidationException; - /** - * PendingRequestId generation strategy based on signed tokens that facilitates extended token validation - * + * PendingRequestId generation strategy based on signed tokens that facilitates extended token + * validation. + * * @author tlenz * */ -public class SecurePendingRequestIdGenerationStrategy implements IPendingRequestIdGenerationStrategy { - private static final Logger log = LoggerFactory.getLogger(SecurePendingRequestIdGenerationStrategy.class); - - @Autowired(required=true) IConfiguration baseConfig; - - public static final String CONFIG_PROP_PENDINGREQUESTID_DIGIST_SECRET = "core.pendingrequestid.digist.secret"; - public static final String CONFIG_PROP_PENDINGREQUESTID_DIGIST_ALGORITHM = "core.pendingrequestid.digist.algorithm"; - public static final String CONFIG_PROP_PENDINGREQUESTID_MAX_LIFETIME = "core.pendingrequestid.maxlifetime"; - - public static final String DEFAULT_PENDINGREQUESTID_DIGIST_ALGORITHM = "HmacSHA256"; - public static final String DEFAULT_PENDINGREQUESTID_MAX_LIFETIME = "300"; - - private static final int ENCODED_TOKEN_PARTS = 3; - private static final String TOKEN_SEPARATOR = "|"; - private static final DateTimeFormatter TOKEN_TEXTUAL_DATE_FORMAT = - DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss SSS"); - - private int maxPendingRequestIdLifeTime = 300; - private final int maxPendingReqIdSize = 1024; - private String digistAlgorithm = null; - private SecretKey key = null; - private final byte[] salt = "notRequiredInThisScenario".getBytes(); - - @Override - public String generateExternalPendingRequestId() throws EAAFException { - try { - final String toSign = buildInternalToken(Random.nextLongRandom(), DateTime.now()); - final StringBuilder externalPendingRequestId= new StringBuilder(); - externalPendingRequestId.append(toSign); - externalPendingRequestId.append(TOKEN_SEPARATOR); - externalPendingRequestId.append(Base64.getEncoder().encodeToString(calculateHMAC(toSign))); - return Base64.getUrlEncoder().encodeToString(externalPendingRequestId.toString().getBytes("UTF-8")); - - } catch (final UnsupportedEncodingException e) { - throw new EAAFException("internal.99", new Object[] {e.getMessage()}, e); - - } - - } - - @Override - public String getPendingRequestIdWithOutChecks(String externalPendingReqId) throws PendingReqIdValidationException { - final String[] tokenElements = extractTokens(externalPendingReqId); - return tokenElements[1]; - - } - - @Override - public String validateAndGetPendingRequestId(String externalPendingReqId) throws PendingReqIdValidationException { - try { - final String[] tokenElements = extractTokens(externalPendingReqId); - final String internalPendingReqId = tokenElements[1]; - final DateTime timeStamp = TOKEN_TEXTUAL_DATE_FORMAT.parseDateTime(tokenElements[0]); - - log.trace("Checking HMAC from externalPendingReqId ... "); - final byte[] tokenDigest = Base64.getDecoder().decode(tokenElements[2]); - final byte[] refDigist = calculateHMAC(buildInternalToken(internalPendingReqId, timeStamp)); - if (!Arrays.equals(tokenDigest, refDigist)) { - log.warn("Digest of Token does NOT match"); - log.debug("Token: {} | Ref: {}", tokenDigest, refDigist); - throw new PendingReqIdValidationException(null, "Digest of pendingRequestId does NOT match"); - - } - log.debug("PendingRequestId HMAC digest check successful"); - - log.trace("Checking valid period ... "); - final DateTime now = DateTime.now(); - if (timeStamp.withFieldAdded( - DurationFieldType.seconds(), maxPendingRequestIdLifeTime).isBefore(now)) { - log.warn("Token exceeds the valid period"); - log.debug("Token: {} | Now: {}", timeStamp, now ); - throw new PendingReqIdValidationException(internalPendingReqId, "PendingRequestId exceeds the valid period"); - - } - log.debug("Token valid-period check successful"); - - return internalPendingReqId; - - - } catch (final IllegalArgumentException | EAAFIllegalStateException e) { - log.warn("Token is NOT a valid String. Msg: {}", e.getMessage()); - log.debug("TokenValue: {}", externalPendingReqId); - throw new PendingReqIdValidationException(null, "PendingReqId is NOT a valid String", e); - - } - } - - @NonNull - private String[] extractTokens(@Nullable String externalPendingReqId) throws PendingReqIdValidationException { - if (StringUtils.isEmpty(externalPendingReqId)) { - log.info("PendingReqId is 'null' or empty"); - throw new PendingReqIdValidationException(null, "PendingReqId is 'null' or empty"); - - } - - log.trace("RAW external pendingReqId: {}", externalPendingReqId); - final byte[] externalPendingReqIdBytes = Base64.getUrlDecoder().decode(externalPendingReqId); - - if (externalPendingReqIdBytes.length > maxPendingReqIdSize) { - log.warn("pendingReqId size exceeds {}", maxPendingReqIdSize); - throw new PendingReqIdValidationException(null, "pendingReqId exceeds max.size: " + maxPendingReqIdSize); - - } - - final String stringToken = new String(externalPendingReqIdBytes); - if (StringUtils.countMatches(stringToken, TOKEN_SEPARATOR) == ENCODED_TOKEN_PARTS - 1) { - final String[] tokenElements = StringUtils.split(stringToken, - TOKEN_SEPARATOR, ENCODED_TOKEN_PARTS); - return tokenElements; - - } else { - log.warn("PendingRequestId has an unvalid format"); - log.debug("PendingRequestId: {}", stringToken); - throw new PendingReqIdValidationException(null, "PendingReqId has an unvalid format"); - - } - - } - - - @PostConstruct - private void initialize() throws EAAFConfigurationException { - log.debug("Initializing " + this.getClass().getName() + " ... "); - - final String pendingReqIdDigistSecret = baseConfig.getBasicConfiguration(CONFIG_PROP_PENDINGREQUESTID_DIGIST_SECRET); - if (StringUtils.isEmpty(pendingReqIdDigistSecret)) - throw new EAAFConfigurationException("config.08", new Object[] {CONFIG_PROP_PENDINGREQUESTID_DIGIST_SECRET}); - - digistAlgorithm = baseConfig.getBasicConfiguration(CONFIG_PROP_PENDINGREQUESTID_DIGIST_ALGORITHM, DEFAULT_PENDINGREQUESTID_DIGIST_ALGORITHM); - - maxPendingRequestIdLifeTime = Integer.valueOf( - baseConfig.getBasicConfiguration(CONFIG_PROP_PENDINGREQUESTID_MAX_LIFETIME, DEFAULT_PENDINGREQUESTID_MAX_LIFETIME)); - - try { - final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WITHHMACSHA256"); - final KeySpec spec = new PBEKeySpec(pendingReqIdDigistSecret.toCharArray(), salt, 10000, 128); - key = keyFactory.generateSecret(spec); - - - } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { - log.error("Can NOT initialize TokenService with configuration object", e); - throw new EAAFConfigurationException("config.09", - new Object[] { CONFIG_PROP_PENDINGREQUESTID_DIGIST_SECRET, - "Can NOT generate HMAC key"}, - e); - - } - - log.info(this.getClass().getName() + " initialized with digistAlg: {} and maxLifeTime: {}", digistAlgorithm, maxPendingRequestIdLifeTime); - - } - - private String buildInternalToken(String internalPendingReqId, DateTime now) { - return new StringBuilder() - .append(TOKEN_TEXTUAL_DATE_FORMAT.print(now)) - .append(TOKEN_SEPARATOR) - .append(internalPendingReqId).toString(); - } - - private byte[] calculateHMAC(String toSign) throws EAAFIllegalStateException { - try { - final Mac mac = Mac.getInstance(digistAlgorithm); - mac.init(key); - return mac.doFinal(toSign.getBytes("UTF-8")); - - } catch (UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException e) { - log.error("Can NOT generate secure pendingRequestId", e); - throw new EAAFIllegalStateException(new Object[] {"Can NOT caluclate digist for secure pendingRequestId"}, e); - - } - - } +public class SecurePendingRequestIdGenerationStrategy + implements IPendingRequestIdGenerationStrategy { + private static final Logger log = + LoggerFactory.getLogger(SecurePendingRequestIdGenerationStrategy.class); + + @Autowired(required = true) + IConfiguration baseConfig; + + public static final String CONFIG_PROP_PENDINGREQUESTID_DIGIST_SECRET = + "core.pendingrequestid.digist.secret"; + public static final String CONFIG_PROP_PENDINGREQUESTID_DIGIST_ALGORITHM = + "core.pendingrequestid.digist.algorithm"; + public static final String CONFIG_PROP_PENDINGREQUESTID_MAX_LIFETIME = + "core.pendingrequestid.maxlifetime"; + + public static final String DEFAULT_PENDINGREQUESTID_DIGIST_ALGORITHM = "HmacSHA256"; + public static final String DEFAULT_PENDINGREQUESTID_MAX_LIFETIME = "300"; + + private static final int ENCODED_TOKEN_PARTS = 3; + private static final String TOKEN_SEPARATOR = "|"; + private static final DateTimeFormatter TOKEN_TEXTUAL_DATE_FORMAT = + DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss SSS"); + + private int maxPendingRequestIdLifeTime = 300; + private final int maxPendingReqIdSize = 1024; + private String digistAlgorithm = null; + private SecretKey key = null; + private final byte[] salt = "notRequiredInThisScenario".getBytes(Charset.defaultCharset()); + + @Override + public String generateExternalPendingRequestId() throws EaafException { + try { + final String toSign = buildInternalToken(Random.nextLongRandom(), DateTime.now()); + final StringBuilder externalPendingRequestId = new StringBuilder(); + externalPendingRequestId.append(toSign); + externalPendingRequestId.append(TOKEN_SEPARATOR); + externalPendingRequestId.append(Base64.getEncoder().encodeToString(calculateHmac(toSign))); + return Base64.getUrlEncoder() + .encodeToString(externalPendingRequestId.toString().getBytes("UTF-8")); + + } catch (final UnsupportedEncodingException e) { + throw new EaafException("internal.99", new Object[] {e.getMessage()}, e); + + } + + } + + @Override + public String getPendingRequestIdWithOutChecks(final String externalPendingReqId) + throws PendingReqIdValidationException { + try { + final String[] tokenElements = extractTokens(externalPendingReqId); + return tokenElements[1]; + + } catch (final UnsupportedEncodingException e) { + throw new RuntimeException(e); + + } + } + + @Override + public String validateAndGetPendingRequestId(final String externalPendingReqId) + throws PendingReqIdValidationException { + try { + final String[] tokenElements = extractTokens(externalPendingReqId); + final String internalPendingReqId = tokenElements[1]; + final DateTime timeStamp = TOKEN_TEXTUAL_DATE_FORMAT.parseDateTime(tokenElements[0]); + + log.trace("Checking HMAC from externalPendingReqId ... "); + final byte[] tokenDigest = Base64.getDecoder().decode(tokenElements[2]); + final byte[] refDigist = calculateHmac(buildInternalToken(internalPendingReqId, timeStamp)); + if (!Arrays.equals(tokenDigest, refDigist)) { + log.warn("Digest of Token does NOT match"); + log.debug("Token: {} | Ref: {}", tokenDigest, refDigist); + throw new PendingReqIdValidationException(null, + "Digest of pendingRequestId does NOT match"); + + } + log.debug("PendingRequestId HMAC digest check successful"); + + log.trace("Checking valid period ... "); + final DateTime now = DateTime.now(); + if (timeStamp.withFieldAdded(DurationFieldType.seconds(), maxPendingRequestIdLifeTime) + .isBefore(now)) { + log.warn("Token exceeds the valid period"); + log.debug("Token: {} | Now: {}", timeStamp, now); + throw new PendingReqIdValidationException(internalPendingReqId, + "PendingRequestId exceeds the valid period"); + + } + log.debug("Token valid-period check successful"); + + return internalPendingReqId; + + + } catch (final IllegalArgumentException | EaafIllegalStateException e) { + log.warn("Token is NOT a valid String. Msg: {}", e.getMessage()); + log.debug("TokenValue: {}", externalPendingReqId); + throw new PendingReqIdValidationException(null, "PendingReqId is NOT a valid String", e); + + } catch (final UnsupportedEncodingException e) { + throw new RuntimeException(e); + + } + } + + @NonNull + private String[] extractTokens(@Nullable final String externalPendingReqId) + throws PendingReqIdValidationException, UnsupportedEncodingException { + if (StringUtils.isEmpty(externalPendingReqId)) { + log.info("PendingReqId is 'null' or empty"); + throw new PendingReqIdValidationException(null, "PendingReqId is 'null' or empty"); + + } + + log.trace("RAW external pendingReqId: {}", externalPendingReqId); + final byte[] externalPendingReqIdBytes = Base64.getUrlDecoder().decode(externalPendingReqId); + + if (externalPendingReqIdBytes.length > maxPendingReqIdSize) { + log.warn("pendingReqId size exceeds {}", maxPendingReqIdSize); + throw new PendingReqIdValidationException(null, + "pendingReqId exceeds max.size: " + maxPendingReqIdSize); + + } + + final String stringToken = new String(externalPendingReqIdBytes, "UTF-8"); + if (StringUtils.countMatches(stringToken, TOKEN_SEPARATOR) == ENCODED_TOKEN_PARTS - 1) { + final String[] tokenElements = + StringUtils.split(stringToken, TOKEN_SEPARATOR, ENCODED_TOKEN_PARTS); + return tokenElements; + + } else { + log.warn("PendingRequestId has an unvalid format"); + log.debug("PendingRequestId: {}", stringToken); + throw new PendingReqIdValidationException(null, "PendingReqId has an unvalid format"); + + } + + } + + + @PostConstruct + private void initialize() throws EaafConfigurationException { + log.debug("Initializing " + this.getClass().getName() + " ... "); + + final String pendingReqIdDigistSecret = + baseConfig.getBasicConfiguration(CONFIG_PROP_PENDINGREQUESTID_DIGIST_SECRET); + if (StringUtils.isEmpty(pendingReqIdDigistSecret)) { + throw new EaafConfigurationException("config.08", + new Object[] {CONFIG_PROP_PENDINGREQUESTID_DIGIST_SECRET}); + } + + digistAlgorithm = baseConfig.getBasicConfiguration( + CONFIG_PROP_PENDINGREQUESTID_DIGIST_ALGORITHM, DEFAULT_PENDINGREQUESTID_DIGIST_ALGORITHM); + + maxPendingRequestIdLifeTime = + Integer.parseInt(baseConfig.getBasicConfiguration(CONFIG_PROP_PENDINGREQUESTID_MAX_LIFETIME, + DEFAULT_PENDINGREQUESTID_MAX_LIFETIME)); + + try { + final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WITHHMACSHA256"); + final KeySpec spec = new PBEKeySpec(pendingReqIdDigistSecret.toCharArray(), salt, 10000, 128); + key = keyFactory.generateSecret(spec); + + + } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { + log.error("Can NOT initialize TokenService with configuration object", e); + throw new EaafConfigurationException("config.09", + new Object[] {CONFIG_PROP_PENDINGREQUESTID_DIGIST_SECRET, "Can NOT generate HMAC key"}, + e); + + } + + log.info(this.getClass().getName() + " initialized with digistAlg: {} and maxLifeTime: {}", + digistAlgorithm, maxPendingRequestIdLifeTime); + + } + + private String buildInternalToken(final String internalPendingReqId, final DateTime now) { + return new StringBuilder().append(TOKEN_TEXTUAL_DATE_FORMAT.print(now)).append(TOKEN_SEPARATOR) + .append(internalPendingReqId).toString(); + } + + private byte[] calculateHmac(final String toSign) throws EaafIllegalStateException { + try { + final Mac mac = Mac.getInstance(digistAlgorithm); + mac.init(key); + return mac.doFinal(toSign.getBytes("UTF-8")); + + } catch (UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException e) { + log.error("Can NOT generate secure pendingRequestId", e); + throw new EaafIllegalStateException( + new Object[] {"Can NOT caluclate digist for secure pendingRequestId"}, e); + + } + + } } diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/ServletUtils.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/ServletUtils.java index 38e873e2..0d16e9cd 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/ServletUtils.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/ServletUtils.java @@ -1,43 +1,41 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. + */ package at.gv.egiz.eaaf.core.impl.utils; import javax.servlet.http.HttpServletRequest; public class ServletUtils { - - - public static String getBaseUrl( HttpServletRequest request ) { - if ( ( request.getServerPort() == 80 ) || - ( request.getServerPort() == 443 ) ) - return request.getScheme() + "://" + - request.getServerName() + - request.getContextPath(); - else - return request.getScheme() + "://" + - request.getServerName() + ":" + request.getServerPort() + - request.getContextPath(); - } - + + /** + * Get Context URL from http request. + * + * @param request http Request + * @return Context URL + */ + public static String getBaseUrl(final HttpServletRequest request) { + if ((request.getServerPort() == 80) || (request.getServerPort() == 443)) { + return request.getScheme() + "://" + request.getServerName() + request.getContextPath(); + } else { + return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + + request.getContextPath(); + } + } + } diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/SimplePendingRequestIdGenerationStrategy.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/SimplePendingRequestIdGenerationStrategy.java index 6b8fe9b7..049f7175 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/SimplePendingRequestIdGenerationStrategy.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/SimplePendingRequestIdGenerationStrategy.java @@ -1,38 +1,42 @@ package at.gv.egiz.eaaf.core.impl.utils; -import org.apache.commons.lang3.StringUtils; - import at.gv.egiz.eaaf.core.api.utils.IPendingRequestIdGenerationStrategy; import at.gv.egiz.eaaf.core.exceptions.PendingReqIdValidationException; +import org.apache.commons.lang3.StringUtils; /** - * Simple pendingRequestId generation strategy that facilitates no extended validation - * + * Simple pendingRequestId generation strategy that facilitates no extended validation. + * * @author tlenz * */ -public class SimplePendingRequestIdGenerationStrategy implements IPendingRequestIdGenerationStrategy { - - @Override - public String generateExternalPendingRequestId() { - return Random.nextLongRandom(); - - } - - @Override - public String validateAndGetPendingRequestId(String pendingReqId) throws PendingReqIdValidationException { - return getPendingRequestIdWithOutChecks(pendingReqId); - - } - - @Override - public String getPendingRequestIdWithOutChecks(String externalPendingReqId) throws PendingReqIdValidationException { - if (StringUtils.isEmpty(externalPendingReqId)) - throw new PendingReqIdValidationException(externalPendingReqId, "PendingRequestId is empty or null"); - - - - return externalPendingReqId; - } +public class SimplePendingRequestIdGenerationStrategy + implements IPendingRequestIdGenerationStrategy { + + @Override + public String generateExternalPendingRequestId() { + return Random.nextLongRandom(); + + } + + @Override + public String validateAndGetPendingRequestId(final String pendingReqId) + throws PendingReqIdValidationException { + return getPendingRequestIdWithOutChecks(pendingReqId); + + } + + @Override + public String getPendingRequestIdWithOutChecks(final String externalPendingReqId) + throws PendingReqIdValidationException { + if (StringUtils.isEmpty(externalPendingReqId)) { + throw new PendingReqIdValidationException(externalPendingReqId, + "PendingRequestId is empty or null"); + } + + + + return externalPendingReqId; + } } diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/StreamUtils.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/StreamUtils.java index 530da777..cc784870 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/StreamUtils.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/StreamUtils.java @@ -1,29 +1,22 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. + */ + package at.gv.egiz.eaaf.core.impl.utils; @@ -32,38 +25,37 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.io.PrintStream; /** * Utility methods for streams. - * + * * @author Patrick Peck * @version $Id$ */ public class StreamUtils { - + /** * Compare the contents of two InputStreams. - * + * * @param is1 The 1st InputStream to compare. * @param is2 The 2nd InputStream to compare. - * @return boolean true, if both streams contain the exactly the - * same content, false otherwise. + * @return boolean true, if both streams contain the exactly the same content, + * false otherwise. * @throws IOException An error occurred reading one of the streams. */ - public static boolean compareStreams(InputStream is1, InputStream is2) - throws IOException { - - byte[] buf1 = new byte[256]; - byte[] buf2 = new byte[256]; + public static boolean compareStreams(final InputStream is1, final InputStream is2) + throws IOException { + + final byte[] buf1 = new byte[256]; + final byte[] buf2 = new byte[256]; int length1; int length2; - + try { while (true) { length1 = is1.read(buf1); length2 = is2.read(buf2); - + if (length1 != length2) { return false; } @@ -74,128 +66,125 @@ public class StreamUtils { return false; } } - } catch (IOException e) { + } catch (final IOException e) { throw e; } finally { // close both streams try { is1.close(); is2.close(); - } catch (IOException e) { - // ignore this + } catch (final IOException e) { + e.printStackTrace(); + } } } - + /** * Compare two byte arrays, up to a given maximum length. - * + * * @param b1 1st byte array to compare. * @param b2 2nd byte array to compare. * @param length The maximum number of bytes to compare. - * @return true, if the byte arrays are equal, false - * otherwise. + * @return true, if the byte arrays are equal, false otherwise. */ - private static boolean compareBytes(byte[] b1, byte[] b2, int length) { + private static boolean compareBytes(final byte[] b1, final byte[] b2, final int length) { if (b1.length != b2.length) { return false; } - + for (int i = 0; i < b1.length && i < length; i++) { if (b1[i] != b2[i]) { return false; } } - + return true; } /** * Reads a byte array from a stream. + * * @param in The InputStream to read. * @return The bytes contained in the given InputStream. * @throws IOException on any exception thrown */ - public static byte[] readStream(InputStream in) throws IOException { + public static byte[] readStream(final InputStream in) throws IOException { - ByteArrayOutputStream out = new ByteArrayOutputStream(); + final ByteArrayOutputStream out = new ByteArrayOutputStream(); copyStream(in, out, null); - - /* - ByteArrayOutputStream out = new ByteArrayOutputStream(); - int b; - while ((b = in.read()) >= 0) - out.write(b); - - */ + + /* + * ByteArrayOutputStream out = new ByteArrayOutputStream(); int b; while ((b = in.read()) >= 0) + * out.write(b); + * + */ in.close(); return out.toByteArray(); } /** * Reads a String from a stream, using given encoding. + * * @param in The InputStream to read. - * @param encoding The character encoding to use for converting the bytes - * of the InputStream into a String. - * @return The content of the given InputStream converted into - * a String. + * @param encoding The character encoding to use for converting the bytes of the + * InputStream into a String. + * @return The content of the given InputStream converted into a String. * @throws IOException on any exception thrown */ - public static String readStream(InputStream in, String encoding) throws IOException { - ByteArrayOutputStream out = new ByteArrayOutputStream(); + public static String readStream(final InputStream in, final String encoding) throws IOException { + final ByteArrayOutputStream out = new ByteArrayOutputStream(); copyStream(in, out, null); /* - ByteArrayOutputStream out = new ByteArrayOutputStream(); - int b; - while ((b = in.read()) >= 0) - out.write(b); - */ + * ByteArrayOutputStream out = new ByteArrayOutputStream(); int b; while ((b = in.read()) >= 0) + * out.write(b); + */ in.close(); return out.toString(encoding); } - + /** - * Reads all data (until EOF is reached) from the given source to the - * destination stream. If the destination stream is null, all data is dropped. - * It uses the given buffer to read data and forward it. If the buffer is - * null, this method allocates a buffer. + * Reads all data (until EOF is reached) from the given source to the destination stream. If the + * destination stream is null, all data is dropped. It uses the given buffer to read data and + * forward it. If the buffer is null, this method allocates a buffer. * * @param source The stream providing the data. - * @param destination The stream that takes the data. If this is null, all - * data from source will be read and discarded. - * @param buffer The buffer to use for forwarding. If it is null, the method - * allocates a buffer. - * @exception IOException If reading from the source or writing to the - * destination fails. + * @param destination The stream that takes the data. If this is null, all data from source will + * be read and discarded. + * @param buffer The buffer to use for forwarding. If it is null, the method allocates a buffer. + * @exception IOException If reading from the source or writing to the destination fails. */ - private static void copyStream(InputStream source, OutputStream destination, byte[] buffer) throws IOException { + private static void copyStream(final InputStream source, final OutputStream destination, + byte[] buffer) throws IOException { if (source == null) { throw new NullPointerException("Argument \"source\" must not be null."); } if (buffer == null) { buffer = new byte[8192]; } - + if (destination != null) { int bytesRead; while ((bytesRead = source.read(buffer)) >= 0) { destination.write(buffer, 0, bytesRead); } } else { - while (source.read(buffer) >= 0); - } - } - - /** - * Gets the stack trace of the Throwable passed in as a string. - * @param t The Throwable. - * @return a String representing the stack trace of the Throwable. - */ - public static String getStackTraceAsString(Throwable t) - { - ByteArrayOutputStream stackTraceBIS = new ByteArrayOutputStream(); - t.printStackTrace(new PrintStream(stackTraceBIS)); - return new String(stackTraceBIS.toByteArray()); + while (source.read(buffer) >= 0) { + + } + } } + + // /** + // * Gets the stack trace of the Throwable passed in as a string. + // * + // * @param t The Throwable. + // * @return a String representing the stack trace of the Throwable. + // */ + // public static String getStackTraceAsString(final Throwable t) { + // final ByteArrayOutputStream stackTraceBis = new ByteArrayOutputStream(); + // t.printStackTrace(new PrintStream(stackTraceBis)); + // return new String(stackTraceBis.toByteArray()); + // } } diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/TransactionIDUtils.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/TransactionIDUtils.java deleted file mode 100644 index 2e016848..00000000 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/TransactionIDUtils.java +++ /dev/null @@ -1,101 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.core.impl.utils; - - -import at.gv.egiz.eaaf.core.api.IRequest; - -/** - * @author tlenz - * - */ -public class TransactionIDUtils { - - //MDC variables for logging - public static final String MDC_TRANSACTION_ID = "transactionId"; - public static final String MDC_SESSION_ID = "sessionId"; - public static final String MDC_SERVICEPROVIDER_ID = "oaId"; - - /** - * Set all MDC variables from pending request to this threat context
    - * These includes SessionID, TransactionID, and unique service-provider identifier - * - * @param pendingRequest - */ - public static void setAllLoggingVariables(IRequest pendingRequest) { - setTransactionId(pendingRequest.getUniqueTransactionIdentifier()); - setSessionId(pendingRequest.getUniqueSessionIdentifier()); - setServiceProviderId(pendingRequest.getServiceProviderConfiguration().getUniqueIdentifier()); - - } - - /** - * Remove all MDC variables from this threat context - * - */ - public static void removeAllLoggingVariables() { - removeSessionId(); - removeTransactionId(); - removeServiceProviderId(); - - } - - - public static void setServiceProviderId(String oaUniqueId) { - org.slf4j.MDC.put(MDC_SERVICEPROVIDER_ID, oaUniqueId); - - } - - public static void removeServiceProviderId() { - org.slf4j.MDC.remove(MDC_SERVICEPROVIDER_ID); - - } - - public static void setTransactionId(String pendingRequestID) { - org.slf4j.MDC.put(MDC_TRANSACTION_ID, - "TID-" + pendingRequestID); - - } - - public static void removeTransactionId() { - org.slf4j.MDC.remove(MDC_TRANSACTION_ID); - - } - - public static void setSessionId(String uniqueSessionId) { - org.slf4j.MDC.put(MDC_SESSION_ID, - "SID-" + uniqueSessionId); - - } - - public static void removeSessionId() { - org.slf4j.MDC.remove(MDC_SESSION_ID); - - } - - -} diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/TransactionIdUtils.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/TransactionIdUtils.java new file mode 100644 index 00000000..3875e587 --- /dev/null +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/TransactionIdUtils.java @@ -0,0 +1,94 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.core.impl.utils; + + +import at.gv.egiz.eaaf.core.api.IRequest; + +/** + * Transaction Identifier Utils. + * + * @author tlenz + * + */ +public class TransactionIdUtils { + + // MDC variables for logging + public static final String MDC_TRANSACTION_ID = "transactionId"; + public static final String MDC_SESSION_ID = "sessionId"; + public static final String MDC_SERVICEPROVIDER_ID = "oaId"; + + /** + * Set all MDC variables from pending request to this threat context.
    + * These includes SessionID, TransactionID, and unique service-provider identifier + * + * @param pendingRequest Http request object + */ + public static void setAllLoggingVariables(final IRequest pendingRequest) { + setTransactionId(pendingRequest.getUniqueTransactionIdentifier()); + setSessionId(pendingRequest.getUniqueSessionIdentifier()); + setServiceProviderId(pendingRequest.getServiceProviderConfiguration().getUniqueIdentifier()); + + } + + /** + * Remove all MDC variables from this threat context. + * + */ + public static void removeAllLoggingVariables() { + removeSessionId(); + removeTransactionId(); + removeServiceProviderId(); + + } + + + public static void setServiceProviderId(final String oaUniqueId) { + org.slf4j.MDC.put(MDC_SERVICEPROVIDER_ID, oaUniqueId); + + } + + public static void removeServiceProviderId() { + org.slf4j.MDC.remove(MDC_SERVICEPROVIDER_ID); + + } + + public static void setTransactionId(final String pendingRequestID) { + org.slf4j.MDC.put(MDC_TRANSACTION_ID, "TID-" + pendingRequestID); + + } + + public static void removeTransactionId() { + org.slf4j.MDC.remove(MDC_TRANSACTION_ID); + + } + + public static void setSessionId(final String uniqueSessionId) { + org.slf4j.MDC.put(MDC_SESSION_ID, "SID-" + uniqueSessionId); + + } + + public static void removeSessionId() { + org.slf4j.MDC.remove(MDC_SESSION_ID); + + } + + +} diff --git a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/X509Utils.java b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/X509Utils.java index b3fb42c4..00a31a13 100644 --- a/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/X509Utils.java +++ b/eaaf_core_utils/src/main/java/at/gv/egiz/eaaf/core/impl/utils/X509Utils.java @@ -7,56 +7,45 @@ import javax.security.auth.x500.X500Principal; public class X509Utils { - /** - * Sorts the Certificate Chain by IssuerDN and SubjectDN. The [0]-Element should be the Hostname, - * the last Element should be the Root Certificate. - * - * @param certs - * The first element must be the correct one. - * @return sorted Certificate Chain - */ - public static List sortCertificates( - List certs) - { - int length = certs.size(); - if (certs.size() <= 1) - { - return certs; - } + /** + * Sorts the Certificate Chain by IssuerDN and SubjectDN. The [0]-Element should be the Hostname, + * the last Element should be the Root Certificate. + * + * @param certs The first element must be the correct one. + * @return sorted Certificate Chain + */ + public static List sortCertificates(final List certs) { + final int length = certs.size(); + if (certs.size() <= 1) { + return certs; + } - for (X509Certificate cert : certs) - { - if (cert == null) - { - throw new NullPointerException(); - } - } + for (final X509Certificate cert : certs) { + if (cert == null) { + throw new NullPointerException(); + } + } - for (int i = 0; i < length; i++) - { - boolean found = false; - X500Principal issuer = certs.get(i).getIssuerX500Principal(); - for (int j = i + 1; j < length; j++) - { - X500Principal subject = certs.get(j).getSubjectX500Principal(); - if (issuer.equals(subject)) - { - // sorting necessary? - if (i + 1 != j) - { - X509Certificate tmp = certs.get(i + 1); - certs.set(i + 1, certs.get(j)); - certs.set(j, tmp); - } - found = true; - } - } - if (!found) - { - break; - } - } + for (int i = 0; i < length; i++) { + boolean found = false; + final X500Principal issuer = certs.get(i).getIssuerX500Principal(); + for (int j = i + 1; j < length; j++) { + final X500Principal subject = certs.get(j).getSubjectX500Principal(); + if (issuer.equals(subject)) { + // sorting necessary? + if (i + 1 != j) { + final X509Certificate tmp = certs.get(i + 1); + certs.set(i + 1, certs.get(j)); + certs.set(j, tmp); + } + found = true; + } + } + if (!found) { + break; + } + } - return certs; - } + return certs; + } } diff --git a/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/impl/logging/JUnitTestStatusMessenger.java b/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/impl/logging/JUnitTestStatusMessenger.java index 5cdd404c..be5d95b1 100644 --- a/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/impl/logging/JUnitTestStatusMessenger.java +++ b/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/impl/logging/JUnitTestStatusMessenger.java @@ -3,54 +3,59 @@ package at.gv.egiz.eaaf.core.impl.logging; import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; - import at.gv.egiz.eaaf.core.api.IStatusMessenger; public class JUnitTestStatusMessenger implements IStatusMessenger { - private final Map msgStore = new HashMap<>(); - - @Override - public String getMessage(String messageId, Object[] parameters) { - final String msg = getMessageWithoutDefault(messageId, parameters); - if (msg != null) { - return msg; - - } else { - return MessageFormat.format(messageId, parameters); - - } - - } - - @Override - public String getMessageWithoutDefault(String messageId, Object[] parameters) { - if (messageId != null) { - if (msgStore.containsKey(messageId)) { - return MessageFormat.format(msgStore.get(messageId), parameters); - - } - } - - return null; - } - - @Override - public String getResponseErrorCode(Throwable throwable) { - return null; - } - - @Override - public String mapInternalErrorToExternalError(String intErrorCode) { - return null; - } - - public void addMsg(String msgCode, String msg) { - if (!msgStore.containsKey(msgCode)) { - msgStore.put(msgCode, msg); - - } - - } - + private final Map msgStore = new HashMap<>(); + + @Override + public String getMessage(final String messageId, final Object[] parameters) { + final String msg = getMessageWithoutDefault(messageId, parameters); + if (msg != null) { + return msg; + + } else { + return MessageFormat.format(messageId, parameters); + + } + + } + + @Override + public String getMessageWithoutDefault(final String messageId, final Object[] parameters) { + if (messageId != null) { + if (msgStore.containsKey(messageId)) { + return MessageFormat.format(msgStore.get(messageId), parameters); + + } + } + + return null; + } + + @Override + public String getResponseErrorCode(final Throwable throwable) { + return null; + } + + @Override + public String mapInternalErrorToExternalError(final String intErrorCode) { + return null; + } + + /** + * Add a message into Message-Store. + * + * @param msgCode message-code + * @param msg message + */ + public void addMsg(final String msgCode, final String msg) { + if (!msgStore.containsKey(msgCode)) { + msgStore.put(msgCode, msg); + + } + + } + } diff --git a/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/impl/utils/test/KeyValueUtilsTest.java b/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/impl/utils/test/KeyValueUtilsTest.java new file mode 100644 index 00000000..258c3210 --- /dev/null +++ b/eaaf_core_utils/src/test/java/at/gv/egiz/eaaf/core/impl/utils/test/KeyValueUtilsTest.java @@ -0,0 +1,446 @@ +package at.gv.egiz.eaaf.core.impl.utils.test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.BlockJUnit4ClassRunner; +import com.google.common.collect.Sets; + +@RunWith(BlockJUnit4ClassRunner.class) +public class KeyValueUtilsTest { + + @Test + public void getFirstChildTest_1() { + final String prefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(5); + final String child = RandomStringUtils.randomAlphabetic(2); + final String key = prefix + KeyValueUtils.KEY_DELIMITER + child + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(4); + final String resut = KeyValueUtils.getFirstChildAfterPrefix(key, prefix); + Assert.assertEquals("First child not match", child, resut); + + } + + @Test + public void getFirstChildTest_2() { + final String prefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(5); + final String child = RandomStringUtils.randomAlphabetic(2); + final String key = prefix + KeyValueUtils.KEY_DELIMITER + child; + final String resut = KeyValueUtils.getFirstChildAfterPrefix(key, prefix); + Assert.assertEquals("First child not match", child, resut); + + } + + @Test + public void getFirstChildTest_3() { + final String prefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(5); + final String child = RandomStringUtils.randomAlphabetic(2); + final String key = prefix + KeyValueUtils.KEY_DELIMITER + child; + final String resut = KeyValueUtils.getFirstChildAfterPrefix(key, key); + Assert.assertNull("First child not null", resut); + + } + + @Test + public void getFirstChildTest_4() { + final String prefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(5); + final String child = RandomStringUtils.randomAlphabetic(2); + final String key = prefix + KeyValueUtils.KEY_DELIMITER + child; + final String resut = KeyValueUtils.getFirstChildAfterPrefix( + RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + key, key); + Assert.assertNull("First child not null", resut); + + } + + @Test + public void getFirstChildTest_5() { + final String prefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(5); + final String child = RandomStringUtils.randomAlphabetic(2); + final String key = child + KeyValueUtils.KEY_DELIMITER + prefix; + final String resut = KeyValueUtils.getFirstChildAfterPrefix(key, null); + Assert.assertEquals("First child not match", child, resut); + + } + + @Test + public void getFirstChildTest_6() { + final String prefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(5); + final String child = RandomStringUtils.randomAlphabetic(2); + final String key = prefix + KeyValueUtils.KEY_DELIMITER + child; + final String resut = KeyValueUtils.getFirstChildAfterPrefix(key, key); + Assert.assertNull("First child not null", resut); + + } + + @Test + public void getPrefixFromKey_1() { + final String prefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(5); + final String child = RandomStringUtils.randomAlphabetic(2); + final String key = prefix + KeyValueUtils.KEY_DELIMITER + child; + final String resut = KeyValueUtils.getPrefixFromKey(key, child); + Assert.assertEquals("Prefix not match", prefix, resut); + + } + + @Test + public void getPrefixFromKey_2() { + final String child = RandomStringUtils.randomAlphabetic(2); + final String resut = KeyValueUtils.getPrefixFromKey(null, child); + Assert.assertNull("Prefix not null", resut); + + } + + @Test + public void getPrefixFromKey_3() { + final String prefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(5); + final String key = prefix + KeyValueUtils.KEY_DELIMITER + RandomStringUtils.randomAlphabetic(4); + final String resut = KeyValueUtils.getPrefixFromKey(key, RandomStringUtils.randomAlphabetic(5)); + Assert.assertNull("Prefix not null", resut); + + } + + @Test + public void getPrefixFromKey_4() { + final String prefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(5); + final String child = KeyValueUtils.KEY_DELIMITER + RandomStringUtils.randomAlphabetic(2); + final String key = prefix + child; + final String resut = KeyValueUtils.getPrefixFromKey(key, child); + Assert.assertEquals("Prefix not match", prefix, resut); + + } + + @Test + public void getPrefixFromKey_5() { + final String key = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(5); + final String resut = KeyValueUtils.getPrefixFromKey(key, null); + Assert.assertNull("Prefix not null", resut); + + } + + @Test + public void getRemovePrefixesFromKeys_1() { + final String testPrefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(5); + final Map testMap = generateTestMap(testPrefix, 5, 5); + + final Map result = KeyValueUtils.removePrefixFromKeys(testMap, testPrefix); + Assert.assertNotNull("Result is null", result); + Assert.assertFalse("Result is empty", result.isEmpty()); + Assert.assertEquals("Result size not match", 5, result.size()); + final Iterator> it = result.entrySet().iterator(); + while (it.hasNext()) { + final Entry next = it.next(); + Assert.assertNotNull("Key is null", next.getKey()); + Assert.assertNotNull("Value is null", next.getValue()); + Assert.assertTrue("Key is null", testMap.containsKey(testPrefix + "." + next.getKey())); + Assert.assertEquals("Value not match", testMap.get(testPrefix + "." + next.getKey()), + next.getValue()); + + } + + } + + @Test + public void getSubSetWithPrefixTest_1() { + final String testPrefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(5); + final Map testMap = generateTestMap(testPrefix, 5, 5); + + final Map result = KeyValueUtils.getSubSetWithPrefix(testMap, testPrefix); + Assert.assertNotNull("Result is null", result); + Assert.assertFalse("Result is empty", result.isEmpty()); + Assert.assertEquals("Result size not match", 5, result.size()); + final Iterator> it = result.entrySet().iterator(); + while (it.hasNext()) { + final Entry next = it.next(); + Assert.assertNotNull("Key is null", next.getKey()); + Assert.assertNotNull("Value is null", next.getValue()); + Assert.assertTrue("Key is null", testMap.containsKey(testPrefix + "." + next.getKey())); + Assert.assertEquals("Value not match", testMap.get(testPrefix + "." + next.getKey()), + next.getValue()); + + } + + } + + @Test + public void makeKeysAbsolutTest_1() { + final String absTestPrefixtestPrefix = RandomStringUtils.randomAlphabetic(4) + + KeyValueUtils.KEY_DELIMITER + RandomStringUtils.randomAlphabetic(6) + + KeyValueUtils.KEY_DELIMITER + RandomStringUtils.randomAlphabetic(5); + final String prefix = absTestPrefixtestPrefix + "." + RandomStringUtils.randomAlphabetic(4); + final Map testMap = generateTestMap(prefix, 5, 5); + final Map result = + KeyValueUtils.makeKeysAbsolut(testMap, absTestPrefixtestPrefix, prefix); + + Assert.assertNotNull("Result is null", result); + Assert.assertFalse("Result is empty", result.isEmpty()); + Assert.assertEquals("Result size not match", 10, result.size()); + final Iterator> it = result.entrySet().iterator(); + while (it.hasNext()) { + final Entry next = it.next(); + Assert.assertNotNull("Key is null", next.getKey()); + Assert.assertNotNull("Value is null", next.getValue()); + if (testMap.containsKey(next.getKey())) { + Assert.assertEquals("Value not match", testMap.get(next.getKey()), next.getValue()); + } else { + Assert.assertTrue("Key not found", + testMap.containsKey(next.getKey().substring(absTestPrefixtestPrefix.length() + 1))); + Assert.assertEquals("Value not match", + testMap.get(next.getKey().substring(absTestPrefixtestPrefix.length() + 1)), + next.getValue()); + } + } + } + + @Test + public void getParentKeyTest_1() { + final String testPrefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(5); + final String result = + KeyValueUtils.getParentKey(testPrefix + "." + RandomStringUtils.randomAlphabetic(5)); + Assert.assertNotNull("Result is null", result); + Assert.assertEquals("Parent not match", testPrefix, result); + + } + + @Test + public void getParentKeyTest_2() { + final String result = KeyValueUtils.getParentKey(RandomStringUtils.randomAlphabetic(5)); + Assert.assertNotNull("Result is null", result); + Assert.assertTrue("Result not empty", result.isEmpty()); + + } + + @Test + public void findNextFreeListCoutnerTest_1() { + final String testPrefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(5); + final java.util.List propList = new ArrayList<>(); + propList.add(testPrefix + ".1"); + propList.add(testPrefix + ".2"); + propList.add(testPrefix + ".0"); + propList.add(testPrefix + ".4"); + propList.add(testPrefix + ".3"); + + final int result = KeyValueUtils.findNextFreeListCounter(Sets.newHashSet(propList), testPrefix); + Assert.assertEquals("Next free element not fount", 5, result); + + } + + @Test + public void findNextFreeListCoutnerTest_2() { + final String testPrefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(5); + final java.util.List propList = new ArrayList<>(); + propList.add(testPrefix + ".1"); + propList.add(testPrefix + ".5"); + propList.add(testPrefix + ".0"); + propList.add(testPrefix + ".4"); + propList.add(testPrefix + ".3"); + + final int result = KeyValueUtils.findNextFreeListCounter(Sets.newHashSet(propList), testPrefix); + Assert.assertEquals("Next free element not fount", 6, result); + + } + + @Test + public void findNextFreeListCoutnerTest_3() { + final String testPrefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(5); + final java.util.List propList = new ArrayList<>(); + + final int result = KeyValueUtils.findNextFreeListCounter(Sets.newHashSet(propList), testPrefix); + Assert.assertEquals("Next free element not fount", 0, result); + + } + + @Test + public void findNextFreeListCoutnerTest_4() { + final String testPrefix = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(5); + final java.util.List propList = new ArrayList<>(); + + final int result = + KeyValueUtils.findNextFreeListCounter(propList.stream().toArray(String[]::new), testPrefix); + Assert.assertEquals("Next free element not fount", 0, result); + + } + + @Test + public void normalizeCsvValueStringTest_1() { + final String csv1 = RandomStringUtils.randomAlphanumeric(5); + final String csv2 = RandomStringUtils.randomAlphanumeric(5); + final String csv3 = RandomStringUtils.randomAlphanumeric(5); + final String csv4 = RandomStringUtils.randomAlphanumeric(5); + final String testValue = " " + csv1 + " ," + csv2 + "," + csv3 + "\n," + csv4 + " "; + + final String result = KeyValueUtils.normalizeCsvValueString(testValue); + + Assert.assertNotNull("Result is null", result); + Assert.assertFalse("Result is empty", result.isEmpty()); + final String[] check = result.split(","); + Assert.assertEquals("Result size wrong", 4, check.length); + Assert.assertEquals("Result 1 wrong", csv1, check[0]); + Assert.assertEquals("Result 2 wrong", csv2, check[1]); + Assert.assertEquals("Result 3 wrong", csv3, check[2]); + Assert.assertEquals("Result 4 wrong", csv4, check[3]); + + } + + @Test + public void isCsvValueStringTest_1() { + final String csv1 = RandomStringUtils.randomAlphanumeric(5); + final String csv2 = RandomStringUtils.randomAlphanumeric(5); + final String csv3 = RandomStringUtils.randomAlphanumeric(5); + final String csv4 = RandomStringUtils.randomAlphanumeric(5); + final String testValue = " " + csv1 + " ," + csv2 + "," + csv3 + "\n," + csv4 + " "; + final boolean result = KeyValueUtils.isCsvValueString(testValue); + Assert.assertTrue("CSV value not detected", result); + + } + + @Test + public void isCsvValueStringTest_2() { + final String csv1 = RandomStringUtils.randomAlphanumeric(5); + final String testValue = " " + csv1 + " ,"; + final boolean result = KeyValueUtils.isCsvValueString(testValue); + Assert.assertFalse("CSV value not detected", result); + + } + + @Test + public void isCsvValueStringTest_3() { + final String csv1 = RandomStringUtils.randomAlphanumeric(5); + final String testValue = " " + csv1; + final boolean result = KeyValueUtils.isCsvValueString(testValue); + Assert.assertFalse("CSV value not detected", result); + + } + + @Test + public void getListOfCsvValuesTest_1() { + final String csv1 = RandomStringUtils.randomAlphanumeric(5); + final String csv2 = RandomStringUtils.randomAlphanumeric(5); + final String csv3 = RandomStringUtils.randomAlphanumeric(5); + final String csv4 = RandomStringUtils.randomAlphanumeric(5); + final String testValue = " " + csv1 + " ," + csv2 + "," + csv3 + "\n," + csv4 + " "; + + final List result = KeyValueUtils.getListOfCsvValues(testValue); + + Assert.assertNotNull("Result is null", result); + Assert.assertFalse("Result is empty", result.isEmpty()); + Assert.assertEquals("Result size wrong", 4, result.size()); + Assert.assertEquals("Result 1 wrong", csv1, result.get(0)); + Assert.assertEquals("Result 2 wrong", csv2, result.get(1)); + Assert.assertEquals("Result 3 wrong", csv3, result.get(2)); + Assert.assertEquals("Result 4 wrong", csv4, result.get(3)); + + } + + @Test + public void convertListToMapTest_1() { + final java.util.List propList = new ArrayList<>(); + final String prefix = RandomStringUtils.randomAlphabetic(4) + "."; + final String key1 = RandomStringUtils.randomAlphabetic(5); + final String value1 = RandomStringUtils.randomAlphanumeric(10); + final String key2 = RandomStringUtils.randomAlphabetic(5); + final String value2 = RandomStringUtils.randomAlphanumeric(10); + final String key3 = RandomStringUtils.randomAlphabetic(5); + final String value3 = RandomStringUtils.randomAlphanumeric(10); + final String key4 = RandomStringUtils.randomAlphabetic(5); + final String value4 = RandomStringUtils.randomAlphanumeric(10); + final String key5 = RandomStringUtils.randomAlphabetic(5); + final String value5 = RandomStringUtils.randomAlphanumeric(10); + final String key6 = RandomStringUtils.randomAlphabetic(5); + final String value6 = "=" + RandomStringUtils.randomAlphanumeric(10); + + propList.add(prefix + key1 + "=" + value1); + propList.add(prefix + key2 + "=" + value2); + propList.add(prefix + key3 + "=" + value3); + propList.add(prefix + key4 + "=" + value4); + propList.add(prefix + key5 + "+" + value5); + propList.add(prefix + key6 + "=" + value6); + + final Map result = KeyValueUtils.convertListToMap(propList); + Assert.assertNotNull("Result is null", result); + Assert.assertFalse("Result is empty", result.isEmpty()); + Assert.assertEquals("Result size not match", 5, result.size()); + + Assert.assertTrue("Key1 not found", result.containsKey(prefix + key1)); + Assert.assertEquals("Value1 not found", value1, result.get(prefix + key1)); + Assert.assertTrue("Key2 not found", result.containsKey(prefix + key2)); + Assert.assertEquals("Value2 not found", value2, result.get(prefix + key2)); + Assert.assertTrue("Key3 not found", result.containsKey(prefix + key3)); + Assert.assertEquals("Value3 not found", value3, result.get(prefix + key3)); + Assert.assertTrue("Key4 not found", result.containsKey(prefix + key4)); + Assert.assertEquals("Value4 not found", value4, result.get(prefix + key4)); + + } + + @Test + public void convertListToMapTest_2() { + final java.util.List propList = new ArrayList<>(); + + final Map result = KeyValueUtils.convertListToMap(propList); + Assert.assertNotNull("Result is null", result); + Assert.assertTrue("Result is not empty", result.isEmpty()); + + } + + private Map generateTestMap(final String testPrefix, final int entriesWithPrefix, + final int entriesWithoutPrefix) { + final Map result = new HashMap<>(); + for (int i = 0; i < entriesWithPrefix; i++) { + result.put(testPrefix + KeyValueUtils.KEY_DELIMITER + RandomStringUtils.randomAlphabetic(5), + RandomStringUtils.randomAlphabetic(5)); + } + + final String key = RandomStringUtils.randomAlphabetic(4) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(6) + KeyValueUtils.KEY_DELIMITER + + RandomStringUtils.randomAlphabetic(5); + for (int i = 0; i < entriesWithoutPrefix; i++) { + result.put(key + KeyValueUtils.KEY_DELIMITER + RandomStringUtils.randomAlphabetic(5), + RandomStringUtils.randomAlphabetic(5)); + } + + return result; + + } + + +} diff --git a/eaaf_modules/eaaf_module_auth_sl20/pom.xml b/eaaf_modules/eaaf_module_auth_sl20/pom.xml index 2153dfaa..f293f37e 100644 --- a/eaaf_modules/eaaf_module_auth_sl20/pom.xml +++ b/eaaf_modules/eaaf_module_auth_sl20/pom.xml @@ -1,14 +1,17 @@ - + + 4.0.0 at.gv.egiz.eaaf eaaf_modules - 1.0.14-SNAPSHOT + 1.1.0-SNAPSHOT eaaf_module_auth_sl20 Generic SL2.0 authentication - - + + European Union Public License, version 1.2 (EUPL-1.2) https://opensource.org/licenses/EUPL-1.2 @@ -24,37 +27,37 @@ https://www.egiz.gv.at - + - - at.gv.egiz.eaaf - eaaf-core - ${egiz.eaaf.version} - - - org.bitbucket.b_c - jose4j - - - com.fasterxml.jackson.core - jackson-databind - - - - javax.servlet - javax.servlet-api - provided - + + at.gv.egiz.eaaf + eaaf-core + ${egiz.eaaf.version} + + + org.bitbucket.b_c + jose4j + + + com.fasterxml.jackson.core + jackson-databind + + + + javax.servlet + javax.servlet-api + provided + - + - - - src/main/resources - - - - + + + src/main/resources + + + + org.apache.maven.plugins maven-compiler-plugin @@ -70,13 +73,13 @@ maven-jar-plugin 3.1.1 - - - true - true - true - - + + + true + true + true + + @@ -92,23 +95,23 @@ - + - - maven-surefire-plugin - ${surefire.version} - - 1 - - - - org.apache.maven.surefire - surefire-junit47 - ${surefire.version} - - - - + + maven-surefire-plugin + ${surefire.version} + + 1 + + + + org.apache.maven.surefire + surefire-junit47 + ${surefire.version} + + + + - + \ No newline at end of file diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/AbstractSL20AuthenticationModulImpl.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/AbstractSL20AuthenticationModulImpl.java index 7e306f25..4009796f 100644 --- a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/AbstractSL20AuthenticationModulImpl.java +++ b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/AbstractSL20AuthenticationModulImpl.java @@ -2,129 +2,145 @@ package at.gv.egiz.eaaf.modules.auth.sl20; import java.util.Arrays; import java.util.List; - import javax.annotation.PostConstruct; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; import at.gv.egiz.eaaf.core.api.idp.auth.modules.AuthModule; import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; import at.gv.egiz.eaaf.core.impl.idp.auth.AbstractAuthenticationManager; import at.gv.egiz.eaaf.modules.auth.sl20.utils.SL20Constants; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; /** + * AuthModule to select a Securtiy-Layer 2.0 based authentication process. + * * @author tlenz * */ -public abstract class AbstractSL20AuthenticationModulImpl implements AuthModule { - private static final Logger log = LoggerFactory.getLogger(AbstractSL20AuthenticationModulImpl.class); - - private int priority = 3; - public static final List VDA_TYPE_IDS = Arrays.asList("1", "2", "3", "4"); - - @Autowired(required=true) protected IConfiguration authConfig; - @Autowired(required=true) private AbstractAuthenticationManager authManager; - - @Override - public int getPriority() { - return priority; - } - - /** - * Sets the priority of this module. Default value is {@code 0}. - * @param priority The priority. - */ - public void setPriority(int priority) { - this.priority = priority; - } - - @PostConstruct - protected void initalSL20Authentication() { - //parameter to whiteList - authManager.addHeaderNameToWhiteList(SL20Constants.HTTP_HEADER_SL20_CLIENT_TYPE); - authManager.addHeaderNameToWhiteList(SL20Constants.HTTP_HEADER_SL20_VDA_TYPE); - - } - - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.modules.AuthModule#selectProcess(at.gv.egovernment.moa.id.process.api.ExecutionContext) - */ - @Override - public String selectProcess(ExecutionContext context, IRequest pendingReq) { - final ISPConfiguration spConfig = pendingReq.getServiceProviderConfiguration(); - - if (spConfig == null) { - log.error("Suspect state. NO SP CONFIGURATION IN CONTEXT!"); - throw new RuntimeException("Suspect state. NO SP CONFIGURATION IN CONTEXT!"); - - } - - final String sl20ClientTypeHeader = (String) context.get(SL20Constants.HTTP_HEADER_SL20_CLIENT_TYPE.toLowerCase()); - final String sl20VDATypeHeader = (String) context.get(SL20Constants.HTTP_HEADER_SL20_VDA_TYPE.toLowerCase()); - - if (authConfig.getBasicConfigurationBoolean(getGeneralConfigPropertyNameEnableModule(), getGeneralConfigPropertyNameEnableModuleDefault())) { - if (spConfig != null && - StringUtils.isNotEmpty(spConfig.getConfigurationValue(getSPConfigPropertyNameEnableModule())) && - Boolean.valueOf(spConfig.getConfigurationValue(getSPConfigPropertyNameEnableModule()))) { - log.debug("SL2.0 is enabled for " + spConfig.getUniqueIdentifier()); - log.trace(SL20Constants.HTTP_HEADER_SL20_CLIENT_TYPE + ": " + sl20ClientTypeHeader); - log.trace(SL20Constants.HTTP_HEADER_SL20_VDA_TYPE + ": " + sl20VDATypeHeader); - return getProcessName(); - - } else { - log.trace("SL2.0 is NOT enabled for " + spConfig.getUniqueIdentifier()); - return null; - - } - - } else { - log.trace("SL2.0 is NOT enabled with property: {}", getGeneralConfigPropertyNameEnableModule()); - return null; - - } - - } - - /** - * Get the general configuration-key that holds the enabled key for this authentication module - * - * @return - */ - public abstract String getGeneralConfigPropertyNameEnableModule(); - - /** - * Get the default value of the general configuration-key that holds the enabled key for this authentication module - * - * @return - */ - public abstract boolean getGeneralConfigPropertyNameEnableModuleDefault(); - - /** - * Get the SP specific configuration-key that holds the enabled key for this authentication module - * - * @return configuration key for SP configuration - */ - public abstract String getSPConfigPropertyNameEnableModule(); - - /** - * Get the name of this specific SL2.0 process - * - * @return - */ - public abstract String getProcessName(); - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.modules.AuthModule#getProcessDefinitions() - */ - @Override - public abstract String[] getProcessDefinitions(); +public abstract class AbstractSL20AuthenticationModulImpl implements AuthModule { + private static final Logger log = + LoggerFactory.getLogger(AbstractSL20AuthenticationModulImpl.class); + + private int priority = 3; + public static final List VDA_TYPE_IDS = Arrays.asList("1", "2", "3", "4"); + + @Autowired(required = true) + protected IConfiguration authConfig; + @Autowired(required = true) + private AbstractAuthenticationManager authManager; + + @Override + public int getPriority() { + return priority; + } + + /** + * Sets the priority of this module. Default value is {@code 0}. + * + * @param priority The priority. + */ + public void setPriority(final int priority) { + this.priority = priority; + } + + @PostConstruct + protected void initalSL20Authentication() { + // parameter to whiteList + authManager.addHeaderNameToWhiteList(SL20Constants.HTTP_HEADER_SL20_CLIENT_TYPE); + authManager.addHeaderNameToWhiteList(SL20Constants.HTTP_HEADER_SL20_VDA_TYPE); + + } + + + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.auth.modules.AuthModule#selectProcess(at.gv.egovernment.moa.id.process + * .api.ExecutionContext) + */ + @Override + public String selectProcess(final ExecutionContext context, final IRequest pendingReq) { + final IspConfiguration spConfig = pendingReq.getServiceProviderConfiguration(); + + if (spConfig == null) { + log.error("Suspect state. NO SP CONFIGURATION IN CONTEXT!"); + throw new RuntimeException("Suspect state. NO SP CONFIGURATION IN CONTEXT!"); + + } + + final String sl20ClientTypeHeader = + (String) context.get(SL20Constants.HTTP_HEADER_SL20_CLIENT_TYPE.toLowerCase()); + final String sl20VdaTypeHeader = + (String) context.get(SL20Constants.HTTP_HEADER_SL20_VDA_TYPE.toLowerCase()); + + if (authConfig.getBasicConfigurationBoolean(getGeneralConfigPropertyNameEnableModule(), + getGeneralConfigPropertyNameEnableModuleDefault())) { + if (spConfig != null + && StringUtils + .isNotEmpty(spConfig.getConfigurationValue(getSpConfigPropertyNameEnableModule())) + && Boolean + .valueOf(spConfig.getConfigurationValue(getSpConfigPropertyNameEnableModule()))) { + log.debug("SL2.0 is enabled for " + spConfig.getUniqueIdentifier()); + log.trace(SL20Constants.HTTP_HEADER_SL20_CLIENT_TYPE + ": " + sl20ClientTypeHeader); + log.trace(SL20Constants.HTTP_HEADER_SL20_VDA_TYPE + ": " + sl20VdaTypeHeader); + return getProcessName(); + + } else { + log.trace("SL2.0 is NOT enabled for " + spConfig.getUniqueIdentifier()); + return null; + + } + + } else { + log.trace("SL2.0 is NOT enabled with property: {}", + getGeneralConfigPropertyNameEnableModule()); + return null; + + } + + } + + /** + * Get the general configuration-key that holds the enabled key for this authentication module. + * + * @return + */ + public abstract String getGeneralConfigPropertyNameEnableModule(); + + /** + * Get the default value of the general configuration-key that holds the enabled key for this + * authentication module. + * + * @return + */ + public abstract boolean getGeneralConfigPropertyNameEnableModuleDefault(); + + /** + * Get the SP specific configuration-key that holds the enabled key for this authentication module. + * + * @return configuration key for SP configuration + */ + public abstract String getSpConfigPropertyNameEnableModule(); + + /** + * Get the name of this specific SL2.0 process. + * + * @return + */ + public abstract String getProcessName(); + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.modules.AuthModule#getProcessDefinitions() + */ + @Override + public abstract String[] getProcessDefinitions(); } diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/Constants.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/Constants.java index a1490d2b..a8460911 100644 --- a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/Constants.java +++ b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/Constants.java @@ -1,58 +1,75 @@ package at.gv.egiz.eaaf.modules.auth.sl20; public class Constants { - - public static final String CONFIG_PROP_PREFIX = "modules.sl20"; - public static final String CONFIG_PROP_VDA_ENDPOINT_QUALeID = CONFIG_PROP_PREFIX + ".vda.urls.qualeID."; - - public static final String CONFIG_PROP_VDA_AUTHBLOCK_TRANSFORMATION_ID = CONFIG_PROP_PREFIX + ".vda.authblock.transformation.id"; - public static final String CONFIG_PROP_SECURITY_KEYSTORE_PATH = CONFIG_PROP_PREFIX + ".security.keystore.path"; - public static final String CONFIG_PROP_SECURITY_KEYSTORE_PASSWORD = CONFIG_PROP_PREFIX + ".security.keystore.password"; - public static final String CONFIG_PROP_SECURITY_KEYSTORE_KEY_SIGN_ALIAS = CONFIG_PROP_PREFIX + ".security.sign.alias"; - public static final String CONFIG_PROP_SECURITY_KEYSTORE_KEY_SIGN_PASSWORD = CONFIG_PROP_PREFIX + ".security.sign.password"; - public static final String CONFIG_PROP_SECURITY_KEYSTORE_KEY_ENCRYPTION_ALIAS = CONFIG_PROP_PREFIX + ".security.encryption.alias";; - public static final String CONFIG_PROP_SECURITY_KEYSTORE_KEY_ENCRYPTION_PASSWORD = CONFIG_PROP_PREFIX + ".security.encryption.password"; - - public static final String CONFIG_PROP_VDA_ENDPOINT_QUALeID_DEFAULT_ELEMENT = "default"; - public static final String CONFIG_PROP_VDA_ENDPOINT_QUALeID_DEFAULT = CONFIG_PROP_VDA_ENDPOINT_QUALeID + CONFIG_PROP_VDA_ENDPOINT_QUALeID_DEFAULT_ELEMENT; - public static final String CONFIG_PROP_VDA_ENDPOINT_QUALeID_LIST = CONFIG_PROP_VDA_ENDPOINT_QUALeID + "list"; - public static final String CONFIG_PROP_SP_LIST = CONFIG_PROP_PREFIX + ".sp.entityIds."; - - public static final String CONFIG_PROP_DISABLE_EID_VALIDATION = CONFIG_PROP_PREFIX + ".security.eID.validation.disable"; - public static final String CONFIG_PROP_ENABLE_EID_ENCRYPTION = CONFIG_PROP_PREFIX + ".security.eID.encryption.enabled"; - public static final String CONFIG_PROP_FORCE_EID_ENCRYPTION = CONFIG_PROP_PREFIX + ".security.eID.encryption.required"; - public static final String CONFIG_PROP_FORCE_EID_SIGNED_RESULT = CONFIG_PROP_PREFIX + ".security.eID.signed.result.required"; - - public static final String CONFIG_PROP_IPC_RETURN_URL = CONFIG_PROP_PREFIX + ".testing.ipc.return.url"; - public static final String CONFIG_PROP_HTTP_REDIRECT_CODE = CONFIG_PROP_PREFIX + ".testing.redirect.http.code"; - public static final String CONFIG_PROP_HTTP_REDIRECT_CODE_DEFAULT_VALUE = "303"; - - public static final String CONFIG_PROP_SP_ENABLE_SL20_AUTHENTICATION = "auth.sl20.enabled"; - public static final String CONFIG_PROP_SP_SL20_ENDPOINT_LIST = "auth.sl20.endpoints"; - - public static final String PENDING_REQ_STORAGE_PREFIX = "SL20_AUTH_"; - - /** - * Only dummy data for development!!!!!! - */ - public static final String DUMMY_SIGNING_CERT = - "MIIC9zCCAd8CBFretWcwDQYJKoZIhvcNAQEOBQAwQDELMAkGA1UEBhMCQVQxDTAL\n" + - "BgNVBAoMBEVHSVoxIjAgBgNVBAMMGW93biBkdW1teSBtZXRhZGF0YSBzaWduZXIw\n" + - "HhcNMTgwNDI0MDQ0MTExWhcNMjEwMTE3MDQ0MTExWjBAMQswCQYDVQQGEwJBVDEN\n" + - "MAsGA1UECgwERUdJWjEiMCAGA1UEAwwZb3duIGR1bW15IG1ldGFkYXRhIHNpZ25l\n" + - "cjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJvN3l1pjzlnmoW5trHH\n" + - "Rb1s60QtGNp2v1nfMg1R6h7SzygtmO869v5bqrVBBVGmujslr7W8cZ2DLmJoQx1N\n" + - "WwhccjXTHpNPw0B70qHGch2uRNkqkizSOlwth0Ll2DJtzxTolbajYdg+xppXScUq\n" + - "WNlNZndauPSnB2CESgNkaUou4x4YVSDInugAtLvdLx8rf2YcuidI6UIXxeSZr3VO\n" + - "Z12YtddzcJ+lwh7OX8B0UvLsdYjKjefjEudyuNBmVwLv4K2LsFhSqgE1CAzk3oCb\n" + - "V2A84klaWVPiXoBiOucyouvX781WVp1aCBp0QA8gpJH7/2wRsdPQ90tjMzM7dcgY\n" + - "LDkCAwEAATANBgkqhkiG9w0BAQ4FAAOCAQEAQuYRQcCNLDYU1ItliYz9f28+KDyU\n" + - "8WjF3NDZrlJbGSKQ4n7wkBfxdK3zprmpHadWDB+aZaPt/+voE2FduzPiLUDlpazN\n" + - "60JJ5/YHZ3q9MZvdoNg6rjkpioWatoj/smUkT6oUWL/gp8tH12fOd2oJygBqXMve\n" + - "3y3qVCghnjRaMYuXcScTZcjH9yebkTLygirtw34oGVb7t+HwbtcN65fUIBly6Rcl\n" + - "8NV3pwOKhXFKDAqXUpvhebL4+tWOqPdqfIfGaE6rELfTf3icGY3CQCzDz5Gp0Ptc\n" + - "TfQqm64xnhtAruXNJXWg2ptg+GuQgWnJUgQ8wLNMxw9XdeEwlQo5dL6xmg=="; - - public static final String DUMMY_SIGNING_CERT_FINGERPRINT = "IwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJvN3l1pjzlnmoW"; + + public static final String CONFIG_PROP_PREFIX = "modules.sl20"; + public static final String CONFIG_PROP_VDA_ENDPOINT_QUALeID = + CONFIG_PROP_PREFIX + ".vda.urls.qualeID."; + + public static final String CONFIG_PROP_VDA_AUTHBLOCK_TRANSFORMATION_ID = + CONFIG_PROP_PREFIX + ".vda.authblock.transformation.id"; + public static final String CONFIG_PROP_SECURITY_KEYSTORE_PATH = + CONFIG_PROP_PREFIX + ".security.keystore.path"; + public static final String CONFIG_PROP_SECURITY_KEYSTORE_PASSWORD = + CONFIG_PROP_PREFIX + ".security.keystore.password"; + public static final String CONFIG_PROP_SECURITY_KEYSTORE_KEY_SIGN_ALIAS = + CONFIG_PROP_PREFIX + ".security.sign.alias"; + public static final String CONFIG_PROP_SECURITY_KEYSTORE_KEY_SIGN_PASSWORD = + CONFIG_PROP_PREFIX + ".security.sign.password"; + public static final String CONFIG_PROP_SECURITY_KEYSTORE_KEY_ENCRYPTION_ALIAS = + CONFIG_PROP_PREFIX + ".security.encryption.alias"; + public static final String CONFIG_PROP_SECURITY_KEYSTORE_KEY_ENCRYPTION_PASSWORD = + CONFIG_PROP_PREFIX + ".security.encryption.password"; + + public static final String CONFIG_PROP_VDA_ENDPOINT_QUALeID_DEFAULT_ELEMENT = "default"; + public static final String CONFIG_PROP_VDA_ENDPOINT_QUALeID_DEFAULT = + CONFIG_PROP_VDA_ENDPOINT_QUALeID + CONFIG_PROP_VDA_ENDPOINT_QUALeID_DEFAULT_ELEMENT; + public static final String CONFIG_PROP_VDA_ENDPOINT_QUALeID_LIST = + CONFIG_PROP_VDA_ENDPOINT_QUALeID + "list"; + public static final String CONFIG_PROP_SP_LIST = CONFIG_PROP_PREFIX + ".sp.entityIds."; + + public static final String CONFIG_PROP_DISABLE_EID_VALIDATION = + CONFIG_PROP_PREFIX + ".security.eID.validation.disable"; + public static final String CONFIG_PROP_ENABLE_EID_ENCRYPTION = + CONFIG_PROP_PREFIX + ".security.eID.encryption.enabled"; + public static final String CONFIG_PROP_FORCE_EID_ENCRYPTION = + CONFIG_PROP_PREFIX + ".security.eID.encryption.required"; + public static final String CONFIG_PROP_FORCE_EID_SIGNED_RESULT = + CONFIG_PROP_PREFIX + ".security.eID.signed.result.required"; + + public static final String CONFIG_PROP_IPC_RETURN_URL = + CONFIG_PROP_PREFIX + ".testing.ipc.return.url"; + public static final String CONFIG_PROP_HTTP_REDIRECT_CODE = + CONFIG_PROP_PREFIX + ".testing.redirect.http.code"; + public static final String CONFIG_PROP_HTTP_REDIRECT_CODE_DEFAULT_VALUE = "303"; + + public static final String CONFIG_PROP_SP_ENABLE_SL20_AUTHENTICATION = "auth.sl20.enabled"; + public static final String CONFIG_PROP_SP_SL20_ENDPOINT_LIST = "auth.sl20.endpoints"; + + public static final String PENDING_REQ_STORAGE_PREFIX = "SL20_AUTH_"; + + /** + * Only dummy data for development!!!!!!. + */ + public static final String DUMMY_SIGNING_CERT = + "MIIC9zCCAd8CBFretWcwDQYJKoZIhvcNAQEOBQAwQDELMAkGA1UEBhMCQVQxDTAL\n" + + "BgNVBAoMBEVHSVoxIjAgBgNVBAMMGW93biBkdW1teSBtZXRhZGF0YSBzaWduZXIw\n" + + "HhcNMTgwNDI0MDQ0MTExWhcNMjEwMTE3MDQ0MTExWjBAMQswCQYDVQQGEwJBVDEN\n" + + "MAsGA1UECgwERUdJWjEiMCAGA1UEAwwZb3duIGR1bW15IG1ldGFkYXRhIHNpZ25l\n" + + "cjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJvN3l1pjzlnmoW5trHH\n" + + "Rb1s60QtGNp2v1nfMg1R6h7SzygtmO869v5bqrVBBVGmujslr7W8cZ2DLmJoQx1N\n" + + "WwhccjXTHpNPw0B70qHGch2uRNkqkizSOlwth0Ll2DJtzxTolbajYdg+xppXScUq\n" + + "WNlNZndauPSnB2CESgNkaUou4x4YVSDInugAtLvdLx8rf2YcuidI6UIXxeSZr3VO\n" + + "Z12YtddzcJ+lwh7OX8B0UvLsdYjKjefjEudyuNBmVwLv4K2LsFhSqgE1CAzk3oCb\n" + + "V2A84klaWVPiXoBiOucyouvX781WVp1aCBp0QA8gpJH7/2wRsdPQ90tjMzM7dcgY\n" + + "LDkCAwEAATANBgkqhkiG9w0BAQ4FAAOCAQEAQuYRQcCNLDYU1ItliYz9f28+KDyU\n" + + "8WjF3NDZrlJbGSKQ4n7wkBfxdK3zprmpHadWDB+aZaPt/+voE2FduzPiLUDlpazN\n" + + "60JJ5/YHZ3q9MZvdoNg6rjkpioWatoj/smUkT6oUWL/gp8tH12fOd2oJygBqXMve\n" + + "3y3qVCghnjRaMYuXcScTZcjH9yebkTLygirtw34oGVb7t+HwbtcN65fUIBly6Rcl\n" + + "8NV3pwOKhXFKDAqXUpvhebL4+tWOqPdqfIfGaE6rELfTf3icGY3CQCzDz5Gp0Ptc\n" + + "TfQqm64xnhtAruXNJXWg2ptg+GuQgWnJUgQ8wLNMxw9XdeEwlQo5dL6xmg=="; + + public static final String DUMMY_SIGNING_CERT_FINGERPRINT = + "IwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJvN3l1pjzlnmoW"; } diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/EventCodes.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/EventCodes.java index e19ef5fc..af155206 100644 --- a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/EventCodes.java +++ b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/EventCodes.java @@ -1,16 +1,16 @@ package at.gv.egiz.eaaf.modules.auth.sl20; /** - * Set of event codes uses in Auth-Handler implementation - * + * Set of event codes uses in Auth-Handler implementation. + * * @author tlenz * */ public class EventCodes { - public static final int AUTHPROCESS_SL20_SELECTED = 4111; - public static final int AUTHPROCESS_SL20_ENDPOINT_URL = 4112; - public static final int AUTHPROCESS_SL20_DATAURL_IP = 4113; - - public static final int AUTHPROCESS_SL20_CONSENT_VALID = 4113; + public static final int AUTHPROCESS_SL20_SELECTED = 4111; + public static final int AUTHPROCESS_SL20_ENDPOINT_URL = 4112; + public static final int AUTHPROCESS_SL20_DATAURL_IP = 4113; + + public static final int AUTHPROCESS_SL20_CONSENT_VALID = 4113; } diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/data/VerificationResult.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/data/VerificationResult.java index 0c625a9b..7ca4ea87 100644 --- a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/data/VerificationResult.java +++ b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/data/VerificationResult.java @@ -7,33 +7,34 @@ import com.fasterxml.jackson.databind.JsonNode; public class VerificationResult { - private Boolean validSigned = null; - private List certs = null; - private JsonNode payload = null; - - public VerificationResult(JsonNode payload) { - this.payload = payload; - - } - - public VerificationResult(JsonNode string, List certs, boolean wasValidSigned) { - this.payload = string; - this.certs = certs; - this.validSigned = wasValidSigned; - - } - - public Boolean isValidSigned() { - return validSigned; - } - public List getCertChain() { - return certs; - } - public JsonNode getPayload() { - return payload; - } - - - - + private Boolean validSigned = null; + private List certs = null; + private JsonNode payload = null; + + public VerificationResult(final JsonNode payload) { + this.payload = payload; + + } + + public VerificationResult(final JsonNode string, final List certs, final boolean wasValidSigned) { + this.payload = string; + this.certs = certs; + this.validSigned = wasValidSigned; + + } + + public Boolean isValidSigned() { + return validSigned; + } + + public List getCertChain() { + return certs; + } + + public JsonNode getPayload() { + return payload; + } + + + } diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SL20EidDataValidationException.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SL20EidDataValidationException.java new file mode 100644 index 00000000..a14fbe9e --- /dev/null +++ b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SL20EidDataValidationException.java @@ -0,0 +1,16 @@ +package at.gv.egiz.eaaf.modules.auth.sl20.exceptions; + +public class SL20EidDataValidationException extends SL20Exception { + private static final long serialVersionUID = 1L; + + public SL20EidDataValidationException(final Object[] parameters) { + super("sl20.07", parameters); + + } + + public SL20EidDataValidationException(final Object[] parameters, final Throwable e) { + super("sl20.07", parameters, e); + + } + +} diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SL20Exception.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SL20Exception.java index b23b5ca3..12921ad6 100644 --- a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SL20Exception.java +++ b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SL20Exception.java @@ -1,19 +1,19 @@ package at.gv.egiz.eaaf.modules.auth.sl20.exceptions; -import at.gv.egiz.eaaf.core.exceptions.EAAFAuthenticationException; +import at.gv.egiz.eaaf.core.exceptions.EaafAuthenticationException; -public class SL20Exception extends EAAFAuthenticationException { +public class SL20Exception extends EaafAuthenticationException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public SL20Exception(String messageId, Object[] parameters) { - super(messageId, parameters); + public SL20Exception(final String messageId, final Object[] parameters) { + super(messageId, parameters); - } - - public SL20Exception(String messageId, Object[] parameters, Throwable wrapped) { - super(messageId, parameters, wrapped); + } - } + public SL20Exception(final String messageId, final Object[] parameters, final Throwable wrapped) { + super(messageId, parameters, wrapped); + + } } diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SL20SecurityException.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SL20SecurityException.java index eaf55ba3..c751f2c2 100644 --- a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SL20SecurityException.java +++ b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SL20SecurityException.java @@ -2,19 +2,19 @@ package at.gv.egiz.eaaf.modules.auth.sl20.exceptions; public class SL20SecurityException extends SL20Exception { - private static final long serialVersionUID = 3281385988027147449L; + private static final long serialVersionUID = 3281385988027147449L; - public SL20SecurityException(Object[] parameters) { - super("sl20.05", parameters); - } - - public SL20SecurityException(String parameter) { - super("sl20.05", new Object[] {parameter}); - } - - public SL20SecurityException(Object[] parameters, Throwable wrapped) { - super("sl20.05", parameters, wrapped); + public SL20SecurityException(final Object[] parameters) { + super("sl20.05", parameters); + } - } + public SL20SecurityException(final String parameter) { + super("sl20.05", new Object[] {parameter}); + } + + public SL20SecurityException(final Object[] parameters, final Throwable wrapped) { + super("sl20.05", parameters, wrapped); + + } } diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SL20eIDDataValidationException.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SL20eIDDataValidationException.java deleted file mode 100644 index 24df735a..00000000 --- a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SL20eIDDataValidationException.java +++ /dev/null @@ -1,16 +0,0 @@ -package at.gv.egiz.eaaf.modules.auth.sl20.exceptions; - -public class SL20eIDDataValidationException extends SL20Exception { - private static final long serialVersionUID = 1L; - - public SL20eIDDataValidationException(Object[] parameters) { - super("sl20.07", parameters); - - } - - public SL20eIDDataValidationException(Object[] parameters, Throwable e) { - super("sl20.07", parameters, e); - - } - -} diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SLCommandoBuildException.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SLCommandoBuildException.java deleted file mode 100644 index 1f521ebc..00000000 --- a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SLCommandoBuildException.java +++ /dev/null @@ -1,17 +0,0 @@ -package at.gv.egiz.eaaf.modules.auth.sl20.exceptions; - -public class SLCommandoBuildException extends SL20Exception { - - private static final long serialVersionUID = 1L; - - - public SLCommandoBuildException(String msg) { - super("sl20.01", new Object[]{msg}); - - } - - public SLCommandoBuildException(String msg, Throwable e) { - super("sl20.01", new Object[]{msg}, e); - - } -} diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SLCommandoParserException.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SLCommandoParserException.java deleted file mode 100644 index 60993e69..00000000 --- a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SLCommandoParserException.java +++ /dev/null @@ -1,17 +0,0 @@ -package at.gv.egiz.eaaf.modules.auth.sl20.exceptions; - -public class SLCommandoParserException extends SL20Exception { - - private static final long serialVersionUID = 1L; - - - public SLCommandoParserException(String msg) { - super("sl20.02", new Object[]{msg}); - - } - - public SLCommandoParserException(String msg, Throwable e) { - super("sl20.02", new Object[]{msg}, e); - - } -} diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SlCommandoBuildException.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SlCommandoBuildException.java new file mode 100644 index 00000000..bed1cdb0 --- /dev/null +++ b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SlCommandoBuildException.java @@ -0,0 +1,17 @@ +package at.gv.egiz.eaaf.modules.auth.sl20.exceptions; + +public class SlCommandoBuildException extends SL20Exception { + + private static final long serialVersionUID = 1L; + + + public SlCommandoBuildException(final String msg) { + super("sl20.01", new Object[] {msg}); + + } + + public SlCommandoBuildException(final String msg, final Throwable e) { + super("sl20.01", new Object[] {msg}, e); + + } +} diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SlCommandoParserException.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SlCommandoParserException.java new file mode 100644 index 00000000..dab42631 --- /dev/null +++ b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/exceptions/SlCommandoParserException.java @@ -0,0 +1,17 @@ +package at.gv.egiz.eaaf.modules.auth.sl20.exceptions; + +public class SlCommandoParserException extends SL20Exception { + + private static final long serialVersionUID = 1L; + + + public SlCommandoParserException(final String msg) { + super("sl20.02", new Object[] {msg}); + + } + + public SlCommandoParserException(final String msg, final Throwable e) { + super("sl20.02", new Object[] {msg}, e); + + } +} diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/tasks/AbstractCreateQualEidRequestTask.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/tasks/AbstractCreateQualEidRequestTask.java new file mode 100644 index 00000000..251b516f --- /dev/null +++ b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/tasks/AbstractCreateQualEidRequestTask.java @@ -0,0 +1,250 @@ +package at.gv.egiz.eaaf.modules.auth.sl20.tasks; + +import java.security.cert.CertificateEncodingException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import at.gv.egiz.eaaf.core.api.idp.IConfigurationWithSP; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.exceptions.EaafAuthenticationException; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; +import at.gv.egiz.eaaf.core.impl.utils.IHttpClientFactory; +import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; +import at.gv.egiz.eaaf.core.impl.utils.Random; +import at.gv.egiz.eaaf.core.impl.utils.TransactionIdUtils; +import at.gv.egiz.eaaf.modules.auth.sl20.Constants; +import at.gv.egiz.eaaf.modules.auth.sl20.EventCodes; +import at.gv.egiz.eaaf.modules.auth.sl20.data.VerificationResult; +import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SL20Exception; +import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SlCommandoParserException; +import at.gv.egiz.eaaf.modules.auth.sl20.utils.SL20Constants; +import at.gv.egiz.eaaf.modules.auth.sl20.utils.SL20HttpBindingUtils; +import at.gv.egiz.eaaf.modules.auth.sl20.utils.SL20JsonExtractorUtils; +import at.gv.egiz.eaaf.modules.auth.sl20.utils.SL20JsonBuilderUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.message.BasicNameValuePair; +import org.jose4j.base64url.Base64Url; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + +public abstract class AbstractCreateQualEidRequestTask extends AbstractAuthServletTask { + private static final Logger log = LoggerFactory.getLogger(AbstractCreateQualEidRequestTask.class); + + @Autowired(required = true) + private IHttpClientFactory httpClientFactory; + @Autowired(required = true) + protected IConfigurationWithSP authConfigWithSp; + + @Override + public void execute(final ExecutionContext executionContext, final HttpServletRequest request, + final HttpServletResponse response) throws TaskExecutionException { + + log.debug("Starting SL2.0 authentication process .... "); + + revisionsLogger.logEvent(pendingReq, EventCodes.AUTHPROCESS_SL20_SELECTED, "sl20auth"); + + try { + // get service-provider configuration + final IspConfiguration oaConfig = pendingReq.getServiceProviderConfiguration(); + + if (oaConfig == null) { + log.warn("No SP configuration in pendingReq!"); + throw new RuntimeException("Suspect state. NO SP CONFIGURATION IN PendingRequest!"); + + } + + // get basic configuration parameters + final String vdaQualEidDUrl = extractVdaUrlForSpecificOa(oaConfig, executionContext); + if (StringUtils.isEmpty(vdaQualEidDUrl)) { + log.error("NO VDA URL for qualified eID (" + + Constants.CONFIG_PROP_VDA_ENDPOINT_QUALeID_DEFAULT + ")"); + throw new SL20Exception("sl20.03", new Object[] {"NO VDA URL for qualified eID"}); + + } + + log.debug("Use {} as VDA end-point", vdaQualEidDUrl); + pendingReq.setRawDataToTransaction( + Constants.PENDING_REQ_STORAGE_PREFIX + SL20Constants.SL20_COMMAND_PARAM_EID_RESULT_CCSURL, + vdaQualEidDUrl); + revisionsLogger.logEvent(pendingReq, EventCodes.AUTHPROCESS_SL20_ENDPOINT_URL, vdaQualEidDUrl); + + // create SL2.0 command for qualified eID + final String signedQualEidCommand = buildSignedQualifiedEidCommand(); + + // build request container + final String qualEidReqId = Random.nextProcessReferenceValue(); + final ObjectNode sl20Req = + SL20JsonBuilderUtils.createGenericRequest(qualEidReqId, null, null, signedQualEidCommand); + + // build http POST request + final HttpPost httpReq = new HttpPost(new URIBuilder(vdaQualEidDUrl).build()); + final List parameters = new ArrayList<>(); + parameters.add(new BasicNameValuePair(SL20Constants.PARAM_SL20_REQ_COMMAND_PARAM, + Base64Url.encode(sl20Req.toString().getBytes()))); + httpReq.setEntity(new UrlEncodedFormEntity(parameters)); + + // build http GET request + // URIBuilder sl20ReqUri = new URIBuilder(vdaQualeIDUrl); + // sl20ReqUri.addParameter(SL20Constants.PARAM_SL20_REQ_COMMAND_PARAM, + // Base64Url.encode(sl20Req.toString().getBytes())); + // HttpGet httpReq = new HttpGet(sl20ReqUri.build()); + + // set native client header + httpReq.addHeader(SL20Constants.HTTP_HEADER_SL20_CLIENT_TYPE, + SL20Constants.HTTP_HEADER_VALUE_NATIVE); + + log.trace("Request VDA via SL20 with: " + Base64Url.encode(sl20Req.toString().getBytes())); + + // request VDA + final HttpResponse httpResp = httpClientFactory.getHttpClient(false).execute(httpReq); + + // parse response + log.info("Receive response from VDA ... "); + final JsonNode sl20Resp = SL20JsonExtractorUtils.getSL20ContainerFromResponse(httpResp); + final VerificationResult respPayloadContainer = + SL20JsonExtractorUtils.extractSL20PayLoad(sl20Resp, null, false); + + if (respPayloadContainer.isValidSigned() == null) { + log.debug("Receive unsigned payLoad from VDA"); + + } + + final JsonNode respPayload = respPayloadContainer.getPayload(); + if (respPayload.get(SL20Constants.SL20_COMMAND_CONTAINER_NAME).asText() + .equals(SL20Constants.SL20_COMMAND_IDENTIFIER_REDIRECT)) { + log.debug("Find 'redirect' command in VDA response ... "); + final JsonNode params = SL20JsonExtractorUtils.getJsonObjectValue(respPayload, + SL20Constants.SL20_COMMAND_CONTAINER_PARAMS, true); + final String redirectUrl = SL20JsonExtractorUtils.getStringValue(params, + SL20Constants.SL20_COMMAND_PARAM_GENERAL_REDIRECT_URL, true); + final JsonNode command = SL20JsonExtractorUtils.getJsonObjectValue(params, + SL20Constants.SL20_COMMAND_PARAM_GENERAL_REDIRECT_COMMAND, false); + final String signedCommand = SL20JsonExtractorUtils.getStringValue(params, + SL20Constants.SL20_COMMAND_PARAM_GENERAL_REDIRECT_SIGNEDCOMMAND, false); + + // create forward SL2.0 command + final ObjectNode sl20Forward = sl20Resp.deepCopy(); + SL20JsonBuilderUtils.addOnlyOnceOfTwo(sl20Forward, SL20Constants.SL20_PAYLOAD, + SL20Constants.SL20_SIGNEDPAYLOAD, command.deepCopy(), signedCommand); + + // store pending request + pendingReq.setRawDataToTransaction( + Constants.PENDING_REQ_STORAGE_PREFIX + SL20Constants.SL20_REQID, qualEidReqId); + requestStoreage.storePendingRequest(pendingReq); + + // forward SL2.0 command + // TODO: maybe add SL2ClientType Header from execution context + SL20HttpBindingUtils.writeIntoResponse(request, response, sl20Forward, redirectUrl, + Integer + .parseInt(authConfig.getBasicConfiguration(Constants.CONFIG_PROP_HTTP_REDIRECT_CODE, + Constants.CONFIG_PROP_HTTP_REDIRECT_CODE_DEFAULT_VALUE))); + + } else if (respPayload.get(SL20Constants.SL20_COMMAND_CONTAINER_NAME).asText() + .equals(SL20Constants.SL20_COMMAND_IDENTIFIER_ERROR)) { + JsonNode result = SL20JsonExtractorUtils.getJsonObjectValue(respPayload, + SL20Constants.SL20_COMMAND_CONTAINER_RESULT, false); + if (result == null) { + result = SL20JsonExtractorUtils.getJsonObjectValue(respPayload, + SL20Constants.SL20_COMMAND_CONTAINER_PARAMS, false); + } + + final String errorCode = SL20JsonExtractorUtils.getStringValue(result, + SL20Constants.SL20_COMMAND_PARAM_GENERAL_RESPONSE_ERRORCODE, true); + final String errorMsg = SL20JsonExtractorUtils.getStringValue(result, + SL20Constants.SL20_COMMAND_PARAM_GENERAL_RESPONSE_ERRORMESSAGE, true); + + log.info("Receive SL2.0 error. Code:" + errorCode + " Msg:" + errorMsg); + throw new SL20Exception("sl20.08", new Object[] {errorCode, errorMsg}); + + } else { + // TODO: update to add error handling + log.warn("Received an unrecognized command: " + + respPayload.get(SL20Constants.SL20_COMMAND_CONTAINER_NAME).asText()); + throw new SlCommandoParserException( + "Received an unrecognized command: " + + respPayload.get(SL20Constants.SL20_COMMAND_CONTAINER_NAME).toString()); + } + + + } catch (final EaafAuthenticationException e) { + throw new TaskExecutionException(pendingReq, + "SL2.0 Authentication FAILED. Msg: " + e.getMessage(), e); + + } catch (final Exception e) { + log.warn("SL2.0 Authentication FAILED with a generic error.", e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); + + } finally { + TransactionIdUtils.removeTransactionId(); + TransactionIdUtils.removeSessionId(); + + } + + } + + /** + * Create a implementation specific qualified eID SL2.0 command + * + * @param oaConfig + * + * @return signed JWT token as serialized {@link String} + * @throws CertificateEncodingException In case of certificate parsing error + * @throws SL20Exception In case of a SL2.0 error + */ + protected abstract String buildSignedQualifiedEidCommand() + throws CertificateEncodingException, SL20Exception; + + + private String extractVdaUrlForSpecificOa(final IspConfiguration oaConfig, + final ExecutionContext executionContext) { + + // load SP specific config for development and testing purposes + final String spSpecificVdaEndpoints = + oaConfig.getConfigurationValue(Constants.CONFIG_PROP_SP_SL20_ENDPOINT_LIST); + + // load general configuration + final Map endPointMap = authConfigWithSp + .getBasicConfigurationWithPrefix(Constants.CONFIG_PROP_VDA_ENDPOINT_QUALeID_LIST); + endPointMap.put(Constants.CONFIG_PROP_VDA_ENDPOINT_QUALeID_DEFAULT_ELEMENT, + authConfig.getBasicConfiguration(Constants.CONFIG_PROP_VDA_ENDPOINT_QUALeID_DEFAULT)); + if (StringUtils.isNotEmpty(spSpecificVdaEndpoints)) { + endPointMap.putAll(KeyValueUtils.convertListToMap(KeyValueUtils + .getListOfCsvValues(KeyValueUtils.normalizeCsvValueString(spSpecificVdaEndpoints)))); + log.debug("Find OA specific SL2.0 endpoints. Updating endPoint list ... "); + + } + + log.trace("Find #" + endPointMap.size() + " SL2.0 endpoints ... "); + + // selection based on request Header + final String sl20VdaTypeHeader = + (String) executionContext.get(SL20Constants.HTTP_HEADER_SL20_VDA_TYPE.toLowerCase()); + if (StringUtils.isNotEmpty(sl20VdaTypeHeader)) { + final String vdaUrl = endPointMap.get(sl20VdaTypeHeader); + if (StringUtils.isNotEmpty(vdaUrl)) { + return vdaUrl.trim(); + } else { + log.info("Can NOT find VDA with Id: " + sl20VdaTypeHeader + ". Use default VDA"); + } + + } + + + log.info("NO specific VDA endpoint requested or found. Use default VDA"); + return endPointMap.get(Constants.CONFIG_PROP_VDA_ENDPOINT_QUALeID_DEFAULT_ELEMENT); + + } + +} diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/tasks/AbstractCreateQualeIDRequestTask.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/tasks/AbstractCreateQualeIDRequestTask.java deleted file mode 100644 index 85302d83..00000000 --- a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/tasks/AbstractCreateQualeIDRequestTask.java +++ /dev/null @@ -1,227 +0,0 @@ -package at.gv.egiz.eaaf.modules.auth.sl20.tasks; - -import java.security.cert.CertificateEncodingException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang3.StringUtils; -import org.apache.http.HttpResponse; -import org.apache.http.NameValuePair; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.utils.URIBuilder; -import org.apache.http.message.BasicNameValuePair; -import org.jose4j.base64url.Base64Url; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ObjectNode; - -import at.gv.egiz.eaaf.core.api.idp.IConfigurationWithSP; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; -import at.gv.egiz.eaaf.core.exceptions.EAAFAuthenticationException; -import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; -import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; -import at.gv.egiz.eaaf.core.impl.utils.IHttpClientFactory; -import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; -import at.gv.egiz.eaaf.core.impl.utils.Random; -import at.gv.egiz.eaaf.core.impl.utils.TransactionIDUtils; -import at.gv.egiz.eaaf.modules.auth.sl20.Constants; -import at.gv.egiz.eaaf.modules.auth.sl20.EventCodes; -import at.gv.egiz.eaaf.modules.auth.sl20.data.VerificationResult; -import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SL20Exception; -import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SLCommandoBuildException; -import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SLCommandoParserException; -import at.gv.egiz.eaaf.modules.auth.sl20.utils.SL20Constants; -import at.gv.egiz.eaaf.modules.auth.sl20.utils.SL20HttpBindingUtils; -import at.gv.egiz.eaaf.modules.auth.sl20.utils.SL20JSONBuilderUtils; -import at.gv.egiz.eaaf.modules.auth.sl20.utils.SL20JSONExtractorUtils; - -public abstract class AbstractCreateQualeIDRequestTask extends AbstractAuthServletTask { - private static final Logger log = LoggerFactory.getLogger(AbstractCreateQualeIDRequestTask.class); - - @Autowired(required=true) private IHttpClientFactory httpClientFactory; - @Autowired(required=true) protected IConfigurationWithSP authConfigWithSp; - - @Override - public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) - throws TaskExecutionException { - - log.debug("Starting SL2.0 authentication process .... "); - - revisionsLogger.logEvent(pendingReq, EventCodes.AUTHPROCESS_SL20_SELECTED, "sl20auth"); - - try { - //get service-provider configuration - final ISPConfiguration oaConfig = pendingReq.getServiceProviderConfiguration(); - - if (oaConfig == null) { - log.warn("No SP configuration in pendingReq!"); - throw new RuntimeException("Suspect state. NO SP CONFIGURATION IN PendingRequest!"); - - } - - //get basic configuration parameters - final String vdaQualeIDUrl = extractVDAURLForSpecificOA(oaConfig, executionContext); - if (StringUtils.isEmpty(vdaQualeIDUrl)) { - log.error("NO VDA URL for qualified eID (" + Constants.CONFIG_PROP_VDA_ENDPOINT_QUALeID_DEFAULT + ")"); - throw new SL20Exception("sl20.03", new Object[]{"NO VDA URL for qualified eID"}); - - } - - log.debug("Use {} as VDA end-point", vdaQualeIDUrl) ; - pendingReq.setRawDataToTransaction( - Constants.PENDING_REQ_STORAGE_PREFIX + SL20Constants.SL20_COMMAND_PARAM_EID_RESULT_CCSURL, - vdaQualeIDUrl); - revisionsLogger.logEvent(pendingReq, EventCodes.AUTHPROCESS_SL20_ENDPOINT_URL, vdaQualeIDUrl); - - //create SL2.0 command for qualified eID - final String signedQualeIDCommand = buildSignedQualifiedEIDCommand(); - - //build request container - final String qualeIDReqId = Random.nextProcessReferenceValue(); - final ObjectNode sl20Req = SL20JSONBuilderUtils.createGenericRequest(qualeIDReqId, null, null, signedQualeIDCommand); - - //build http POST request - final HttpPost httpReq = new HttpPost(new URIBuilder(vdaQualeIDUrl).build()); - final List parameters = new ArrayList();; - parameters.add(new BasicNameValuePair(SL20Constants.PARAM_SL20_REQ_COMMAND_PARAM, Base64Url.encode(sl20Req.toString().getBytes()))); - httpReq.setEntity(new UrlEncodedFormEntity(parameters )); - - //build http GET request -// URIBuilder sl20ReqUri = new URIBuilder(vdaQualeIDUrl); -// sl20ReqUri.addParameter(SL20Constants.PARAM_SL20_REQ_COMMAND_PARAM, Base64Url.encode(sl20Req.toString().getBytes())); -// HttpGet httpReq = new HttpGet(sl20ReqUri.build()); - - //set native client header - httpReq.addHeader(SL20Constants.HTTP_HEADER_SL20_CLIENT_TYPE, SL20Constants.HTTP_HEADER_VALUE_NATIVE); - - log.trace("Request VDA via SL20 with: " + Base64Url.encode(sl20Req.toString().getBytes())); - - //request VDA - final HttpResponse httpResp = httpClientFactory.getHttpClient(false).execute(httpReq); - - //parse response - log.info("Receive response from VDA ... "); - final JsonNode sl20Resp = SL20JSONExtractorUtils.getSL20ContainerFromResponse(httpResp); - final VerificationResult respPayloadContainer = SL20JSONExtractorUtils.extractSL20PayLoad(sl20Resp, null, false); - - if (respPayloadContainer.isValidSigned() == null) { - log.debug("Receive unsigned payLoad from VDA"); - - } - - final JsonNode respPayload = respPayloadContainer.getPayload(); - if (respPayload.get(SL20Constants.SL20_COMMAND_CONTAINER_NAME).asText() - .equals(SL20Constants.SL20_COMMAND_IDENTIFIER_REDIRECT)) { - log.debug("Find 'redirect' command in VDA response ... "); - final JsonNode params = SL20JSONExtractorUtils.getJSONObjectValue(respPayload, SL20Constants.SL20_COMMAND_CONTAINER_PARAMS, true); - final String redirectURL = SL20JSONExtractorUtils.getStringValue(params, SL20Constants.SL20_COMMAND_PARAM_GENERAL_REDIRECT_URL, true); - final JsonNode command = SL20JSONExtractorUtils.getJSONObjectValue(params, SL20Constants.SL20_COMMAND_PARAM_GENERAL_REDIRECT_COMMAND, false); - final String signedCommand = SL20JSONExtractorUtils.getStringValue(params, SL20Constants.SL20_COMMAND_PARAM_GENERAL_REDIRECT_SIGNEDCOMMAND, false); - - //create forward SL2.0 command - final ObjectNode sl20Forward = sl20Resp.deepCopy(); - SL20JSONBuilderUtils.addOnlyOnceOfTwo(sl20Forward, - SL20Constants.SL20_PAYLOAD, SL20Constants.SL20_SIGNEDPAYLOAD, - command.deepCopy(), signedCommand); - - //store pending request - pendingReq.setRawDataToTransaction(Constants.PENDING_REQ_STORAGE_PREFIX + SL20Constants.SL20_REQID, - qualeIDReqId); - requestStoreage.storePendingRequest(pendingReq); - - //forward SL2.0 command - //TODO: maybe add SL2ClientType Header from execution context - SL20HttpBindingUtils.writeIntoResponse(request, response, sl20Forward, redirectURL, - Integer.parseInt(authConfig.getBasicConfiguration(Constants.CONFIG_PROP_HTTP_REDIRECT_CODE, Constants.CONFIG_PROP_HTTP_REDIRECT_CODE_DEFAULT_VALUE))); - - } else if (respPayload.get(SL20Constants.SL20_COMMAND_CONTAINER_NAME).asText() - .equals(SL20Constants.SL20_COMMAND_IDENTIFIER_ERROR)) { - JsonNode result = SL20JSONExtractorUtils.getJSONObjectValue(respPayload, SL20Constants.SL20_COMMAND_CONTAINER_RESULT, false); - if (result == null) - result = SL20JSONExtractorUtils.getJSONObjectValue(respPayload, SL20Constants.SL20_COMMAND_CONTAINER_PARAMS, false); - - final String errorCode = SL20JSONExtractorUtils.getStringValue(result, SL20Constants.SL20_COMMAND_PARAM_GENERAL_RESPONSE_ERRORCODE, true); - final String errorMsg = SL20JSONExtractorUtils.getStringValue(result, SL20Constants.SL20_COMMAND_PARAM_GENERAL_RESPONSE_ERRORMESSAGE, true); - - log.info("Receive SL2.0 error. Code:" + errorCode + " Msg:" + errorMsg); - throw new SL20Exception("sl20.08", new Object[]{errorCode, errorMsg}); - - } else { - //TODO: update to add error handling - log.warn("Received an unrecognized command: " + respPayload.get(SL20Constants.SL20_COMMAND_CONTAINER_NAME).asText()); - throw new SLCommandoParserException("Received an unrecognized command: \" + respPayload.get(SL20Constants.SL20_COMMAND_CONTAINER_NAME).getAsString()"); - } - - - } catch (final EAAFAuthenticationException e) { - throw new TaskExecutionException(pendingReq, "SL2.0 Authentication FAILED. Msg: " + e.getMessage(), e); - - } catch (final Exception e) { - log.warn("SL2.0 Authentication FAILED with a generic error.", e); - throw new TaskExecutionException(pendingReq, e.getMessage(), e); - - } finally { - TransactionIDUtils.removeTransactionId(); - TransactionIDUtils.removeSessionId(); - - } - - } - - /** - * Create a implementation specific qualified eID SL2.0 command - * @param oaConfig - * - * @return signed JWT token as serialized {@link String} - * @throws CertificateEncodingException - * @throws SLCommandoBuildException - * @throws SL20Exception - */ - protected abstract String buildSignedQualifiedEIDCommand() throws CertificateEncodingException, SL20Exception; - - - private String extractVDAURLForSpecificOA(ISPConfiguration oaConfig, ExecutionContext executionContext) { - - //load SP specific config for development and testing purposes - final String spSpecificVDAEndpoints = oaConfig.getConfigurationValue(Constants.CONFIG_PROP_SP_SL20_ENDPOINT_LIST); - - //load general configuration - final Map endPointMap = authConfigWithSp.getBasicConfigurationWithPrefix(Constants.CONFIG_PROP_VDA_ENDPOINT_QUALeID_LIST); - endPointMap.put(Constants.CONFIG_PROP_VDA_ENDPOINT_QUALeID_DEFAULT_ELEMENT, authConfig.getBasicConfiguration(Constants.CONFIG_PROP_VDA_ENDPOINT_QUALeID_DEFAULT)); - if (StringUtils.isNotEmpty(spSpecificVDAEndpoints)) { - endPointMap.putAll(KeyValueUtils.convertListToMap( - KeyValueUtils.getListOfCSVValues( - KeyValueUtils.normalizeCSVValueString(spSpecificVDAEndpoints)))); - log.debug("Find OA specific SL2.0 endpoints. Updating endPoint list ... "); - - } - - log.trace("Find #" + endPointMap.size() + " SL2.0 endpoints ... "); - - //selection based on request Header - final String sl20VDATypeHeader = (String) executionContext.get(SL20Constants.HTTP_HEADER_SL20_VDA_TYPE.toLowerCase()); - if (StringUtils.isNotEmpty(sl20VDATypeHeader)) { - final String vdaURL = endPointMap.get(sl20VDATypeHeader); - if (StringUtils.isNotEmpty(vdaURL)) - return vdaURL.trim(); - else - log.info("Can NOT find VDA with Id: " + sl20VDATypeHeader + ". Use default VDA"); - - } - - - log.info("NO specific VDA endpoint requested or found. Use default VDA"); - return endPointMap.get(Constants.CONFIG_PROP_VDA_ENDPOINT_QUALeID_DEFAULT_ELEMENT); - - } - -} diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/tasks/AbstractReceiveQualEidTask.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/tasks/AbstractReceiveQualEidTask.java new file mode 100644 index 00000000..39cfce05 --- /dev/null +++ b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/tasks/AbstractReceiveQualEidTask.java @@ -0,0 +1,344 @@ +package at.gv.egiz.eaaf.modules.auth.sl20.tasks; + +import java.io.IOException; +import java.io.StringWriter; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.exceptions.EaafAuthenticationException; +import at.gv.egiz.eaaf.core.exceptions.EaafStorageException; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; +import at.gv.egiz.eaaf.core.impl.utils.DataUrlBuilder; +import at.gv.egiz.eaaf.core.impl.utils.StreamUtils; +import at.gv.egiz.eaaf.core.impl.utils.TransactionIdUtils; +import at.gv.egiz.eaaf.modules.auth.sl20.Constants; +import at.gv.egiz.eaaf.modules.auth.sl20.EventCodes; +import at.gv.egiz.eaaf.modules.auth.sl20.data.VerificationResult; +import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SL20Exception; +import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SL20SecurityException; +import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SlCommandoParserException; +import at.gv.egiz.eaaf.modules.auth.sl20.utils.IJoseTools; +import at.gv.egiz.eaaf.modules.auth.sl20.utils.JsonMapper; +import at.gv.egiz.eaaf.modules.auth.sl20.utils.SL20Constants; +import at.gv.egiz.eaaf.modules.auth.sl20.utils.SL20JsonBuilderUtils; +import at.gv.egiz.eaaf.modules.auth.sl20.utils.SL20JsonExtractorUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.entity.ContentType; +import org.jose4j.base64url.Base64Url; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + + +public abstract class AbstractReceiveQualEidTask extends AbstractAuthServletTask { + private static final Logger log = LoggerFactory.getLogger(AbstractReceiveQualEidTask.class); + + private static final String PATTERN_PENDING_REQ_ID = "#PENDINGREQID#"; + + @Autowired(required = true) + private IJoseTools joseTools; + + @Override + public void execute(final ExecutionContext executionContext, final HttpServletRequest request, + final HttpServletResponse response) throws TaskExecutionException { + String sl20Result = null; + + try { + log.debug("Receiving SL2.0 response process .... "); + JsonNode sl20ReqObj = null; + + // A-Trust does not SET http-header 'SL2ClientType' with value 'native' + // If A-trust sends an error, its maybe FrontChannel on DataURL + // boolean aTrustErrorWorkAround = false; + + try { + // get SL2.0 command or result from HTTP request + final Map reqParams = getParameters(request); + sl20Result = reqParams.get(SL20Constants.PARAM_SL20_REQ_COMMAND_PARAM); + + if (StringUtils.isEmpty(sl20Result)) { + // Workaround for SIC Handy-Signature, because it sends result in InputStream + final String isReqInput = StreamUtils.readStream(request.getInputStream(), "UTF-8"); + if (StringUtils.isNotEmpty(isReqInput)) { + log.info("Use SIC Handy-Signature work-around!"); + sl20Result = isReqInput.substring("slcommand=".length()); + + } else { + log.info("NO SL2.0 commando or result FOUND."); + throw new SL20Exception("sl20.04", null); + } + + } + + log.trace("Received SL2.0 result: " + sl20Result); + revisionsLogger.logEvent(pendingReq, EventCodes.AUTHPROCESS_SL20_DATAURL_IP, + request.getRemoteAddr()); + + // parse SL2.0 command/result into JSON + try { + sl20ReqObj = + new JsonMapper().getMapper().readTree(Base64Url.decodeToUtf8String(sl20Result)); + + } catch (final JsonParseException e) { + log.warn("SL2.0 command or result is NOT valid JSON.", e); + log.debug("SL2.0 msg: " + sl20Result); + throw new SL20Exception("sl20.02", + new Object[] {"SL2.0 command or result is NOT valid JSON."}, e); + + } + + // check on errorMessage + final VerificationResult payLoadContainerErrorCheck = + SL20JsonExtractorUtils.extractSL20PayLoad(sl20ReqObj, joseTools, false); + if (SL20JsonExtractorUtils + .getStringValue(payLoadContainerErrorCheck.getPayload(), + SL20Constants.SL20_COMMAND_CONTAINER_NAME, true) + .equals(SL20Constants.SL20_COMMAND_IDENTIFIER_ERROR)) { + log.debug("Find " + SL20Constants.SL20_COMMAND_IDENTIFIER_ERROR + " result .... "); + final JsonNode errorResult = SL20JsonExtractorUtils + .extractSL20Result(payLoadContainerErrorCheck.getPayload(), joseTools, false); + final String errorCode = SL20JsonExtractorUtils.getStringValue(errorResult, + SL20Constants.SL20_COMMAND_PARAM_GENERAL_RESPONSE_ERRORCODE, true); + final String errorMsg = SL20JsonExtractorUtils.getStringValue(errorResult, + SL20Constants.SL20_COMMAND_PARAM_GENERAL_RESPONSE_ERRORMESSAGE, false); + + log.info("Receiving errorcode: {} with msg: {} from VDA! Stopping auth-process ... ", + errorCode, errorMsg); + // aTrustErrorWorkAround = true; + throw new SL20Exception("sl20.08", new Object[] {errorCode, errorMsg}); + + } else { + // Receive no error - To request validation + + // validate reqId with inResponseTo + final String sl20ReqId = pendingReq.getRawData( + Constants.PENDING_REQ_STORAGE_PREFIX + SL20Constants.SL20_REQID, String.class); + final String inRespTo = + SL20JsonExtractorUtils.getStringValue(sl20ReqObj, SL20Constants.SL20_INRESPTO, true); + if (sl20ReqId == null || !sl20ReqId.equals(inRespTo)) { + log.info( + "SL20 'reqId': " + sl20ReqId + " does NOT match to 'inResponseTo':" + inRespTo); + throw new SL20SecurityException( + "SL20 'reqId': " + sl20ReqId + " does NOT match to 'inResponseTo':" + inRespTo); + } + + + // validate signature + final VerificationResult payLoadContainer = SL20JsonExtractorUtils + .extractSL20PayLoad(sl20ReqObj, joseTools, authConfig.getBasicConfigurationBoolean( + Constants.CONFIG_PROP_FORCE_EID_SIGNED_RESULT, true)); + + if ((payLoadContainer.isValidSigned() == null || !payLoadContainer.isValidSigned())) { + if (authConfig.getBasicConfigurationBoolean( + Constants.CONFIG_PROP_FORCE_EID_SIGNED_RESULT, true)) { + log.info("SL20 result from VDA was not valid signed"); + throw new SL20SecurityException(new Object[] {"Signature on SL20 result NOT valid."}); + + } else { + log.warn( + "SL20 result from VDA is NOT valid signed, but signatures-verification " + + "is DISABLED by configuration!"); + + } + } + + payLoadContainer.getCertChain(); + + + // extract payloaf + final JsonNode payLoad = payLoadContainer.getPayload(); + + + // handle SL2.0 response payLoad + handleResponsePayLoad(payLoad); + + } + + } catch (final EaafAuthenticationException e) { + log.warn("SL2.0 processing error:", e); + if (sl20Result != null) { + log.debug("Received SL2.0 result: " + sl20Result); + } + pendingReq.setRawDataToTransaction( + Constants.PENDING_REQ_STORAGE_PREFIX + SL20Constants.SL20_COMMAND_IDENTIFIER_ERROR, + new TaskExecutionException(pendingReq, + "SL2.0 Authentication FAILED. Msg: " + e.getMessage(), e)); + + } catch (final Exception e) { + log.warn("ERROR:", e); + log.warn("SL2.0 Authentication FAILED with a generic error.", e); + if (sl20Result != null) { + log.debug("Received SL2.0 result: " + sl20Result); + } + pendingReq.setRawDataToTransaction( + Constants.PENDING_REQ_STORAGE_PREFIX + SL20Constants.SL20_COMMAND_IDENTIFIER_ERROR, + new TaskExecutionException(pendingReq, e.getMessage(), e)); + + } finally { + // store pending request + requestStoreage.storePendingRequest(pendingReq); + + // write SL2.0 response + if (sl20ReqObj != null) { + // buildResponse(request, response, sl20ReqObj, aTrustErrorWorkAround); + buildResponse(request, response, sl20ReqObj); + } else { + buildErrorResponse(request, response, "2000", "General transport Binding error"); + } + + } + + } catch (final Exception e) { + // write internal server errror 500 according to SL2.0 specification, chapter https transport + // binding + log.warn("Can NOT build SL2.0 response. Reason: " + e.getMessage(), e); + if (sl20Result != null) { + log.debug("Received SL2.0 result: " + sl20Result); + } + try { + response.sendError(500, "Internal Server Error."); + + } catch (final IOException e1) { + log.error("Can NOT send error message. SOMETHING IS REALY WRONG!", e); + + } + + } finally { + TransactionIdUtils.removeTransactionId(); + TransactionIdUtils.removeSessionId(); + + } + } + + protected abstract void handleResponsePayLoad(JsonNode payLoad) + throws SlCommandoParserException, SL20Exception, EaafStorageException; + + protected abstract String getResumeEndPoint(); + + private void buildErrorResponse(final HttpServletRequest request, + final HttpServletResponse response, final String errorCode, final String errorMsg) + throws Exception { + final ObjectNode error = SL20JsonBuilderUtils.createErrorCommandResult(errorCode, errorMsg); + final ObjectNode errorCommand = SL20JsonBuilderUtils + .createCommandResponse(SL20Constants.SL20_COMMAND_IDENTIFIER_ERROR, error, null); + + + final ObjectNode respContainer = SL20JsonBuilderUtils + .createGenericResponse(UUID.randomUUID().toString(), null, null, errorCommand, null); + + log.trace("SL20 response to VDA: " + respContainer); + final StringWriter writer = new StringWriter(); + writer.write(respContainer.toString()); + final byte[] content = writer.toString().getBytes("UTF-8"); + response.setStatus(HttpServletResponse.SC_OK); + response.setContentLength(content.length); + response.setContentType(ContentType.APPLICATION_JSON.toString()); + response.getOutputStream().write(content); + + } + + private void buildResponse(final HttpServletRequest request, final HttpServletResponse response, + final JsonNode sl20ReqObj) throws IOException, SL20Exception, URISyntaxException { + // create response + final Map reqParameters = new HashMap<>(); + reqParameters.put(EAAFConstants.PARAM_HTTP_TARGET_PENDINGREQUESTID, + pendingReq.getPendingRequestId()); + final ObjectNode callReqParams = SL20JsonBuilderUtils.createCallCommandParameters( + new DataUrlBuilder().buildDataUrl(pendingReq.getAuthUrl(), getResumeEndPoint(), null), + SL20Constants.SL20_COMMAND_PARAM_GENERAL_CALL_METHOD_GET, false, reqParameters); + final ObjectNode callCommand = SL20JsonBuilderUtils + .createCommand(SL20Constants.SL20_COMMAND_IDENTIFIER_CALL, callReqParams); + + // build first redirect command for app + final ObjectNode redirectOneParams = SL20JsonBuilderUtils.createRedirectCommandParameters( + generateIpcRedirectUrlForDebugging(), callCommand, null, true); + final ObjectNode redirectOneCommand = SL20JsonBuilderUtils + .createCommand(SL20Constants.SL20_COMMAND_IDENTIFIER_REDIRECT, redirectOneParams); + + // build second redirect command for IDP + final ObjectNode redirectTwoParams = SL20JsonBuilderUtils.createRedirectCommandParameters( + new DataUrlBuilder().buildDataUrl(pendingReq.getAuthUrl(), getResumeEndPoint(), + pendingReq.getPendingRequestId()), + redirectOneCommand, null, false); + final ObjectNode redirectTwoCommand = SL20JsonBuilderUtils + .createCommand(SL20Constants.SL20_COMMAND_IDENTIFIER_REDIRECT, redirectTwoParams); + + // build generic SL2.0 response container + final String transactionId = + SL20JsonExtractorUtils.getStringValue(sl20ReqObj, SL20Constants.SL20_TRANSACTIONID, false); + final ObjectNode respContainer = SL20JsonBuilderUtils.createGenericRequest( + UUID.randomUUID().toString(), transactionId, redirectTwoCommand, null); + + if (request.getHeader(SL20Constants.HTTP_HEADER_SL20_CLIENT_TYPE) != null + && request.getHeader(SL20Constants.HTTP_HEADER_SL20_CLIENT_TYPE) + .equals(SL20Constants.HTTP_HEADER_VALUE_NATIVE)) { + log.debug("Client request containts 'native client' header ... "); + log.trace("SL20 response to VDA: " + respContainer); + final StringWriter writer = new StringWriter(); + writer.write(respContainer.toString()); + final byte[] content = writer.toString().getBytes("UTF-8"); + response.setStatus(HttpServletResponse.SC_OK); + response.setContentLength(content.length); + response.setContentType(ContentType.APPLICATION_JSON.toString()); + response.getOutputStream().write(content); + + + } else { + log.info("SL2.0 DataURL communication needs http header: '" + + SL20Constants.HTTP_HEADER_SL20_CLIENT_TYPE + "'"); + + log.debug("Client request containts is no native client ... "); + final URIBuilder clientRedirectUri = + new URIBuilder(new DataUrlBuilder().buildDataUrl(pendingReq.getAuthUrl(), + getResumeEndPoint(), pendingReq.getPendingRequestId())); + response.setStatus(Integer + .parseInt(authConfig.getBasicConfiguration(Constants.CONFIG_PROP_HTTP_REDIRECT_CODE, + Constants.CONFIG_PROP_HTTP_REDIRECT_CODE_DEFAULT_VALUE))); + response.setHeader("Location", clientRedirectUri.build().toString()); + + + // throw new SL20Exception("sl20.06", + // new Object[] {"SL2.0 DataURL communication needs http header: '" + + // SL20Constants.HTTP_HEADER_SL20_CLIENT_TYPE + "'"}); + + } + } + + /** + * Generates a IPC redirect URL that is configured on IDP side. + * + * @return IPC ReturnURL, or null if no URL is configured + */ + private String generateIpcRedirectUrlForDebugging() { + + + String ipcRedirectUrlConfig = + authConfig.getBasicConfiguration(Constants.CONFIG_PROP_IPC_RETURN_URL); + if (StringUtils.isNotEmpty(ipcRedirectUrlConfig)) { + if (ipcRedirectUrlConfig.contains(PATTERN_PENDING_REQ_ID)) { + log.trace("Find 'pendingReqId' pattern in IPC redirect URL. Update url ... "); + ipcRedirectUrlConfig = ipcRedirectUrlConfig.replaceAll("#PENDINGREQID#", + EAAFConstants.PARAM_HTTP_TARGET_PENDINGREQUESTID + "=" + + pendingReq.getPendingRequestId()); + + } + + return ipcRedirectUrlConfig; + } + + return null; + + } + + +} diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/tasks/AbstractReceiveQualeIDTask.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/tasks/AbstractReceiveQualeIDTask.java deleted file mode 100644 index b4039cf9..00000000 --- a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/tasks/AbstractReceiveQualeIDTask.java +++ /dev/null @@ -1,321 +0,0 @@ -package at.gv.egiz.eaaf.modules.auth.sl20.tasks; - -import java.io.IOException; -import java.io.StringWriter; -import java.net.URISyntaxException; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang3.StringUtils; -import org.apache.http.client.utils.URIBuilder; -import org.apache.http.entity.ContentType; -import org.jose4j.base64url.Base64Url; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ObjectNode; - -import at.gv.egiz.eaaf.core.api.data.EAAFConstants; -import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; -import at.gv.egiz.eaaf.core.exceptions.EAAFAuthenticationException; -import at.gv.egiz.eaaf.core.exceptions.EAAFStorageException; -import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; -import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; -import at.gv.egiz.eaaf.core.impl.utils.DataURLBuilder; -import at.gv.egiz.eaaf.core.impl.utils.StreamUtils; -import at.gv.egiz.eaaf.core.impl.utils.TransactionIDUtils; -import at.gv.egiz.eaaf.modules.auth.sl20.Constants; -import at.gv.egiz.eaaf.modules.auth.sl20.EventCodes; -import at.gv.egiz.eaaf.modules.auth.sl20.data.VerificationResult; -import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SL20Exception; -import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SL20SecurityException; -import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SLCommandoParserException; -import at.gv.egiz.eaaf.modules.auth.sl20.utils.IJOSETools; -import at.gv.egiz.eaaf.modules.auth.sl20.utils.JsonMapper; -import at.gv.egiz.eaaf.modules.auth.sl20.utils.SL20Constants; -import at.gv.egiz.eaaf.modules.auth.sl20.utils.SL20JSONBuilderUtils; -import at.gv.egiz.eaaf.modules.auth.sl20.utils.SL20JSONExtractorUtils; - - -public abstract class AbstractReceiveQualeIDTask extends AbstractAuthServletTask { - private static final Logger log = LoggerFactory.getLogger(AbstractReceiveQualeIDTask.class); - - @Autowired(required=true) private IJOSETools joseTools; - - @Override - public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) - throws TaskExecutionException { - String sl20Result = null; - - try { - log.debug("Receiving SL2.0 response process .... "); - JsonNode sl20ReqObj = null; - - //A-Trust does not SET http-header 'SL2ClientType' with value 'native' - //If A-trust sends an error, its maybe FrontChannel on DataURL - //boolean aTrustErrorWorkAround = false; - - try { - //get SL2.0 command or result from HTTP request - final Map reqParams = getParameters(request); - sl20Result = reqParams.get(SL20Constants.PARAM_SL20_REQ_COMMAND_PARAM); - - if (StringUtils.isEmpty(sl20Result)) { - //Workaround for SIC Handy-Signature, because it sends result in InputStream - final String isReqInput = StreamUtils.readStream(request.getInputStream(), "UTF-8"); - if (StringUtils.isNotEmpty(isReqInput)) { - log.info("Use SIC Handy-Signature work-around!"); - sl20Result = isReqInput.substring("slcommand=".length()); - - } else { - log.info("NO SL2.0 commando or result FOUND."); - throw new SL20Exception("sl20.04", null); - } - - } - - log.trace("Received SL2.0 result: " + sl20Result); - revisionsLogger.logEvent(pendingReq, EventCodes.AUTHPROCESS_SL20_DATAURL_IP, request.getRemoteAddr()); - - //parse SL2.0 command/result into JSON - try { - sl20ReqObj = new JsonMapper().getMapper().readTree(Base64Url.decodeToUtf8String(sl20Result)); - - } catch (final JsonParseException e) { - log.warn("SL2.0 command or result is NOT valid JSON.", e); - log.debug("SL2.0 msg: " + sl20Result); - throw new SL20Exception("sl20.02", new Object[]{"SL2.0 command or result is NOT valid JSON."}, e); - - } - - //check on errorMessage - final VerificationResult payLoadContainerErrorCheck = SL20JSONExtractorUtils.extractSL20PayLoad(sl20ReqObj, joseTools, false); - if (SL20JSONExtractorUtils.getStringValue( - payLoadContainerErrorCheck.getPayload(), SL20Constants.SL20_COMMAND_CONTAINER_NAME, true) - .equals(SL20Constants.SL20_COMMAND_IDENTIFIER_ERROR)) { - log.debug("Find " + SL20Constants.SL20_COMMAND_IDENTIFIER_ERROR + " result .... "); - final JsonNode errorResult = SL20JSONExtractorUtils.extractSL20Result(payLoadContainerErrorCheck.getPayload(), joseTools, false); - final String errorCode = SL20JSONExtractorUtils.getStringValue(errorResult, - SL20Constants.SL20_COMMAND_PARAM_GENERAL_RESPONSE_ERRORCODE, true); - final String errorMsg = SL20JSONExtractorUtils.getStringValue(errorResult, - SL20Constants.SL20_COMMAND_PARAM_GENERAL_RESPONSE_ERRORMESSAGE, false); - - log.info("Receiving errorcode: {} with msg: {} from VDA! Stopping auth-process ... ", errorCode, errorMsg); - //aTrustErrorWorkAround = true; - throw new SL20Exception("sl20.08", new Object[] {errorCode, errorMsg}); - - } else { - //Receive no error - To request validation - - //validate reqId with inResponseTo - final String sl20ReqId = pendingReq.getRawData(Constants.PENDING_REQ_STORAGE_PREFIX + SL20Constants.SL20_REQID, String.class); - final String inRespTo = SL20JSONExtractorUtils.getStringValue(sl20ReqObj, SL20Constants.SL20_INRESPTO, true); - if (sl20ReqId == null || !sl20ReqId.equals(inRespTo)) { - log.info("SL20 'reqId': " + sl20ReqId + " does NOT match to 'inResponseTo':" + inRespTo); - throw new SL20SecurityException("SL20 'reqId': " + sl20ReqId + " does NOT match to 'inResponseTo':" + inRespTo); - } - - - //validate signature - final VerificationResult payLoadContainer = SL20JSONExtractorUtils.extractSL20PayLoad( - sl20ReqObj, joseTools, - authConfig.getBasicConfigurationBoolean(Constants.CONFIG_PROP_FORCE_EID_SIGNED_RESULT, true)); - - if ( (payLoadContainer.isValidSigned() == null || !payLoadContainer.isValidSigned())) { - if (authConfig.getBasicConfigurationBoolean(Constants.CONFIG_PROP_FORCE_EID_SIGNED_RESULT, true)) { - log.info("SL20 result from VDA was not valid signed"); - throw new SL20SecurityException(new Object[]{"Signature on SL20 result NOT valid."}); - - } else { - log.warn("SL20 result from VDA is NOT valid signed, but signatures-verification is DISABLED by configuration!"); - - } - } - - payLoadContainer.getCertChain(); - - - //extract payloaf - final JsonNode payLoad = payLoadContainer.getPayload(); - - - //handle SL2.0 response payLoad - handleResponsePayLoad(payLoad); - - } - - } catch (final EAAFAuthenticationException e) { - log.warn("SL2.0 processing error:", e); - if (sl20Result != null) - log.debug("Received SL2.0 result: " + sl20Result); - pendingReq.setRawDataToTransaction( - Constants.PENDING_REQ_STORAGE_PREFIX + SL20Constants.SL20_COMMAND_IDENTIFIER_ERROR, - new TaskExecutionException(pendingReq, "SL2.0 Authentication FAILED. Msg: " + e.getMessage(), e)); - - } catch (final Exception e) { - log.warn("ERROR:", e); - log.warn("SL2.0 Authentication FAILED with a generic error.", e); - if (sl20Result != null) - log.debug("Received SL2.0 result: " + sl20Result); - pendingReq.setRawDataToTransaction( - Constants.PENDING_REQ_STORAGE_PREFIX + SL20Constants.SL20_COMMAND_IDENTIFIER_ERROR, - new TaskExecutionException(pendingReq, e.getMessage(), e)); - - } finally { - //store pending request - requestStoreage.storePendingRequest(pendingReq); - - //write SL2.0 response - if (sl20ReqObj != null) - //buildResponse(request, response, sl20ReqObj, aTrustErrorWorkAround); - buildResponse(request, response, sl20ReqObj); - else - buildErrorResponse(request, response, "2000", "General transport Binding error"); - - } - - } catch (final Exception e) { - //write internal server errror 500 according to SL2.0 specification, chapter https transport binding - log.warn("Can NOT build SL2.0 response. Reason: " + e.getMessage(), e); - if (sl20Result != null) - log.debug("Received SL2.0 result: " + sl20Result); - try { - response.sendError(500, "Internal Server Error."); - - } catch (final IOException e1) { - log.error("Can NOT send error message. SOMETHING IS REALY WRONG!", e); - - } - - } finally { - TransactionIDUtils.removeTransactionId(); - TransactionIDUtils.removeSessionId(); - - } - } - - protected abstract void handleResponsePayLoad(JsonNode payLoad) throws SLCommandoParserException, SL20Exception, EAAFStorageException; - - protected abstract String getResumeEndPoint(); - - private void buildErrorResponse(HttpServletRequest request, HttpServletResponse response, String errorCode, String errorMsg) throws Exception { - final ObjectNode error = SL20JSONBuilderUtils.createErrorCommandResult(errorCode, errorMsg); - final ObjectNode errorCommand = SL20JSONBuilderUtils.createCommandResponse(SL20Constants.SL20_COMMAND_IDENTIFIER_ERROR, error, null); - - - final ObjectNode respContainer = SL20JSONBuilderUtils.createGenericResponse( - UUID.randomUUID().toString(), - null, - null, - errorCommand , - null); - - log.trace("SL20 response to VDA: " + respContainer); - final StringWriter writer = new StringWriter(); - writer.write(respContainer.toString()); - final byte[] content = writer.toString().getBytes("UTF-8"); - response.setStatus(HttpServletResponse.SC_OK); - response.setContentLength(content.length); - response.setContentType(ContentType.APPLICATION_JSON.toString()); - response.getOutputStream().write(content); - - } - - private void buildResponse(HttpServletRequest request, HttpServletResponse response, JsonNode sl20ReqObj) throws IOException, SL20Exception, URISyntaxException { - //create response - final Map reqParameters = new HashMap(); - reqParameters.put(EAAFConstants.PARAM_HTTP_TARGET_PENDINGREQUESTID, pendingReq.getPendingRequestId()); - final ObjectNode callReqParams = SL20JSONBuilderUtils.createCallCommandParameters( - new DataURLBuilder().buildDataURL(pendingReq.getAuthURL(), getResumeEndPoint(), null), - SL20Constants.SL20_COMMAND_PARAM_GENERAL_CALL_METHOD_GET, - false, - reqParameters); - final ObjectNode callCommand = SL20JSONBuilderUtils.createCommand(SL20Constants.SL20_COMMAND_IDENTIFIER_CALL, callReqParams); - - //build first redirect command for app - final ObjectNode redirectOneParams = SL20JSONBuilderUtils.createRedirectCommandParameters( - generateICPRedirectURLForDebugging(), - callCommand, null, true); - final ObjectNode redirectOneCommand = SL20JSONBuilderUtils.createCommand(SL20Constants.SL20_COMMAND_IDENTIFIER_REDIRECT, redirectOneParams); - - //build second redirect command for IDP - final ObjectNode redirectTwoParams = SL20JSONBuilderUtils.createRedirectCommandParameters( - new DataURLBuilder().buildDataURL(pendingReq.getAuthURL(), getResumeEndPoint(), pendingReq.getPendingRequestId()), - redirectOneCommand, null, false); - final ObjectNode redirectTwoCommand = SL20JSONBuilderUtils.createCommand(SL20Constants.SL20_COMMAND_IDENTIFIER_REDIRECT, redirectTwoParams); - - //build generic SL2.0 response container - final String transactionId = SL20JSONExtractorUtils.getStringValue(sl20ReqObj, SL20Constants.SL20_TRANSACTIONID, false); - final ObjectNode respContainer = SL20JSONBuilderUtils.createGenericRequest( - UUID.randomUUID().toString(), - transactionId, - redirectTwoCommand, - null); - - if (request.getHeader(SL20Constants.HTTP_HEADER_SL20_CLIENT_TYPE) != null && - request.getHeader(SL20Constants.HTTP_HEADER_SL20_CLIENT_TYPE).equals(SL20Constants.HTTP_HEADER_VALUE_NATIVE)) { - log.debug("Client request containts 'native client' header ... "); - log.trace("SL20 response to VDA: " + respContainer); - final StringWriter writer = new StringWriter(); - writer.write(respContainer.toString()); - final byte[] content = writer.toString().getBytes("UTF-8"); - response.setStatus(HttpServletResponse.SC_OK); - response.setContentLength(content.length); - response.setContentType(ContentType.APPLICATION_JSON.toString()); - response.getOutputStream().write(content); - - - } else { - log.info("SL2.0 DataURL communication needs http header: '" + SL20Constants.HTTP_HEADER_SL20_CLIENT_TYPE + "'"); - - log.debug("Client request containts is no native client ... "); - final URIBuilder clientRedirectURI = new URIBuilder( - new DataURLBuilder().buildDataURL( - pendingReq.getAuthURL(), getResumeEndPoint(), pendingReq.getPendingRequestId())); - response.setStatus(Integer.parseInt( - authConfig.getBasicConfiguration( - Constants.CONFIG_PROP_HTTP_REDIRECT_CODE, - Constants.CONFIG_PROP_HTTP_REDIRECT_CODE_DEFAULT_VALUE))); - response.setHeader("Location", clientRedirectURI.build().toString()); - - -// throw new SL20Exception("sl20.06", -// new Object[] {"SL2.0 DataURL communication needs http header: '" + SL20Constants.HTTP_HEADER_SL20_CLIENT_TYPE + "'"}); - - } - } - - /** - * Generates a IPC redirect URL that is configured on IDP side - * - * @return IPC ReturnURL, or null if no URL is configured - */ - private String generateICPRedirectURLForDebugging() { - final String PATTERN_PENDING_REQ_ID = "#PENDINGREQID#"; - - String ipcRedirectURLConfig = authConfig.getBasicConfiguration(Constants.CONFIG_PROP_IPC_RETURN_URL); - if (StringUtils.isNotEmpty(ipcRedirectURLConfig)) { - if (ipcRedirectURLConfig.contains(PATTERN_PENDING_REQ_ID)) { - log.trace("Find 'pendingReqId' pattern in IPC redirect URL. Update url ... "); - ipcRedirectURLConfig = ipcRedirectURLConfig.replaceAll( - "#PENDINGREQID#", - EAAFConstants.PARAM_HTTP_TARGET_PENDINGREQUESTID + "=" + pendingReq.getPendingRequestId()); - - } - - return ipcRedirectURLConfig; - } - - return null; - - } - - -} diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/IJOSETools.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/IJOSETools.java deleted file mode 100644 index b124ada7..00000000 --- a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/IJOSETools.java +++ /dev/null @@ -1,87 +0,0 @@ -package at.gv.egiz.eaaf.modules.auth.sl20.utils; - -import java.io.IOException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.cert.X509Certificate; -import java.util.List; - -import javax.annotation.Nonnull; - -import org.jose4j.jwa.AlgorithmConstraints; -import org.jose4j.lang.JoseException; - -import com.fasterxml.jackson.databind.JsonNode; - -import at.gv.egiz.eaaf.modules.auth.sl20.data.VerificationResult; -import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SL20Exception; -import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SLCommandoBuildException; -import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SLCommandoParserException; - -public interface IJOSETools { - - /** - * Create a JWS signature - * - * @param payLoad Payload to sign - * @throws SLCommandoBuildException - */ - public String createSignature(String payLoad) throws SLCommandoBuildException; - - /** - * Validates a signed SL2.0 message - * - * @param serializedContent - * @return - * @throws SLCommandoParserException - * @throws SL20Exception - */ - @Nonnull - public VerificationResult validateSignature(@Nonnull String serializedContent) throws SL20Exception; - - /** - * Validate a JWS signature - * - * @param serializedContent JWS in serialized form - * @param trustedCerts trusted X509 certificates - * @param constraints signature verification constraints - * @return Signature-verification result - * @throws JoseException - * @throws IOException - */ - @Nonnull - public VerificationResult validateSignature(@Nonnull String serializedContent, @Nonnull List trustedCerts, - @Nonnull AlgorithmConstraints constraints) throws JoseException, IOException; - - /** - * Validate a JWS signature - * - * @param serializedContent JWS in serialized form - * @param trustStore with trusted X509 certificates - * @param algconstraints signature verification constraints - * @return Signature-verification result - * @throws JoseException - * @throws IOException - * @throws KeyStoreException - */ - @Nonnull - public VerificationResult validateSignature(@Nonnull String serializedContent, @Nonnull KeyStore trustStore, - @Nonnull AlgorithmConstraints algconstraints) throws JoseException, IOException, KeyStoreException; - - /** - * Get the encryption certificate for SL2.0 End-to-End encryption - * - * @return - */ - public X509Certificate getEncryptionCertificate(); - - /** - * Decrypt a serialized JWE token - * - * @param compactSerialization Serialized JWE token - * @return decrypted payload - * @throws SL20Exception - */ - public JsonNode decryptPayload(String compactSerialization) throws SL20Exception; - -} diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/IJoseTools.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/IJoseTools.java new file mode 100644 index 00000000..caa2e8d8 --- /dev/null +++ b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/IJoseTools.java @@ -0,0 +1,84 @@ +package at.gv.egiz.eaaf.modules.auth.sl20.utils; + +import java.io.IOException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.cert.X509Certificate; +import java.util.List; +import javax.annotation.Nonnull; +import at.gv.egiz.eaaf.modules.auth.sl20.data.VerificationResult; +import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SL20Exception; +import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SlCommandoBuildException; +import org.jose4j.jwa.AlgorithmConstraints; +import org.jose4j.lang.JoseException; +import com.fasterxml.jackson.databind.JsonNode; + +public interface IJoseTools { + + /** + * Create a JWS signature. + * + * @param payLoad Payload to sign + * @throws SlCommandoBuildException In case of a signature creation error + */ + public String createSignature(String payLoad) throws SlCommandoBuildException; + + /** + * Validates a signed SL2.0 message. + * + * @param serializedContent Serialized JWS signature + * @return Verification-result DAO + * @throws SL20Exception In case of a signature validation error + */ + @Nonnull + public VerificationResult validateSignature(@Nonnull String serializedContent) + throws SL20Exception; + + /** + * Validate a JWS signature. + * + * @param serializedContent JWS in serialized form + * @param trustedCerts trusted X509 certificates + * @param constraints signature verification constraints + * @return Signature-verification result + * @throws JoseException In case of a signature verification error + * @throws IOException In case of a general IO error + */ + @Nonnull + public VerificationResult validateSignature(@Nonnull String serializedContent, + @Nonnull List trustedCerts, @Nonnull AlgorithmConstraints constraints) + throws JoseException, IOException; + + /** + * Validate a JWS signature. + * + * @param serializedContent JWS in serialized form + * @param trustStore with trusted X509 certificates + * @param algconstraints signature verification constraints + * @return Signature-verification result + * @throws JoseException In case of a signature verification error + * @throws IOException In case of a general IO error + * @throws KeyStoreException In case of TrustStore error + */ + @Nonnull + public VerificationResult validateSignature(@Nonnull String serializedContent, + @Nonnull KeyStore trustStore, @Nonnull AlgorithmConstraints algconstraints) + throws JoseException, IOException, KeyStoreException; + + /** + * Get the encryption certificate for SL2.0 End-to-End encryption. + * + * @return + */ + public X509Certificate getEncryptionCertificate(); + + /** + * Decrypt a serialized JWE token. + * + * @param compactSerialization Serialized JWE token + * @return decrypted payload + * @throws SL20Exception In case of a decryption error + */ + public JsonNode decryptPayload(String compactSerialization) throws SL20Exception; + +} diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/JsonMapper.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/JsonMapper.java index b33649e1..f38203d2 100644 --- a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/JsonMapper.java +++ b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/JsonMapper.java @@ -18,114 +18,125 @@ import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.type.TypeFactory; import at.gv.egiz.eaaf.core.api.utils.IJsonMapper; -import at.gv.egiz.eaaf.core.exceptions.EAAFJsonMapperException; +import at.gv.egiz.eaaf.core.exceptions.EaafJsonMapperException; public class JsonMapper implements IJsonMapper { - private static final Logger log = LoggerFactory.getLogger(JsonMapper.class); - - private final ObjectMapper mapper = new ObjectMapper(); - - /** - * The default constructor where the default pretty printer is disabled. - */ - public JsonMapper() { - this(false); - - } - - /** - * The constructor. - * @param prettyPrint enables or disables the default pretty printer - */ - public JsonMapper(@NonNull boolean prettyPrint) { - log.trace("Initializing JSON object-mapper ... "); - mapper.configure(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY, true); - mapper.configure(DeserializationFeature.FAIL_ON_TRAILING_TOKENS, true); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES , true); - mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE); - mapper.setVisibility(PropertyAccessor.GETTER, Visibility.PUBLIC_ONLY); - mapper.setVisibility(PropertyAccessor.IS_GETTER, Visibility.PUBLIC_ONLY); - if (prettyPrint) { - mapper.enable(SerializationFeature.INDENT_OUTPUT); - } - - log.debug("JSON object-mapper initialized"); - - } - - - /* (non-Javadoc) - * @at.gv.egiz.eaaf.core.api.utils.IJsonMapper#getMapper() - */ - public ObjectMapper getMapper() { - return mapper; - - } - - - /* (non-Javadoc) - * @see at.gv.egiz.eaaf.core.api.utils.IJsonMapper#serialize(java.lang.Object) - */ - @Override - public String serialize(Object value) throws EAAFJsonMapperException { - try { - return mapper.writeValueAsString(value); - - } catch (final JsonProcessingException e) { - log.warn("JSON mapping FAILED with error: {}", e.getMessage()); - throw new EAAFJsonMapperException(e.getMessage(), e); - - } - - } - - /* (non-Javadoc) - * @see at.gv.egiz.eaaf.core.api.utils.IJsonMapper#deserialize(java.lang.String, java.lang.Class) - */ - @Override - public Object deserialize(String value, Class clazz) throws EAAFJsonMapperException { - try { - if (clazz != null) { - if (clazz.isAssignableFrom(TypeReference.class)) - return mapper.readValue(value, clazz); - else { - final JavaType javaType = TypeFactory.defaultInstance().constructType(clazz); - return mapper.readValue(value, javaType); - - } - - } else - return mapper.readValue(value, Object.class); - - } catch (final IOException e) { - log.warn("JSON mapping FAILED with error: {}", e.getMessage()); - throw new EAAFJsonMapperException(e.getMessage(), e); - - } - - } - - @Override - public Object deserialize(InputStream is, Class clazz) throws EAAFJsonMapperException { - try { - if (clazz != null) { - if (clazz.isAssignableFrom(TypeReference.class)) - return mapper.readValue(is, clazz); - else { - final JavaType javaType = TypeFactory.defaultInstance().constructType(clazz); - return mapper.readValue(is, javaType); - - } - - } else - return mapper.readValue(is, Object.class); - - } catch (final IOException e) { - log.warn("JSON mapping FAILED with error: {}", e.getMessage()); - throw new EAAFJsonMapperException(e.getMessage(), e); - - } - - } - + private static final Logger log = LoggerFactory.getLogger(JsonMapper.class); + + private final ObjectMapper mapper = new ObjectMapper(); + + /** + * The default constructor where the default pretty printer is disabled. + */ + public JsonMapper() { + this(false); + + } + + /** + * The constructor. + * + * @param prettyPrint enables or disables the default pretty printer + */ + public JsonMapper(@NonNull final boolean prettyPrint) { + log.trace("Initializing JSON object-mapper ... "); + mapper.configure(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY, true); + mapper.configure(DeserializationFeature.FAIL_ON_TRAILING_TOKENS, true); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); + mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE); + mapper.setVisibility(PropertyAccessor.GETTER, Visibility.PUBLIC_ONLY); + mapper.setVisibility(PropertyAccessor.IS_GETTER, Visibility.PUBLIC_ONLY); + if (prettyPrint) { + mapper.enable(SerializationFeature.INDENT_OUTPUT); + } + + log.debug("JSON object-mapper initialized"); + + } + + + /* + * (non-Javadoc) + * + * @at.gv.egiz.eaaf.core.api.utils.IJsonMapper#getMapper() + */ + public ObjectMapper getMapper() { + return mapper; + + } + + + /* + * (non-Javadoc) + * + * @see at.gv.egiz.eaaf.core.api.utils.IJsonMapper#serialize(java.lang.Object) + */ + @Override + public String serialize(final Object value) throws EaafJsonMapperException { + try { + return mapper.writeValueAsString(value); + + } catch (final JsonProcessingException e) { + log.warn("JSON mapping FAILED with error: {}", e.getMessage()); + throw new EaafJsonMapperException(e.getMessage(), e); + + } + + } + + /* + * (non-Javadoc) + * + * @see at.gv.egiz.eaaf.core.api.utils.IJsonMapper#deserialize(java.lang.String, java.lang.Class) + */ + @Override + public Object deserialize(final String value, final Class clazz) + throws EaafJsonMapperException { + try { + if (clazz != null) { + if (clazz.isAssignableFrom(TypeReference.class)) { + return mapper.readValue(value, clazz); + } else { + final JavaType javaType = TypeFactory.defaultInstance().constructType(clazz); + return mapper.readValue(value, javaType); + + } + + } else { + return mapper.readValue(value, Object.class); + } + + } catch (final IOException e) { + log.warn("JSON mapping FAILED with error: {}", e.getMessage()); + throw new EaafJsonMapperException(e.getMessage(), e); + + } + + } + + @Override + public Object deserialize(final InputStream is, final Class clazz) + throws EaafJsonMapperException { + try { + if (clazz != null) { + if (clazz.isAssignableFrom(TypeReference.class)) { + return mapper.readValue(is, clazz); + } else { + final JavaType javaType = TypeFactory.defaultInstance().constructType(clazz); + return mapper.readValue(is, javaType); + + } + + } else { + return mapper.readValue(is, Object.class); + } + + } catch (final IOException e) { + log.warn("JSON mapping FAILED with error: {}", e.getMessage()); + throw new EaafJsonMapperException(e.getMessage(), e); + + } + + } + } diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/JsonSecurityUtils.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/JsonSecurityUtils.java index c07c6081..28106377 100644 --- a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/JsonSecurityUtils.java +++ b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/JsonSecurityUtils.java @@ -38,7 +38,7 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonNode; import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; +import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; import at.gv.egiz.eaaf.core.impl.utils.FileUtils; import at.gv.egiz.eaaf.core.impl.utils.KeyStoreUtils; import at.gv.egiz.eaaf.core.impl.utils.X509Utils; @@ -46,375 +46,408 @@ import at.gv.egiz.eaaf.modules.auth.sl20.Constants; import at.gv.egiz.eaaf.modules.auth.sl20.data.VerificationResult; import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SL20Exception; import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SL20SecurityException; -import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SLCommandoBuildException; -import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SLCommandoParserException; +import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SlCommandoBuildException; +import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SlCommandoParserException; @Service -public class JsonSecurityUtils implements IJOSETools{ - private static final Logger log = LoggerFactory.getLogger(JsonSecurityUtils.class); - - @Autowired(required=true) IConfiguration authConfig; - private Key signPrivKey = null; - private X509Certificate[] signCertChain = null; - - private Key encPrivKey = null; - private X509Certificate[] encCertChain = null; - - private List trustedCerts = new ArrayList(); - - private static JsonMapper mapper = new JsonMapper(); - - @PostConstruct - protected void initalize() { - log.info("Initialize SL2.0 authentication security constrains ... "); - try { - if (getKeyStoreFilePath() != null) { - final KeyStore keyStore = KeyStoreUtils.loadKeyStore(getKeyStoreFilePath(), - getKeyStorePassword()); - - //load signing key - signPrivKey = keyStore.getKey(getSigningKeyAlias(), getSigningKeyPassword().toCharArray()); - final Certificate[] certChainSigning = keyStore.getCertificateChain(getSigningKeyAlias()); - signCertChain = new X509Certificate[certChainSigning.length]; - for (int i=0; i trustedCertificates = readCertsFromKeyStore(trustStore); - return validateSignature(serializedContent, trustedCertificates , algconstraints); - - } - - @Override - @NonNull - public VerificationResult validateSignature(@Nonnull String serializedContent, @Nonnull List trustedCerts, @Nonnull AlgorithmConstraints constraints) throws JoseException, IOException { - final JsonWebSignature jws = new JsonWebSignature(); - //set payload - jws.setCompactSerialization(serializedContent); - - //set security constrains - jws.setAlgorithmConstraints(constraints); - - //load signinc certs - Key selectedKey = null; - final List x5cCerts = jws.getCertificateChainHeaderValue(); - final String x5t256 = jws.getX509CertSha256ThumbprintHeaderValue(); - if (x5cCerts != null) { - log.debug("Found x509 certificate in JOSE header ... "); - log.trace("Sorting received X509 certificates ... "); - final List sortedX5cCerts = X509Utils.sortCertificates(x5cCerts); - - if (trustedCerts.contains(sortedX5cCerts.get(0))) { - selectedKey = sortedX5cCerts.get(0).getPublicKey(); - - } else { - log.info("Can NOT find JOSE certificate in truststore."); - try { - log.debug("Cert: " + Base64Utils.encodeToString(sortedX5cCerts.get(0).getEncoded())); - - } catch (final CertificateEncodingException e) { - e.printStackTrace(); - - } - - } - - } else if (StringUtils.isNotEmpty(x5t256)) { - log.debug("Found x5t256 fingerprint in JOSE header .... "); - final X509VerificationKeyResolver x509VerificationKeyResolver = new X509VerificationKeyResolver(trustedCerts); - selectedKey = x509VerificationKeyResolver.resolveKey(jws, Collections.emptyList()); - - } else { - throw new JoseException("JWS contains NO signature certificate or NO certificate fingerprint"); - - } - - if (selectedKey == null) { - throw new JoseException("Can NOT select verification key for JWS. Signature verification FAILED"); - - } - - //set verification key - jws.setKey(selectedKey); - - //load payLoad - return new VerificationResult(mapper.getMapper().readTree(jws.getPayload()), null, jws.verifySignature()) ; - - - } - - @Override - @Nonnull - public VerificationResult validateSignature(@Nonnull String serializedContent) throws SL20Exception { - try { - final AlgorithmConstraints algConstraints = new AlgorithmConstraints(ConstraintType.WHITELIST, - SL20Constants.SL20_ALGORITHM_WHITELIST_SIGNING.toArray(new String[SL20Constants.SL20_ALGORITHM_WHITELIST_SIGNING.size()])); - - final VerificationResult result = validateSignature(serializedContent, trustedCerts, algConstraints); - - if (!result.isValidSigned()) { - log.info("JWS signature invalide. Stopping authentication process ..."); - log.debug("Received JWS msg: " + serializedContent); - throw new SL20SecurityException("JWS signature invalide."); - - } - - log.debug("SL2.0 commando signature validation sucessfull"); - return result; - - } catch (JoseException | JsonParseException e) { - log.warn("SL2.0 commando signature validation FAILED", e); - throw new SL20SecurityException(new Object[]{e.getMessage()}, e); - - } catch (final IOException e) { - log.warn("Decrypted SL2.0 result can not be parsed.", e); - throw new SLCommandoParserException("Decrypted SL2.0 result can not be parsed", e); - - } - - } - - - @Override - public JsonNode decryptPayload(String compactSerialization) throws SL20Exception { - try { - final JsonWebEncryption receiverJwe = new JsonWebEncryption(); - - //set security constrains - receiverJwe.setAlgorithmConstraints( - new AlgorithmConstraints(ConstraintType.WHITELIST, - SL20Constants.SL20_ALGORITHM_WHITELIST_KEYENCRYPTION.toArray(new String[SL20Constants.SL20_ALGORITHM_WHITELIST_KEYENCRYPTION.size()]))); - receiverJwe.setContentEncryptionAlgorithmConstraints( - new AlgorithmConstraints(ConstraintType.WHITELIST, - SL20Constants.SL20_ALGORITHM_WHITELIST_ENCRYPTION.toArray(new String[SL20Constants.SL20_ALGORITHM_WHITELIST_ENCRYPTION.size()]))); - - //set payload - receiverJwe.setCompactSerialization(compactSerialization); - - - //validate key from header against key from config - final List x5cCerts = receiverJwe.getCertificateChainHeaderValue(); - final String x5t256 = receiverJwe.getX509CertSha256ThumbprintHeaderValue(); - if (x5cCerts != null) { - log.debug("Found x509 certificate in JOSE header ... "); - log.trace("Sorting received X509 certificates ... "); - final List sortedX5cCerts = X509Utils.sortCertificates(x5cCerts); - - if (!sortedX5cCerts.get(0).equals(encCertChain[0])) { - log.info("Certificate from JOSE header does NOT match encryption certificate"); - log.debug("JOSE certificate: " + sortedX5cCerts.get(0).toString()); - - try { - log.debug("Cert: " + Base64Utils.encode(sortedX5cCerts.get(0).getEncoded())); - } catch (final CertificateEncodingException e) { - e.printStackTrace(); - } - throw new SL20Exception("sl20.05", new Object[]{"Certificate from JOSE header does NOT match encryption certificate"}); - } - - } else if (StringUtils.isNotEmpty(x5t256)) { - log.debug("Found x5t256 fingerprint in JOSE header .... "); - final String certFingerPrint = X509Util.x5tS256(encCertChain[0]); - if (!certFingerPrint.equals(x5t256)) { - log.info("X5t256 from JOSE header does NOT match encryption certificate"); - log.debug("X5t256 from JOSE header: " + x5t256 + " Encrytption cert: " + certFingerPrint); - throw new SL20Exception("sl20.05", new Object[]{"X5t256 from JOSE header does NOT match encryption certificate"}); - - } - - } else { - log.info("Signed SL2.0 response contains NO signature certificate or NO certificate fingerprint"); - throw new SLCommandoParserException("Signed SL2.0 response contains NO signature certificate or NO certificate fingerprint"); - - } - - //set key - receiverJwe.setKey(encPrivKey); - - - //decrypt payload - return mapper.getMapper().readTree(receiverJwe.getPlaintextString()); - - } catch (final JoseException e) { - log.warn("SL2.0 result decryption FAILED", e); - throw new SL20SecurityException(new Object[]{e.getMessage()}, e); - - } catch ( final JsonParseException e) { - log.warn("Decrypted SL2.0 result is NOT a valid JSON.", e); - throw new SLCommandoParserException("Decrypted SL2.0 result is NOT a valid JSON.", e); - - } catch (final IOException e) { - log.warn("Decrypted SL2.0 result can not be parsed.", e); - throw new SLCommandoParserException("Decrypted SL2.0 result can not be parsed", e); - } - - } - - - - @Override - public X509Certificate getEncryptionCertificate() { - //TODO: maybe update after SL2.0 update on encryption certificate parts - if (encCertChain !=null && encCertChain.length > 0) - return encCertChain[0]; - else - return null; - } - - private String getKeyStoreFilePath() throws EAAFConfigurationException, MalformedURLException { - return FileUtils.makeAbsoluteURL( - authConfig.getBasicConfiguration(Constants.CONFIG_PROP_SECURITY_KEYSTORE_PATH), - authConfig.getConfigurationRootDirectory()); - } - - private String getKeyStorePassword() { - String value = authConfig.getBasicConfiguration(Constants.CONFIG_PROP_SECURITY_KEYSTORE_PASSWORD); - if (value != null) - value = value.trim(); - - return value; - - } - - private String getSigningKeyAlias() { - String value = authConfig.getBasicConfiguration( - Constants.CONFIG_PROP_SECURITY_KEYSTORE_KEY_SIGN_ALIAS).trim(); - if (value != null) - value = value.trim(); - - return value; - } - - private String getSigningKeyPassword() { - String value = authConfig.getBasicConfiguration( - Constants.CONFIG_PROP_SECURITY_KEYSTORE_KEY_SIGN_PASSWORD).trim(); - if (value != null) - value = value.trim(); - - return value; - } - - private String getEncryptionKeyAlias() { - String value = authConfig.getBasicConfiguration( - Constants.CONFIG_PROP_SECURITY_KEYSTORE_KEY_ENCRYPTION_ALIAS).trim(); - if (value != null) - value = value.trim(); - - return value; - } - - private String getEncryptionKeyPassword() { - String value = authConfig.getBasicConfiguration( - Constants.CONFIG_PROP_SECURITY_KEYSTORE_KEY_ENCRYPTION_PASSWORD).trim(); - if (value != null) - value = value.trim(); - - return value; - } - - @Nonnull - private List readCertsFromKeyStore(@Nonnull KeyStore keyStore) throws KeyStoreException { - final List result = new ArrayList<>(); - - final Enumeration aliases = keyStore.aliases(); - while(aliases.hasMoreElements()) { - final String el = aliases.nextElement(); - log.trace("Process TrustStoreEntry: " + el); - if (keyStore.isCertificateEntry(el)) { - final Certificate cert = keyStore.getCertificate(el); - if (cert != null && cert instanceof X509Certificate) - result.add((X509Certificate) cert); - else - log.info("Can not process entry: " + el + ". Reason: " + cert.toString()); - - } - } - - return Collections.unmodifiableList(result); - } - +public class JsonSecurityUtils implements IJoseTools { + private static final Logger log = LoggerFactory.getLogger(JsonSecurityUtils.class); + + @Autowired(required = true) + IConfiguration authConfig; + private Key signPrivKey = null; + private X509Certificate[] signCertChain = null; + + private Key encPrivKey = null; + private X509Certificate[] encCertChain = null; + + private List trustedCerts = new ArrayList<>(); + + private static JsonMapper mapper = new JsonMapper(); + + @PostConstruct + protected void initalize() { + log.info("Initialize SL2.0 authentication security constrains ... "); + try { + if (getKeyStoreFilePath() != null) { + final KeyStore keyStore = + KeyStoreUtils.loadKeyStore(getKeyStoreFilePath(), getKeyStorePassword()); + + // load signing key + signPrivKey = keyStore.getKey(getSigningKeyAlias(), getSigningKeyPassword().toCharArray()); + final Certificate[] certChainSigning = keyStore.getCertificateChain(getSigningKeyAlias()); + signCertChain = new X509Certificate[certChainSigning.length]; + for (int i = 0; i < certChainSigning.length; i++) { + if (certChainSigning[i] instanceof X509Certificate) { + signCertChain[i] = (X509Certificate) certChainSigning[i]; + } else { + log.warn("NO X509 certificate for signing: " + certChainSigning[i].getType()); + } + + } + + // load encryption key + try { + encPrivKey = + keyStore.getKey(getEncryptionKeyAlias(), getEncryptionKeyPassword().toCharArray()); + if (encPrivKey != null) { + final Certificate[] certChainEncryption = + keyStore.getCertificateChain(getEncryptionKeyAlias()); + encCertChain = new X509Certificate[certChainEncryption.length]; + for (int i = 0; i < certChainEncryption.length; i++) { + if (certChainEncryption[i] instanceof X509Certificate) { + encCertChain[i] = (X509Certificate) certChainEncryption[i]; + } else { + log.warn("NO X509 certificate for encryption: " + certChainEncryption[i].getType()); + } + } + } else { + log.info("No encryption key for SL2.0 found. End-to-End encryption is not used."); + } + + } catch (final Exception e) { + log.warn("No encryption key for SL2.0 found. End-to-End encryption is not used. Reason: " + + e.getMessage(), e); + + } + + // load trusted certificates + trustedCerts = readCertsFromKeyStore(keyStore); + + // some short validation + if (signPrivKey == null || !(signPrivKey instanceof PrivateKey)) { + log.info("Can NOT open privateKey for SL2.0 signing. KeyStore=" + getKeyStoreFilePath()); + throw new SL20Exception("sl20.03", new Object[] {"Can NOT open private key for signing"}); + + } + + if (signCertChain == null || signCertChain.length == 0) { + log.info("NO certificate for SL2.0 signing. KeyStore=" + getKeyStoreFilePath()); + throw new SL20Exception("sl20.03", new Object[] {"NO certificate for SL2.0 signing"}); + + } + + log.info("SL2.0 authentication security constrains initialized."); + + } else { + log.info("NO SL2.0 authentication security configuration. Initialization was skipped"); + } + + } catch (final Exception e) { + log.error("SL2.0 security constrains initialization FAILED.", e); + + } + + } + + @Override + public String createSignature(final String payLoad) throws SlCommandoBuildException { + try { + final JsonWebSignature jws = new JsonWebSignature(); + + // set payload + jws.setPayload(payLoad); + + // set basic header + jws.setContentTypeHeaderValue(SL20Constants.SL20_CONTENTTYPE_SIGNED_COMMAND); + + // set signing information + jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256); + jws.setKey(signPrivKey); + + // TODO: + jws.setCertificateChainHeaderValue(signCertChain); + jws.setX509CertSha256ThumbprintHeaderValue(signCertChain[0]); + + return jws.getCompactSerialization(); + + } catch (final JoseException e) { + log.warn("Can NOT sign SL2.0 command.", e); + throw new SlCommandoBuildException("Can NOT sign SL2.0 command.", e); + + } + + } + + @Override + public VerificationResult validateSignature(final String serializedContent, + final KeyStore trustStore, final AlgorithmConstraints algconstraints) + throws JoseException, IOException, KeyStoreException { + final List trustedCertificates = readCertsFromKeyStore(trustStore); + return validateSignature(serializedContent, trustedCertificates, algconstraints); + + } + + @Override + @NonNull + public VerificationResult validateSignature(@Nonnull final String serializedContent, + @Nonnull final List trustedCerts, + @Nonnull final AlgorithmConstraints constraints) throws JoseException, IOException { + final JsonWebSignature jws = new JsonWebSignature(); + // set payload + jws.setCompactSerialization(serializedContent); + + // set security constrains + jws.setAlgorithmConstraints(constraints); + + // load signinc certs + Key selectedKey = null; + final List x5cCerts = jws.getCertificateChainHeaderValue(); + final String x5t256 = jws.getX509CertSha256ThumbprintHeaderValue(); + if (x5cCerts != null) { + log.debug("Found x509 certificate in JOSE header ... "); + log.trace("Sorting received X509 certificates ... "); + final List sortedX5cCerts = X509Utils.sortCertificates(x5cCerts); + + if (trustedCerts.contains(sortedX5cCerts.get(0))) { + selectedKey = sortedX5cCerts.get(0).getPublicKey(); + + } else { + log.info("Can NOT find JOSE certificate in truststore."); + try { + log.debug("Cert: " + Base64Utils.encodeToString(sortedX5cCerts.get(0).getEncoded())); + + } catch (final CertificateEncodingException e) { + e.printStackTrace(); + + } + + } + + } else if (StringUtils.isNotEmpty(x5t256)) { + log.debug("Found x5t256 fingerprint in JOSE header .... "); + final X509VerificationKeyResolver x509VerificationKeyResolver = + new X509VerificationKeyResolver(trustedCerts); + selectedKey = + x509VerificationKeyResolver.resolveKey(jws, Collections.emptyList()); + + } else { + throw new JoseException( + "JWS contains NO signature certificate or NO certificate fingerprint"); + + } + + if (selectedKey == null) { + throw new JoseException( + "Can NOT select verification key for JWS. Signature verification FAILED"); + + } + + // set verification key + jws.setKey(selectedKey); + + // load payLoad + return new VerificationResult(mapper.getMapper().readTree(jws.getPayload()), null, + jws.verifySignature()); + + + } + + @Override + @Nonnull + public VerificationResult validateSignature(@Nonnull final String serializedContent) + throws SL20Exception { + try { + final AlgorithmConstraints algConstraints = new AlgorithmConstraints(ConstraintType.WHITELIST, + SL20Constants.SL20_ALGORITHM_WHITELIST_SIGNING + .toArray(new String[SL20Constants.SL20_ALGORITHM_WHITELIST_SIGNING.size()])); + + final VerificationResult result = + validateSignature(serializedContent, trustedCerts, algConstraints); + + if (!result.isValidSigned()) { + log.info("JWS signature invalide. Stopping authentication process ..."); + log.debug("Received JWS msg: " + serializedContent); + throw new SL20SecurityException("JWS signature invalide."); + + } + + log.debug("SL2.0 commando signature validation sucessfull"); + return result; + + } catch (JoseException | JsonParseException e) { + log.warn("SL2.0 commando signature validation FAILED", e); + throw new SL20SecurityException(new Object[] {e.getMessage()}, e); + + } catch (final IOException e) { + log.warn("Decrypted SL2.0 result can not be parsed.", e); + throw new SlCommandoParserException("Decrypted SL2.0 result can not be parsed", e); + + } + + } + + + @Override + public JsonNode decryptPayload(final String compactSerialization) throws SL20Exception { + try { + final JsonWebEncryption receiverJwe = new JsonWebEncryption(); + + // set security constrains + receiverJwe.setAlgorithmConstraints(new AlgorithmConstraints(ConstraintType.WHITELIST, + SL20Constants.SL20_ALGORITHM_WHITELIST_KEYENCRYPTION + .toArray(new String[SL20Constants.SL20_ALGORITHM_WHITELIST_KEYENCRYPTION.size()]))); + receiverJwe.setContentEncryptionAlgorithmConstraints(new AlgorithmConstraints( + ConstraintType.WHITELIST, SL20Constants.SL20_ALGORITHM_WHITELIST_ENCRYPTION + .toArray(new String[SL20Constants.SL20_ALGORITHM_WHITELIST_ENCRYPTION.size()]))); + + // set payload + receiverJwe.setCompactSerialization(compactSerialization); + + + // validate key from header against key from config + final List x5cCerts = receiverJwe.getCertificateChainHeaderValue(); + final String x5t256 = receiverJwe.getX509CertSha256ThumbprintHeaderValue(); + if (x5cCerts != null) { + log.debug("Found x509 certificate in JOSE header ... "); + log.trace("Sorting received X509 certificates ... "); + final List sortedX5cCerts = X509Utils.sortCertificates(x5cCerts); + + if (!sortedX5cCerts.get(0).equals(encCertChain[0])) { + log.info("Certificate from JOSE header does NOT match encryption certificate"); + log.debug("JOSE certificate: " + sortedX5cCerts.get(0).toString()); + + try { + log.debug("Cert: " + Base64Utils.encode(sortedX5cCerts.get(0).getEncoded())); + } catch (final CertificateEncodingException e) { + e.printStackTrace(); + } + throw new SL20Exception("sl20.05", + new Object[] {"Certificate from JOSE header does NOT match encryption certificate"}); + } + + } else if (StringUtils.isNotEmpty(x5t256)) { + log.debug("Found x5t256 fingerprint in JOSE header .... "); + final String certFingerPrint = X509Util.x5tS256(encCertChain[0]); + if (!certFingerPrint.equals(x5t256)) { + log.info("X5t256 from JOSE header does NOT match encryption certificate"); + log.debug("X5t256 from JOSE header: " + x5t256 + " Encrytption cert: " + certFingerPrint); + throw new SL20Exception("sl20.05", + new Object[] {"X5t256 from JOSE header does NOT match encryption certificate"}); + + } + + } else { + log.info( + "Signed SL2.0 response contains NO signature certificate or NO certificate fingerprint"); + throw new SlCommandoParserException( + "Signed SL2.0 response contains NO signature certificate or NO certificate fingerprint"); + + } + + // set key + receiverJwe.setKey(encPrivKey); + + + // decrypt payload + return mapper.getMapper().readTree(receiverJwe.getPlaintextString()); + + } catch (final JoseException e) { + log.warn("SL2.0 result decryption FAILED", e); + throw new SL20SecurityException(new Object[] {e.getMessage()}, e); + + } catch (final JsonParseException e) { + log.warn("Decrypted SL2.0 result is NOT a valid JSON.", e); + throw new SlCommandoParserException("Decrypted SL2.0 result is NOT a valid JSON.", e); + + } catch (final IOException e) { + log.warn("Decrypted SL2.0 result can not be parsed.", e); + throw new SlCommandoParserException("Decrypted SL2.0 result can not be parsed", e); + } + + } + + + + @Override + public X509Certificate getEncryptionCertificate() { + // TODO: maybe update after SL2.0 update on encryption certificate parts + if (encCertChain != null && encCertChain.length > 0) { + return encCertChain[0]; + } else { + return null; + } + } + + private String getKeyStoreFilePath() throws EaafConfigurationException, MalformedURLException { + return FileUtils.makeAbsoluteUrl( + authConfig.getBasicConfiguration(Constants.CONFIG_PROP_SECURITY_KEYSTORE_PATH), + authConfig.getConfigurationRootDirectory()); + } + + private String getKeyStorePassword() { + String value = + authConfig.getBasicConfiguration(Constants.CONFIG_PROP_SECURITY_KEYSTORE_PASSWORD); + if (value != null) { + value = value.trim(); + } + + return value; + + } + + private String getSigningKeyAlias() { + String value = authConfig + .getBasicConfiguration(Constants.CONFIG_PROP_SECURITY_KEYSTORE_KEY_SIGN_ALIAS).trim(); + if (value != null) { + value = value.trim(); + } + + return value; + } + + private String getSigningKeyPassword() { + String value = authConfig + .getBasicConfiguration(Constants.CONFIG_PROP_SECURITY_KEYSTORE_KEY_SIGN_PASSWORD).trim(); + if (value != null) { + value = value.trim(); + } + + return value; + } + + private String getEncryptionKeyAlias() { + String value = authConfig + .getBasicConfiguration(Constants.CONFIG_PROP_SECURITY_KEYSTORE_KEY_ENCRYPTION_ALIAS).trim(); + if (value != null) { + value = value.trim(); + } + + return value; + } + + private String getEncryptionKeyPassword() { + String value = authConfig + .getBasicConfiguration(Constants.CONFIG_PROP_SECURITY_KEYSTORE_KEY_ENCRYPTION_PASSWORD) + .trim(); + if (value != null) { + value = value.trim(); + } + + return value; + } + + @Nonnull + private List readCertsFromKeyStore(@Nonnull final KeyStore keyStore) + throws KeyStoreException { + final List result = new ArrayList<>(); + + final Enumeration aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + final String el = aliases.nextElement(); + log.trace("Process TrustStoreEntry: " + el); + if (keyStore.isCertificateEntry(el)) { + final Certificate cert = keyStore.getCertificate(el); + if (cert != null && cert instanceof X509Certificate) { + result.add((X509Certificate) cert); + } else { + log.info("Can not process entry: " + el + ". Reason: " + cert.toString()); + } + + } + } + + return Collections.unmodifiableList(result); + } + } diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20Constants.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20Constants.java index 06c36cff..5a8be243 100644 --- a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20Constants.java +++ b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20Constants.java @@ -8,234 +8,273 @@ import org.jose4j.jwe.KeyManagementAlgorithmIdentifiers; import org.jose4j.jws.AlgorithmIdentifiers; public class SL20Constants { - public static final int CURRENT_SL20_VERSION = 10; - - //http binding parameters - public static final String PARAM_SL20_REQ_COMMAND_PARAM = "slcommand"; - public static final String PARAM_SL20_REQ_COMMAND_PARAM_OLD = "sl2command"; - - public static final String PARAM_SL20_REQ_ICP_RETURN_URL_PARAM = "slIPCReturnUrl"; - public static final String PARAM_SL20_REQ_TRANSACTIONID = "slTransactionID"; - - public static final String HTTP_HEADER_SL20_CLIENT_TYPE = "SL2ClientType"; - public static final String HTTP_HEADER_SL20_VDA_TYPE = "X-MOA-VDA"; - public static final String HTTP_HEADER_VALUE_NATIVE = "nativeApp"; - - public static final String HTTP_HEADER_SL20_RESP = "X-SL20Operation"; - - - //******************************************************************************************* - //JSON signing and encryption headers - public static final String JSON_ALGORITHM = "alg"; - public static final String JSON_CONTENTTYPE = "cty"; - public static final String JSON_X509_CERTIFICATE = "x5c"; - public static final String JSON_X509_FINGERPRINT = "x5t#S256"; - public static final String JSON_ENCRYPTION_PAYLOAD = "enc"; - - public static final String JSON_ALGORITHM_SIGNING_RS256 = AlgorithmIdentifiers.RSA_USING_SHA256; - public static final String JSON_ALGORITHM_SIGNING_RS512 = AlgorithmIdentifiers.RSA_USING_SHA512; - public static final String JSON_ALGORITHM_SIGNING_ES256 = AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256; - public static final String JSON_ALGORITHM_SIGNING_ES512 = AlgorithmIdentifiers.ECDSA_USING_P521_CURVE_AND_SHA512; - public static final String JSON_ALGORITHM_SIGNING_PS256 = AlgorithmIdentifiers.RSA_PSS_USING_SHA256; - public static final String JSON_ALGORITHM_SIGNING_PS512 = AlgorithmIdentifiers.RSA_PSS_USING_SHA512; - - public static final List SL20_ALGORITHM_WHITELIST_SIGNING = Arrays.asList( - JSON_ALGORITHM_SIGNING_RS256, - JSON_ALGORITHM_SIGNING_RS512, - JSON_ALGORITHM_SIGNING_ES256, - JSON_ALGORITHM_SIGNING_ES512, - JSON_ALGORITHM_SIGNING_PS256, - JSON_ALGORITHM_SIGNING_PS512 - ); - - public static final String JSON_ALGORITHM_ENC_KEY_RSAOAEP = KeyManagementAlgorithmIdentifiers.RSA_OAEP; - public static final String JSON_ALGORITHM_ENC_KEY_RSAOAEP256 = KeyManagementAlgorithmIdentifiers.RSA_OAEP_256; - - public static final List SL20_ALGORITHM_WHITELIST_KEYENCRYPTION = Arrays.asList( - JSON_ALGORITHM_ENC_KEY_RSAOAEP, - JSON_ALGORITHM_ENC_KEY_RSAOAEP256 - ); - - public static final String JSON_ALGORITHM_ENC_PAYLOAD_A128CBCHS256 = ContentEncryptionAlgorithmIdentifiers.AES_128_CBC_HMAC_SHA_256; - public static final String JSON_ALGORITHM_ENC_PAYLOAD_A256CBCHS512 = ContentEncryptionAlgorithmIdentifiers.AES_256_CBC_HMAC_SHA_512; - public static final String JSON_ALGORITHM_ENC_PAYLOAD_A128GCM = ContentEncryptionAlgorithmIdentifiers.AES_128_GCM; - public static final String JSON_ALGORITHM_ENC_PAYLOAD_A256GCM = ContentEncryptionAlgorithmIdentifiers.AES_256_GCM; - - public static final List SL20_ALGORITHM_WHITELIST_ENCRYPTION = Arrays.asList( - JSON_ALGORITHM_ENC_PAYLOAD_A128CBCHS256, - JSON_ALGORITHM_ENC_PAYLOAD_A256CBCHS512, - JSON_ALGORITHM_ENC_PAYLOAD_A128GCM, - JSON_ALGORITHM_ENC_PAYLOAD_A256GCM - ); - - - //********************************************************************************************* - //Object identifier for generic transport container - public static final String SL20_CONTENTTYPE_SIGNED_COMMAND ="application/sl2.0;command"; - public static final String SL20_CONTENTTYPE_ENCRYPTED_RESULT ="application/sl2.0;result"; - - public static final String SL20_VERSION = "v"; - public static final String SL20_REQID = "reqID"; - public static final String SL20_RESPID = "respID"; - public static final String SL20_INRESPTO = "inResponseTo"; - public static final String SL20_TRANSACTIONID = "transactionID"; - public static final String SL20_PAYLOAD = "payload"; - public static final String SL20_SIGNEDPAYLOAD = "signedPayload"; - - //Generic Object identifier for commands - public static final String SL20_COMMAND_CONTAINER_NAME = "name"; - public static final String SL20_COMMAND_CONTAINER_PARAMS = "params"; - public static final String SL20_COMMAND_CONTAINER_RESULT = "result"; - public static final String SL20_COMMAND_CONTAINER_ENCRYPTEDRESULT = "encryptedResult"; - - //COMMAND Object identifier - public static final String SL20_COMMAND_IDENTIFIER_REDIRECT = "redirect"; - public static final String SL20_COMMAND_IDENTIFIER_CALL = "call"; - public static final String SL20_COMMAND_IDENTIFIER_ERROR = "error"; - @Deprecated public static final String SL20_COMMAND_IDENTIFIER_QUALIFIEDEID = "qualifiedeID"; - public static final String SL20_COMMAND_IDENTIFIER_QUALIFIEDEIDCONSENT = "qualifiedEIDConsent"; - //public static final String SL20_COMMAND_IDENTIFIER_QUALIFIEDSIG = "qualifiedSig"; - - public static final String SL20_COMMAND_IDENTIFIER_GETCERTIFICATE = "getCertificate"; - public static final String SL20_COMMAND_IDENTIFIER_CREATE_SIG_CADES = "createCAdES"; - - - public static final String SL20_COMMAND_IDENTIFIER_BINDING_CREATE_KEY = "createBindingKey"; - public static final String SL20_COMMAND_IDENTIFIER_BINDING_STORE_CERT = "storeBindingCert"; - - public static final String SL20_COMMAND_IDENTIFIER_AUTH_IDANDPASSWORD = "idAndPassword"; - public static final String SL20_COMMAND_IDENTIFIER_AUTH_JWSTOKENFACTOR = "jwsTokenAuth"; - public static final String SL20_COMMAND_IDENTIFIER_AUTH_QRCODEFACTOR = "qrCodeFactor"; - - //*****COMMAND parameter identifier****** - //general Identifier - public static final String SL20_COMMAND_PARAM_GENERAL_REQPARAMETER_VALUE = "value"; - public static final String SL20_COMMAND_PARAM_GENERAL_REQPARAMETER_KEY = "key"; - public static final String SL20_COMMAND_PARAM_GENERAL_DATAURL = "dataUrl"; - public static final String SL20_COMMAND_PARAM_GENERAL_RESPONSEENCRYPTIONCERTIFICATE = "x5cEnc"; - public static final String SL20_COMMAND_PARAM_GENERAL_RESPONSEENCRYPTIONJWK = "jwkEnc"; - - //Redirect command - public static final String SL20_COMMAND_PARAM_GENERAL_REDIRECT_URL = "url"; - public static final String SL20_COMMAND_PARAM_GENERAL_REDIRECT_COMMAND = "command"; - public static final String SL20_COMMAND_PARAM_GENERAL_REDIRECT_SIGNEDCOMMAND = "signedCommand"; - public static final String SL20_COMMAND_PARAM_GENERAL_REDIRECT_IPCREDIRECT = "IPCRedirect"; - - //Call command - public static final String SL20_COMMAND_PARAM_GENERAL_CALL_URL = SL20_COMMAND_PARAM_GENERAL_REDIRECT_URL; - public static final String SL20_COMMAND_PARAM_GENERAL_CALL_METHOD = "method"; - public static final String SL20_COMMAND_PARAM_GENERAL_CALL_METHOD_GET = "get"; - public static final String SL20_COMMAND_PARAM_GENERAL_CALL_METHOD_POST = "post"; - public static final String SL20_COMMAND_PARAM_GENERAL_CALL_INCLUDETRANSACTIONID = "includeTransactionID"; - public static final String SL20_COMMAND_PARAM_GENERAL_CALL_REQPARAMETER = "reqParams"; - - //error command - public static final String SL20_COMMAND_PARAM_GENERAL_RESPONSE_ERRORCODE = "errorCode"; - public static final String SL20_COMMAND_PARAM_GENERAL_RESPONSE_ERRORMESSAGE = "errorMessage"; - - //qualified eID command - @Deprecated public static final String SL20_COMMAND_PARAM_EID_AUTHBLOCKID = "authBlockTemplateID"; - public static final String SL20_COMMAND_PARAM_EID_DATAURL = SL20_COMMAND_PARAM_GENERAL_DATAURL; - @Deprecated public static final String SL20_COMMAND_PARAM_EID_ATTRIBUTES = "attributes"; - @Deprecated public static final String SL20_COMMAND_PARAM_EID_ATTRIBUTES_MANDATEREFVALUE = "MANDATE-REFERENCE-VALUE"; - @Deprecated public static final String SL20_COMMAND_PARAM_EID_ATTRIBUTES_SPUNIQUEID = "SP-UNIQUEID"; - @Deprecated public static final String SL20_COMMAND_PARAM_EID_ATTRIBUTES_SPFRIENDLYNAME = "SP-FRIENDLYNAME"; - @Deprecated public static final String SL20_COMMAND_PARAM_EID_ATTRIBUTES_SPCOUNTRYCODE = "SP-COUNTRYCODE"; - public static final String SL20_COMMAND_PARAM_EID_X5CENC = SL20_COMMAND_PARAM_GENERAL_RESPONSEENCRYPTIONCERTIFICATE; - public static final String SL20_COMMAND_PARAM_EID_JWKCENC = SL20_COMMAND_PARAM_GENERAL_RESPONSEENCRYPTIONJWK; - @Deprecated public static final String SL20_COMMAND_PARAM_EID_RESULT_IDL = "EID-IDENTITY-LINK"; - @Deprecated public static final String SL20_COMMAND_PARAM_EID_RESULT_AUTHBLOCK = "EID-AUTH-BLOCK"; - public static final String SL20_COMMAND_PARAM_EID_RESULT_CCSURL = "EID-CCS-URL"; - @Deprecated public static final String SL20_COMMAND_PARAM_EID_RESULT_LOA = "EID-CITIZEN-QAA-LEVEL"; - - public static final String SL20_COMMAND_PARAM_EID_CONSENTTEMPLATEID = "consentTemplateID"; - public static final String SL20_COMMAND_PARAM_EID_CONSENT = "consent"; - public static final String SL20_COMMAND_PARAM_EID_CONSENT_RESULT_MDS = "MDS"; - public static final String SL20_COMMAND_PARAM_EID_CONSENT_RESULT_VSZ = "vSZ"; - public static final String SL20_COMMAND_PARAM_EID_CONSENT_RESULT_SIGNEDCONSENT = "signedConsent"; - - //qualified Signature comamnd -// public static final String SL20_COMMAND_PARAM_QUALSIG_DATAURL = SL20_COMMAND_PARAM_GENERAL_DATAURL; -// public static final String SL20_COMMAND_PARAM_QUALSIG_X5CENC = SL20_COMMAND_PARAM_GENERAL_RESPONSEENCRYPTIONCERTIFICATE; - - - //getCertificate - public static final String SL20_COMMAND_PARAM_GETCERTIFICATE_KEYID = "keyId"; - public static final String SL20_COMMAND_PARAM_GETCERTIFICATE_DATAURL = SL20_COMMAND_PARAM_GENERAL_DATAURL; - public static final String SL20_COMMAND_PARAM_GETCERTIFICATE_X5CENC = SL20_COMMAND_PARAM_GENERAL_RESPONSEENCRYPTIONCERTIFICATE; - public static final String SL20_COMMAND_PARAM_GETCERTIFICATE_JWKCENC = SL20_COMMAND_PARAM_GENERAL_RESPONSEENCRYPTIONJWK; - public static final String SL20_COMMAND_PARAM_GETCERTIFICATE_RESULT_CERTIFICATE = "x5c"; - - //createCAdES Signture - public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_KEYID = "keyId"; - public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_CONTENT = "content"; - public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_MIMETYPE = "mimeType"; - public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_PADES_COMBATIBILTY = "padesComatibility"; - public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_EXCLUDEBYTERANGE = "excludedByteRange"; - public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_CADESLEVEL = "cadesLevel"; - public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_DATAURL = SL20_COMMAND_PARAM_GENERAL_DATAURL; - public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_X5CENC = SL20_COMMAND_PARAM_GENERAL_RESPONSEENCRYPTIONCERTIFICATE; - public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_JWKCENC = SL20_COMMAND_PARAM_GENERAL_RESPONSEENCRYPTIONJWK; - public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_RESULT_SIGNATURE = "signature"; - - public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_CADESLEVEL_BASIC = "cAdES"; - public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_CADESLEVEL_T = "cAdES-T"; - public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_CADESLEVEL_C = "cAdES-C"; - public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_CADESLEVEL_X = "cAdES-X"; - public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_CADESLEVEL_XL = "cAdES-X-L"; - public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_CADESLEVEL_A = "cAdES-A"; - - - - //create binding key command - public static final String SL20_COMMAND_PARAM_BINDING_CREATE_KONTOID = "kontoID"; - public static final String SL20_COMMAND_PARAM_BINDING_CREATE_SN = "SN"; - public static final String SL20_COMMAND_PARAM_BINDING_CREATE_KEYLENGTH = "keyLength"; - public static final String SL20_COMMAND_PARAM_BINDING_CREATE_KEYALG = "keyAlg"; - public static final String SL20_COMMAND_PARAM_BINDING_CREATE_POLICIES = "policies"; - public static final String SL20_COMMAND_PARAM_BINDING_CREATE_DATAURL = SL20_COMMAND_PARAM_GENERAL_DATAURL; - public static final String SL20_COMMAND_PARAM_BINDING_CREATE_X5CVDATRUST = "x5cVdaTrust"; - public static final String SL20_COMMAND_PARAM_BINDING_CREATE_REQUESTUSERPASSWORD = "reqUserPassword"; - public static final String SL20_COMMAND_PARAM_BINDING_CREATE_X5CENC = SL20_COMMAND_PARAM_GENERAL_RESPONSEENCRYPTIONCERTIFICATE; - - public static final String SL20_COMMAND_PARAM_BINDING_CREATE_KEYALG_RSA = "RSA"; - public static final String SL20_COMMAND_PARAM_BINDING_CREATE_KEYALG_SECPR256R1 = "secp256r1"; - - public static final String SL20_COMMAND_PARAM_BINDING_CREATE_POLICIES_LIFETIME = "lifeTime"; - public static final String SL20_COMMAND_PARAM_BINDING_CREATE_POLICIES_USESECUREELEMENT = "useSecureElement"; - public static final String SL20_COMMAND_PARAM_BINDING_CREATE_POLICIES_KEYTIMEOUT = "keyTimeout"; - public static final String SL20_COMMAND_PARAM_BINDING_CREATE_POLICIES_NEEDUSERAUTH = "needUserAuth"; - - public static final String SL20_COMMAND_PARAM_BINDING_CREATE_RESULT_APPID = "appID"; - public static final String SL20_COMMAND_PARAM_BINDING_CREATE_RESULT_CSR = "csr"; - public static final String SL20_COMMAND_PARAM_BINDING_CREATE_RESULT_KEYATTESTATIONZERTIFICATE = "attCert"; - public static final String SL20_COMMAND_PARAM_BINDING_CREATE_RESULT_USERPASSWORD = "encodedPass"; - - - //store binding certificate command - public static final String SL20_COMMAND_PARAM_BINDING_STORE_CERTIFICATE = "x5c"; - public static final String SL20_COMMAND_PARAM_BINDING_STORE_DATAURL = SL20_COMMAND_PARAM_GENERAL_DATAURL; - public static final String SL20_COMMAND_PARAM_BINDING_STORE_RESULT_SUCESS = "success"; - public static final String SL20_COMMAND_PARAM_BINDING_STORE_RESULT_SUCESS_VALUE = "OK"; - - // Username and password authentication - public static final String SL20_COMMAND_PARAM_AUTH_IDANDPASSWORD_KEYALG = "keyAlg"; - public static final String SL20_COMMAND_PARAM_AUTH_IDANDPASSWORD_KEYALG_VALUE_PLAIN = "plain"; - public static final String SL20_COMMAND_PARAM_AUTH_IDANDPASSWORD_KEYALG_VALUE_PBKDF2 = "PBKDF2"; - public static final String SL20_COMMAND_PARAM_AUTH_IDANDPASSWORD_DATAURL = SL20_COMMAND_PARAM_GENERAL_DATAURL; - public static final String SL20_COMMAND_PARAM_AUTH_IDANDPASSWORD_X5CENC = SL20_COMMAND_PARAM_GENERAL_RESPONSEENCRYPTIONCERTIFICATE; - public static final String SL20_COMMAND_PARAM_AUTH_IDANDPASSWORD_RESULT_KONTOID = SL20_COMMAND_PARAM_BINDING_CREATE_KONTOID; - public static final String SL20_COMMAND_PARAM_AUTH_IDANDPASSWORD_RESULT_USERPASSWORD = SL20_COMMAND_PARAM_BINDING_CREATE_RESULT_USERPASSWORD; - - //JWS Token authentication - public static final String SL20_COMMAND_PARAM_AUTH_JWSTOKEN_NONCE = "nonce"; - public static final String SL20_COMMAND_PARAM_AUTH_JWSTOKEN_DISPLAYDATA = "displayData"; - public static final String SL20_COMMAND_PARAM_AUTH_JWSTOKEN_DISPLAYURL = "displayUrl"; - public static final String SL20_COMMAND_PARAM_AUTH_JWSTOKEN_DATAURL = SL20_COMMAND_PARAM_GENERAL_DATAURL; - public static final String SL20_COMMAND_PARAM_AUTH_JWSTOKEN_RESULT_NONCE = SL20_COMMAND_PARAM_AUTH_JWSTOKEN_NONCE; - - //QR-Code authentication - public static final String SL20_COMMAND_PARAM_AUTH_QRCODE_QRCODE = "qrCode"; - public static final String SL20_COMMAND_PARAM_AUTH_QRCODE_DATAURL = SL20_COMMAND_PARAM_GENERAL_DATAURL; - + public static final int CURRENT_SL20_VERSION = 10; + + // http binding parameters + public static final String PARAM_SL20_REQ_COMMAND_PARAM = "slcommand"; + public static final String PARAM_SL20_REQ_COMMAND_PARAM_OLD = "sl2command"; + + public static final String PARAM_SL20_REQ_ICP_RETURN_URL_PARAM = "slIPCReturnUrl"; + public static final String PARAM_SL20_REQ_TRANSACTIONID = "slTransactionID"; + + public static final String HTTP_HEADER_SL20_CLIENT_TYPE = "SL2ClientType"; + public static final String HTTP_HEADER_SL20_VDA_TYPE = "X-MOA-VDA"; + public static final String HTTP_HEADER_VALUE_NATIVE = "nativeApp"; + + public static final String HTTP_HEADER_SL20_RESP = "X-SL20Operation"; + + + // ******************************************************************************************* + // JSON signing and encryption headers + public static final String JSON_ALGORITHM = "alg"; + public static final String JSON_CONTENTTYPE = "cty"; + public static final String JSON_X509_CERTIFICATE = "x5c"; + public static final String JSON_X509_FINGERPRINT = "x5t#S256"; + public static final String JSON_ENCRYPTION_PAYLOAD = "enc"; + + public static final String JSON_ALGORITHM_SIGNING_RS256 = AlgorithmIdentifiers.RSA_USING_SHA256; + public static final String JSON_ALGORITHM_SIGNING_RS512 = AlgorithmIdentifiers.RSA_USING_SHA512; + public static final String JSON_ALGORITHM_SIGNING_ES256 = + AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256; + public static final String JSON_ALGORITHM_SIGNING_ES512 = + AlgorithmIdentifiers.ECDSA_USING_P521_CURVE_AND_SHA512; + public static final String JSON_ALGORITHM_SIGNING_PS256 = + AlgorithmIdentifiers.RSA_PSS_USING_SHA256; + public static final String JSON_ALGORITHM_SIGNING_PS512 = + AlgorithmIdentifiers.RSA_PSS_USING_SHA512; + + public static final List SL20_ALGORITHM_WHITELIST_SIGNING = Arrays.asList( + JSON_ALGORITHM_SIGNING_RS256, JSON_ALGORITHM_SIGNING_RS512, JSON_ALGORITHM_SIGNING_ES256, + JSON_ALGORITHM_SIGNING_ES512, JSON_ALGORITHM_SIGNING_PS256, JSON_ALGORITHM_SIGNING_PS512); + + public static final String JSON_ALGORITHM_ENC_KEY_RSAOAEP = + KeyManagementAlgorithmIdentifiers.RSA_OAEP; + public static final String JSON_ALGORITHM_ENC_KEY_RSAOAEP256 = + KeyManagementAlgorithmIdentifiers.RSA_OAEP_256; + + public static final List SL20_ALGORITHM_WHITELIST_KEYENCRYPTION = + Arrays.asList(JSON_ALGORITHM_ENC_KEY_RSAOAEP, JSON_ALGORITHM_ENC_KEY_RSAOAEP256); + + public static final String JSON_ALGORITHM_ENC_PAYLOAD_A128CBCHS256 = + ContentEncryptionAlgorithmIdentifiers.AES_128_CBC_HMAC_SHA_256; + public static final String JSON_ALGORITHM_ENC_PAYLOAD_A256CBCHS512 = + ContentEncryptionAlgorithmIdentifiers.AES_256_CBC_HMAC_SHA_512; + public static final String JSON_ALGORITHM_ENC_PAYLOAD_A128GCM = + ContentEncryptionAlgorithmIdentifiers.AES_128_GCM; + public static final String JSON_ALGORITHM_ENC_PAYLOAD_A256GCM = + ContentEncryptionAlgorithmIdentifiers.AES_256_GCM; + + public static final List SL20_ALGORITHM_WHITELIST_ENCRYPTION = Arrays.asList( + JSON_ALGORITHM_ENC_PAYLOAD_A128CBCHS256, JSON_ALGORITHM_ENC_PAYLOAD_A256CBCHS512, + JSON_ALGORITHM_ENC_PAYLOAD_A128GCM, JSON_ALGORITHM_ENC_PAYLOAD_A256GCM); + + + // ********************************************************************************************* + // Object identifier for generic transport container + public static final String SL20_CONTENTTYPE_SIGNED_COMMAND = "application/sl2.0;command"; + public static final String SL20_CONTENTTYPE_ENCRYPTED_RESULT = "application/sl2.0;result"; + + public static final String SL20_VERSION = "v"; + public static final String SL20_REQID = "reqID"; + public static final String SL20_RESPID = "respID"; + public static final String SL20_INRESPTO = "inResponseTo"; + public static final String SL20_TRANSACTIONID = "transactionID"; + public static final String SL20_PAYLOAD = "payload"; + public static final String SL20_SIGNEDPAYLOAD = "signedPayload"; + + // Generic Object identifier for commands + public static final String SL20_COMMAND_CONTAINER_NAME = "name"; + public static final String SL20_COMMAND_CONTAINER_PARAMS = "params"; + public static final String SL20_COMMAND_CONTAINER_RESULT = "result"; + public static final String SL20_COMMAND_CONTAINER_ENCRYPTEDRESULT = "encryptedResult"; + + // COMMAND Object identifier + public static final String SL20_COMMAND_IDENTIFIER_REDIRECT = "redirect"; + public static final String SL20_COMMAND_IDENTIFIER_CALL = "call"; + public static final String SL20_COMMAND_IDENTIFIER_ERROR = "error"; + @Deprecated + public static final String SL20_COMMAND_IDENTIFIER_QUALIFIEDEID = "qualifiedeID"; + public static final String SL20_COMMAND_IDENTIFIER_QUALIFIEDEIDCONSENT = "qualifiedEIDConsent"; + // public static final String SL20_COMMAND_IDENTIFIER_QUALIFIEDSIG = "qualifiedSig"; + + public static final String SL20_COMMAND_IDENTIFIER_GETCERTIFICATE = "getCertificate"; + public static final String SL20_COMMAND_IDENTIFIER_CREATE_SIG_CADES = "createCAdES"; + + + public static final String SL20_COMMAND_IDENTIFIER_BINDING_CREATE_KEY = "createBindingKey"; + public static final String SL20_COMMAND_IDENTIFIER_BINDING_STORE_CERT = "storeBindingCert"; + + public static final String SL20_COMMAND_IDENTIFIER_AUTH_IDANDPASSWORD = "idAndPassword"; + public static final String SL20_COMMAND_IDENTIFIER_AUTH_JWSTOKENFACTOR = "jwsTokenAuth"; + public static final String SL20_COMMAND_IDENTIFIER_AUTH_QRCODEFACTOR = "qrCodeFactor"; + + // *****COMMAND parameter identifier****** + // general Identifier + public static final String SL20_COMMAND_PARAM_GENERAL_REQPARAMETER_VALUE = "value"; + public static final String SL20_COMMAND_PARAM_GENERAL_REQPARAMETER_KEY = "key"; + public static final String SL20_COMMAND_PARAM_GENERAL_DATAURL = "dataUrl"; + public static final String SL20_COMMAND_PARAM_GENERAL_RESPONSEENCRYPTIONCERTIFICATE = "x5cEnc"; + public static final String SL20_COMMAND_PARAM_GENERAL_RESPONSEENCRYPTIONJWK = "jwkEnc"; + + // Redirect command + public static final String SL20_COMMAND_PARAM_GENERAL_REDIRECT_URL = "url"; + public static final String SL20_COMMAND_PARAM_GENERAL_REDIRECT_COMMAND = "command"; + public static final String SL20_COMMAND_PARAM_GENERAL_REDIRECT_SIGNEDCOMMAND = "signedCommand"; + public static final String SL20_COMMAND_PARAM_GENERAL_REDIRECT_IPCREDIRECT = "IPCRedirect"; + + // Call command + public static final String SL20_COMMAND_PARAM_GENERAL_CALL_URL = + SL20_COMMAND_PARAM_GENERAL_REDIRECT_URL; + public static final String SL20_COMMAND_PARAM_GENERAL_CALL_METHOD = "method"; + public static final String SL20_COMMAND_PARAM_GENERAL_CALL_METHOD_GET = "get"; + public static final String SL20_COMMAND_PARAM_GENERAL_CALL_METHOD_POST = "post"; + public static final String SL20_COMMAND_PARAM_GENERAL_CALL_INCLUDETRANSACTIONID = + "includeTransactionID"; + public static final String SL20_COMMAND_PARAM_GENERAL_CALL_REQPARAMETER = "reqParams"; + + // error command + public static final String SL20_COMMAND_PARAM_GENERAL_RESPONSE_ERRORCODE = "errorCode"; + public static final String SL20_COMMAND_PARAM_GENERAL_RESPONSE_ERRORMESSAGE = "errorMessage"; + + // qualified eID command + @Deprecated + public static final String SL20_COMMAND_PARAM_EID_AUTHBLOCKID = "authBlockTemplateID"; + public static final String SL20_COMMAND_PARAM_EID_DATAURL = SL20_COMMAND_PARAM_GENERAL_DATAURL; + @Deprecated + public static final String SL20_COMMAND_PARAM_EID_ATTRIBUTES = "attributes"; + @Deprecated + public static final String SL20_COMMAND_PARAM_EID_ATTRIBUTES_MANDATEREFVALUE = + "MANDATE-REFERENCE-VALUE"; + @Deprecated + public static final String SL20_COMMAND_PARAM_EID_ATTRIBUTES_SPUNIQUEID = "SP-UNIQUEID"; + @Deprecated + public static final String SL20_COMMAND_PARAM_EID_ATTRIBUTES_SPFRIENDLYNAME = "SP-FRIENDLYNAME"; + @Deprecated + public static final String SL20_COMMAND_PARAM_EID_ATTRIBUTES_SPCOUNTRYCODE = "SP-COUNTRYCODE"; + public static final String SL20_COMMAND_PARAM_EID_X5CENC = + SL20_COMMAND_PARAM_GENERAL_RESPONSEENCRYPTIONCERTIFICATE; + public static final String SL20_COMMAND_PARAM_EID_JWKCENC = + SL20_COMMAND_PARAM_GENERAL_RESPONSEENCRYPTIONJWK; + @Deprecated + public static final String SL20_COMMAND_PARAM_EID_RESULT_IDL = "EID-IDENTITY-LINK"; + @Deprecated + public static final String SL20_COMMAND_PARAM_EID_RESULT_AUTHBLOCK = "EID-AUTH-BLOCK"; + public static final String SL20_COMMAND_PARAM_EID_RESULT_CCSURL = "EID-CCS-URL"; + @Deprecated + public static final String SL20_COMMAND_PARAM_EID_RESULT_LOA = "EID-CITIZEN-QAA-LEVEL"; + + public static final String SL20_COMMAND_PARAM_EID_CONSENTTEMPLATEID = "consentTemplateID"; + public static final String SL20_COMMAND_PARAM_EID_CONSENT = "consent"; + public static final String SL20_COMMAND_PARAM_EID_CONSENT_RESULT_MDS = "MDS"; + public static final String SL20_COMMAND_PARAM_EID_CONSENT_RESULT_VSZ = "vSZ"; + public static final String SL20_COMMAND_PARAM_EID_CONSENT_RESULT_SIGNEDCONSENT = "signedConsent"; + + // qualified Signature comamnd + // public static final String SL20_COMMAND_PARAM_QUALSIG_DATAURL = + // SL20_COMMAND_PARAM_GENERAL_DATAURL; + // public static final String SL20_COMMAND_PARAM_QUALSIG_X5CENC = + // SL20_COMMAND_PARAM_GENERAL_RESPONSEENCRYPTIONCERTIFICATE; + + + // getCertificate + public static final String SL20_COMMAND_PARAM_GETCERTIFICATE_KEYID = "keyId"; + public static final String SL20_COMMAND_PARAM_GETCERTIFICATE_DATAURL = + SL20_COMMAND_PARAM_GENERAL_DATAURL; + public static final String SL20_COMMAND_PARAM_GETCERTIFICATE_X5CENC = + SL20_COMMAND_PARAM_GENERAL_RESPONSEENCRYPTIONCERTIFICATE; + public static final String SL20_COMMAND_PARAM_GETCERTIFICATE_JWKCENC = + SL20_COMMAND_PARAM_GENERAL_RESPONSEENCRYPTIONJWK; + public static final String SL20_COMMAND_PARAM_GETCERTIFICATE_RESULT_CERTIFICATE = "x5c"; + + // createCAdES Signture + public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_KEYID = "keyId"; + public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_CONTENT = "content"; + public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_MIMETYPE = "mimeType"; + public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_PADES_COMBATIBILTY = + "padesComatibility"; + public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_EXCLUDEBYTERANGE = + "excludedByteRange"; + public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_CADESLEVEL = "cadesLevel"; + public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_DATAURL = + SL20_COMMAND_PARAM_GENERAL_DATAURL; + public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_X5CENC = + SL20_COMMAND_PARAM_GENERAL_RESPONSEENCRYPTIONCERTIFICATE; + public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_JWKCENC = + SL20_COMMAND_PARAM_GENERAL_RESPONSEENCRYPTIONJWK; + public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_RESULT_SIGNATURE = "signature"; + + public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_CADESLEVEL_BASIC = "cAdES"; + public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_CADESLEVEL_T = "cAdES-T"; + public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_CADESLEVEL_C = "cAdES-C"; + public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_CADESLEVEL_X = "cAdES-X"; + public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_CADESLEVEL_XL = "cAdES-X-L"; + public static final String SL20_COMMAND_PARAM_CREATE_SIG_CADES_CADESLEVEL_A = "cAdES-A"; + + + + // create binding key command + public static final String SL20_COMMAND_PARAM_BINDING_CREATE_KONTOID = "kontoID"; + public static final String SL20_COMMAND_PARAM_BINDING_CREATE_SN = "SN"; + public static final String SL20_COMMAND_PARAM_BINDING_CREATE_KEYLENGTH = "keyLength"; + public static final String SL20_COMMAND_PARAM_BINDING_CREATE_KEYALG = "keyAlg"; + public static final String SL20_COMMAND_PARAM_BINDING_CREATE_POLICIES = "policies"; + public static final String SL20_COMMAND_PARAM_BINDING_CREATE_DATAURL = + SL20_COMMAND_PARAM_GENERAL_DATAURL; + public static final String SL20_COMMAND_PARAM_BINDING_CREATE_X5CVDATRUST = "x5cVdaTrust"; + public static final String SL20_COMMAND_PARAM_BINDING_CREATE_REQUESTUSERPASSWORD = + "reqUserPassword"; + public static final String SL20_COMMAND_PARAM_BINDING_CREATE_X5CENC = + SL20_COMMAND_PARAM_GENERAL_RESPONSEENCRYPTIONCERTIFICATE; + + public static final String SL20_COMMAND_PARAM_BINDING_CREATE_KEYALG_RSA = "RSA"; + public static final String SL20_COMMAND_PARAM_BINDING_CREATE_KEYALG_SECPR256R1 = "secp256r1"; + + public static final String SL20_COMMAND_PARAM_BINDING_CREATE_POLICIES_LIFETIME = "lifeTime"; + public static final String SL20_COMMAND_PARAM_BINDING_CREATE_POLICIES_USESECUREELEMENT = + "useSecureElement"; + public static final String SL20_COMMAND_PARAM_BINDING_CREATE_POLICIES_KEYTIMEOUT = "keyTimeout"; + public static final String SL20_COMMAND_PARAM_BINDING_CREATE_POLICIES_NEEDUSERAUTH = + "needUserAuth"; + + public static final String SL20_COMMAND_PARAM_BINDING_CREATE_RESULT_APPID = "appID"; + public static final String SL20_COMMAND_PARAM_BINDING_CREATE_RESULT_CSR = "csr"; + public static final String SL20_COMMAND_PARAM_BINDING_CREATE_RESULT_KEYATTESTATIONZERTIFICATE = + "attCert"; + public static final String SL20_COMMAND_PARAM_BINDING_CREATE_RESULT_USERPASSWORD = "encodedPass"; + + + // store binding certificate command + public static final String SL20_COMMAND_PARAM_BINDING_STORE_CERTIFICATE = "x5c"; + public static final String SL20_COMMAND_PARAM_BINDING_STORE_DATAURL = + SL20_COMMAND_PARAM_GENERAL_DATAURL; + public static final String SL20_COMMAND_PARAM_BINDING_STORE_RESULT_SUCESS = "success"; + public static final String SL20_COMMAND_PARAM_BINDING_STORE_RESULT_SUCESS_VALUE = "OK"; + + // Username and password authentication + public static final String SL20_COMMAND_PARAM_AUTH_IDANDPASSWORD_KEYALG = "keyAlg"; + public static final String SL20_COMMAND_PARAM_AUTH_IDANDPASSWORD_KEYALG_VALUE_PLAIN = "plain"; + public static final String SL20_COMMAND_PARAM_AUTH_IDANDPASSWORD_KEYALG_VALUE_PBKDF2 = "PBKDF2"; + public static final String SL20_COMMAND_PARAM_AUTH_IDANDPASSWORD_DATAURL = + SL20_COMMAND_PARAM_GENERAL_DATAURL; + public static final String SL20_COMMAND_PARAM_AUTH_IDANDPASSWORD_X5CENC = + SL20_COMMAND_PARAM_GENERAL_RESPONSEENCRYPTIONCERTIFICATE; + public static final String SL20_COMMAND_PARAM_AUTH_IDANDPASSWORD_RESULT_KONTOID = + SL20_COMMAND_PARAM_BINDING_CREATE_KONTOID; + public static final String SL20_COMMAND_PARAM_AUTH_IDANDPASSWORD_RESULT_USERPASSWORD = + SL20_COMMAND_PARAM_BINDING_CREATE_RESULT_USERPASSWORD; + + // JWS Token authentication + public static final String SL20_COMMAND_PARAM_AUTH_JWSTOKEN_NONCE = "nonce"; + public static final String SL20_COMMAND_PARAM_AUTH_JWSTOKEN_DISPLAYDATA = "displayData"; + public static final String SL20_COMMAND_PARAM_AUTH_JWSTOKEN_DISPLAYURL = "displayUrl"; + public static final String SL20_COMMAND_PARAM_AUTH_JWSTOKEN_DATAURL = + SL20_COMMAND_PARAM_GENERAL_DATAURL; + public static final String SL20_COMMAND_PARAM_AUTH_JWSTOKEN_RESULT_NONCE = + SL20_COMMAND_PARAM_AUTH_JWSTOKEN_NONCE; + + // QR-Code authentication + public static final String SL20_COMMAND_PARAM_AUTH_QRCODE_QRCODE = "qrCode"; + public static final String SL20_COMMAND_PARAM_AUTH_QRCODE_DATAURL = + SL20_COMMAND_PARAM_GENERAL_DATAURL; + } diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20HttpBindingUtils.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20HttpBindingUtils.java index 4d8cabb7..be306b69 100644 --- a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20HttpBindingUtils.java +++ b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20HttpBindingUtils.java @@ -3,61 +3,61 @@ package at.gv.egiz.eaaf.modules.auth.sl20.utils; import java.io.IOException; import java.io.StringWriter; import java.net.URISyntaxException; - import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.apache.http.client.utils.URIBuilder; import org.jose4j.base64url.Base64Url; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; - import com.fasterxml.jackson.databind.JsonNode; public class SL20HttpBindingUtils { - private static final Logger log = LoggerFactory.getLogger(SL20HttpBindingUtils.class); - - /** - * Write SL2.0 response into http-response object - * - * @param httpReq Current http request - * @param httpResp Current http response - * @param sl20Forward SL2.0 command that should be written to response - * @param redirectURL SL2.0 redirect URL in case of SL2.0 redirect command and no native client (see SL2.0 specification) - * @param httpCodeRedirect http redirect-code in case of SL2.0 redirect command and no native client (see SL2.0 specification) - * @throws IOException - * @throws URISyntaxException - */ - public static void writeIntoResponse(@Nonnull HttpServletRequest httpReq, @Nonnull HttpServletResponse httpResp, - @Nonnull JsonNode sl20Forward, @Nullable String redirectURL, - @Nonnull int httpCodeRedirect) throws IOException, URISyntaxException { - //forward SL2.0 command - httpResp.addIntHeader(SL20Constants.HTTP_HEADER_SL20_RESP, SL20Constants.CURRENT_SL20_VERSION); - - if (httpReq.getHeader(SL20Constants.HTTP_HEADER_SL20_CLIENT_TYPE) != null && - httpReq.getHeader(SL20Constants.HTTP_HEADER_SL20_CLIENT_TYPE).equals(SL20Constants.HTTP_HEADER_VALUE_NATIVE)) { - log.debug("Client request containts 'native client' header ... "); - final StringWriter writer = new StringWriter(); - writer.write(sl20Forward.toString()); - final byte[] content = writer.toString().getBytes("UTF-8"); - httpResp.setStatus(HttpServletResponse.SC_OK); - httpResp.setContentLength(content.length); - httpResp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); - httpResp.getOutputStream().write(content); - - } else { - log.debug("Client request containts is no native client ... "); - final URIBuilder clientRedirectURI = new URIBuilder(redirectURL); - clientRedirectURI.addParameter( - SL20Constants.PARAM_SL20_REQ_COMMAND_PARAM, - Base64Url.encode(sl20Forward.toString().getBytes())); - httpResp.setStatus(httpCodeRedirect); - httpResp.setHeader("Location", clientRedirectURI.build().toString()); - - } - - } + private static final Logger log = LoggerFactory.getLogger(SL20HttpBindingUtils.class); + + /** + * Write SL2.0 response into http-response object + * + * @param httpReq Current http request + * @param httpResp Current http response + * @param sl20Forward SL2.0 command that should be written to response + * @param redirectUrl SL2.0 redirect URL in case of SL2.0 redirect command and no native client + * (see SL2.0 specification) + * @param httpCodeRedirect http redirect-code in case of SL2.0 redirect command and no native + * client (see SL2.0 specification) + * @throws IOException In case of an IO error + * @throws URISyntaxException In case of a wrong URL + */ + public static void writeIntoResponse(@Nonnull final HttpServletRequest httpReq, + @Nonnull final HttpServletResponse httpResp, @Nonnull final JsonNode sl20Forward, + @Nullable final String redirectUrl, @Nonnull final int httpCodeRedirect) + throws IOException, URISyntaxException { + // forward SL2.0 command + httpResp.addIntHeader(SL20Constants.HTTP_HEADER_SL20_RESP, SL20Constants.CURRENT_SL20_VERSION); + + if (httpReq.getHeader(SL20Constants.HTTP_HEADER_SL20_CLIENT_TYPE) != null + && httpReq.getHeader(SL20Constants.HTTP_HEADER_SL20_CLIENT_TYPE) + .equals(SL20Constants.HTTP_HEADER_VALUE_NATIVE)) { + log.debug("Client request containts 'native client' header ... "); + final StringWriter writer = new StringWriter(); + writer.write(sl20Forward.toString()); + final byte[] content = writer.toString().getBytes("UTF-8"); + httpResp.setStatus(HttpServletResponse.SC_OK); + httpResp.setContentLength(content.length); + httpResp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); + httpResp.getOutputStream().write(content); + + } else { + log.debug("Client request containts is no native client ... "); + final URIBuilder clientRedirectUri = new URIBuilder(redirectUrl); + clientRedirectUri.addParameter(SL20Constants.PARAM_SL20_REQ_COMMAND_PARAM, + Base64Url.encode(sl20Forward.toString().getBytes())); + httpResp.setStatus(httpCodeRedirect); + httpResp.setHeader("Location", clientRedirectUri.build().toString()); + + } + + } } diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20JSONBuilderUtils.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20JSONBuilderUtils.java deleted file mode 100644 index ba069ac7..00000000 --- a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20JSONBuilderUtils.java +++ /dev/null @@ -1,640 +0,0 @@ -package at.gv.egiz.eaaf.modules.auth.sl20.utils; - -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; -import java.util.Arrays; -import java.util.Base64; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.ObjectNode; - -import at.gv.egiz.eaaf.modules.auth.sl20.Constants; -import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SLCommandoBuildException; - -public class SL20JSONBuilderUtils { - - private static JsonMapper mapper = new JsonMapper(); - - /** - * Create command request - * @param name - * @param params - * @throws SLCommandoBuildException - * @return - */ - public static ObjectNode createCommand(String name, ObjectNode params) throws SLCommandoBuildException { - - final ObjectNode command = mapper.getMapper().createObjectNode(); - addSingleStringElement(command, SL20Constants.SL20_COMMAND_CONTAINER_NAME, name, true); - addSingleJSONElement(command, SL20Constants.SL20_COMMAND_CONTAINER_PARAMS, params, true); - return command; - - } - - /** - * Create signed command request - * - * @param name - * @param params - * @param signer - * @return - * @throws SLCommandoBuildException - */ - public static String createSignedCommand(String name, ObjectNode params, IJOSETools signer) throws SLCommandoBuildException { - final ObjectNode command = mapper.getMapper().createObjectNode(); - addSingleStringElement(command, SL20Constants.SL20_COMMAND_CONTAINER_NAME, name, true); - addSingleJSONElement(command, SL20Constants.SL20_COMMAND_CONTAINER_PARAMS, params, true); - return signer.createSignature(command.toString()); - - } - - - /** - * Create encrypted command result - * - * @param result - * @param encrypter - * @return - * @throws SLCommandoBuildException - */ - public static String createEncryptedCommandoResult(ObjectNode result, JsonSecurityUtils encrypter) throws SLCommandoBuildException { - //TODO: add real implementation - //create header and footer - final String dummyHeader = createJsonEncryptionHeader(encrypter).toString(); - final String payLoad = result.toString(); - final String dummyFooter = createJsonSignedFooter(encrypter); - - return Base64.getUrlEncoder().encodeToString(dummyHeader.getBytes()) + "." - + Base64.getUrlEncoder().encodeToString(payLoad.getBytes()) + "." - + Base64.getUrlEncoder().encodeToString(dummyFooter.getBytes()); - - } - - - /** - * Create command result - * - * @param name - * @param result - * @param encryptedResult - * @throws SLCommandoBuildException - * @return - */ - public static ObjectNode createCommandResponse(String name, ObjectNode result, String encryptedResult) throws SLCommandoBuildException { - final ObjectNode command = mapper.getMapper().createObjectNode(); - addSingleStringElement(command, SL20Constants.SL20_COMMAND_CONTAINER_NAME, name, true); - addOnlyOnceOfTwo(command, - SL20Constants.SL20_COMMAND_CONTAINER_RESULT, SL20Constants.SL20_COMMAND_CONTAINER_ENCRYPTEDRESULT, - result, encryptedResult); - return command; - - } - - /** - * Create command result - * - * @param name - * @param result - * @param encryptedResult - * @throws SLCommandoBuildException - * @return - */ - public static String createSignedCommandResponse(String name, ObjectNode result, String encryptedResult, JsonSecurityUtils signer) throws SLCommandoBuildException { - final ObjectNode command = mapper.getMapper().createObjectNode(); - addSingleStringElement(command, SL20Constants.SL20_COMMAND_CONTAINER_NAME, name, true); - addOnlyOnceOfTwo(command, - SL20Constants.SL20_COMMAND_CONTAINER_RESULT, SL20Constants.SL20_COMMAND_CONTAINER_ENCRYPTEDRESULT, - result, encryptedResult); - final String encodedCommand = command.toString(); - - //TODO: add real implementation - //create header and footer - final String dummyHeader = createJsonSignedHeader(signer).toString(); - final String dummyFooter = createJsonSignedFooter(signer); - - return Base64.getUrlEncoder().encodeToString(dummyHeader.getBytes()) + "." - + Base64.getUrlEncoder().encodeToString(encodedCommand.getBytes()) + "." - + Base64.getUrlEncoder().encodeToString(dummyFooter.getBytes()); - - } - - /** - * Create parameters for Redirect command - * - * @param url - * @param command - * @param signedCommand - * @param ipcRedirect - * @return - * @throws SLCommandoBuildException - */ - public static ObjectNode createRedirectCommandParameters(String url, ObjectNode command, ObjectNode signedCommand, Boolean ipcRedirect) throws SLCommandoBuildException{ - final ObjectNode redirectReqParams = mapper.getMapper().createObjectNode(); - addOnlyOnceOfTwo(redirectReqParams, - SL20Constants.SL20_COMMAND_PARAM_GENERAL_REDIRECT_COMMAND, SL20Constants.SL20_COMMAND_PARAM_GENERAL_REDIRECT_SIGNEDCOMMAND, - command, signedCommand); - addSingleStringElement(redirectReqParams, SL20Constants.SL20_COMMAND_PARAM_GENERAL_REDIRECT_URL, url, false); - addSingleBooleanElement(redirectReqParams, SL20Constants.SL20_COMMAND_PARAM_GENERAL_REDIRECT_IPCREDIRECT, ipcRedirect, false); - return redirectReqParams; - - } - - /** - * Create parameters for Call command - * - * @param url - * @param method - * @param includeTransactionId - * @param reqParameters - * @return - * @throws SLCommandoBuildException - */ - public static ObjectNode createCallCommandParameters(String url, String method, Boolean includeTransactionId, Map reqParameters) throws SLCommandoBuildException { - final ObjectNode callReqParams = mapper.getMapper().createObjectNode(); - addSingleStringElement(callReqParams, SL20Constants.SL20_COMMAND_PARAM_GENERAL_CALL_URL, url, true); - addSingleStringElement(callReqParams, SL20Constants.SL20_COMMAND_PARAM_GENERAL_CALL_METHOD, method, true); - addSingleBooleanElement(callReqParams, SL20Constants.SL20_COMMAND_PARAM_GENERAL_CALL_INCLUDETRANSACTIONID, includeTransactionId, false); - addArrayOfStringElements(callReqParams, SL20Constants.SL20_COMMAND_PARAM_GENERAL_CALL_REQPARAMETER, reqParameters); - return callReqParams; - - } - - /** - * Create result for Error command - * - * @param errorCode - * @param errorMsg - * @return - * @throws SLCommandoBuildException - */ - public static ObjectNode createErrorCommandResult(String errorCode, String errorMsg) throws SLCommandoBuildException { - final ObjectNode result = mapper.getMapper().createObjectNode(); - addSingleStringElement(result, SL20Constants.SL20_COMMAND_PARAM_GENERAL_RESPONSE_ERRORCODE, errorCode, true); - addSingleStringElement(result, SL20Constants.SL20_COMMAND_PARAM_GENERAL_RESPONSE_ERRORMESSAGE, errorMsg, true); - return result; - - } - - /** - * Create parameters for qualifiedeID command - * - * @param consentTemplateId Identifier of the template that is used for consent visualization - * @param consent Consent that has to be signed by user - * @param dataUrl - * @param additionalReqParameters - * @param x5cEnc - * @return - * @throws CertificateEncodingException - * @throws SLCommandoBuildException - */ - public static ObjectNode createQualifiedeEIDConsent(String consentTemplateId, byte[] consent, String dataUrl, - X509Certificate x5cEnc) throws CertificateEncodingException, SLCommandoBuildException { - final ObjectNode params = mapper.getMapper().createObjectNode(); - addSingleStringElement(params, SL20Constants.SL20_COMMAND_PARAM_EID_CONSENTTEMPLATEID, consentTemplateId, true); - addSingleByteElement(params, SL20Constants.SL20_COMMAND_PARAM_EID_CONSENT, consent, true); - addSingleStringElement(params, SL20Constants.SL20_COMMAND_PARAM_EID_DATAURL, dataUrl, true); - addSingleCertificateElement(params, SL20Constants.SL20_COMMAND_PARAM_EID_X5CENC, x5cEnc, false); - return params; - - } - - - /** - * Create parameters for qualifiedeID command - * - * @param authBlockId - * @param dataUrl - * @param additionalReqParameters - * @param x5cEnc - * @return - * @throws CertificateEncodingException - * @throws SLCommandoBuildException - */ - @Deprecated - public static ObjectNode createQualifiedeIDCommandParameters(String authBlockId, String dataUrl, - Map additionalReqParameters, X509Certificate x5cEnc) throws CertificateEncodingException, SLCommandoBuildException { - final ObjectNode params = mapper.getMapper().createObjectNode(); - addSingleStringElement(params, SL20Constants.SL20_COMMAND_PARAM_EID_AUTHBLOCKID, authBlockId, true); - addSingleStringElement(params, SL20Constants.SL20_COMMAND_PARAM_EID_DATAURL, dataUrl, true); - addArrayOfStringElements(params, SL20Constants.SL20_COMMAND_PARAM_EID_ATTRIBUTES, additionalReqParameters); - addSingleCertificateElement(params, SL20Constants.SL20_COMMAND_PARAM_EID_X5CENC, x5cEnc, false); - return params; - - } - - /** - * Create result for qualifiedeID command - * - * @param idl - * @param authBlock - * @param ccsURL - * @param LoA - * @return - * @throws SLCommandoBuildException - */ - public static ObjectNode createQualifiedeIDCommandResult(byte[] idl, byte[] authBlock, String ccsURL, String LoA) throws SLCommandoBuildException { - final ObjectNode result = mapper.getMapper().createObjectNode(); - addSingleByteElement(result, SL20Constants.SL20_COMMAND_PARAM_EID_RESULT_IDL, idl, true); - addSingleByteElement(result, SL20Constants.SL20_COMMAND_PARAM_EID_RESULT_AUTHBLOCK, authBlock, true); - addSingleStringElement(result, SL20Constants.SL20_COMMAND_PARAM_EID_RESULT_CCSURL, ccsURL, true); - addSingleStringElement(result, SL20Constants.SL20_COMMAND_PARAM_EID_RESULT_LOA, LoA, true); - return result; - - } - - - /** - * Create Binding-Key command parameters - * - * @param kontoId - * @param subjectName - * @param keySize - * @param keyAlg - * @param policies - * @param dataUrl - * @param x5cVdaTrust - * @param reqUserPassword - * @param x5cEnc - * @return - * @throws SLCommandoBuildException - * @throws CertificateEncodingException - */ - public static ObjectNode createBindingKeyCommandParams(String kontoId, String subjectName, int keySize, String keyAlg, - Map policies, String dataUrl, X509Certificate x5cVdaTrust, Boolean reqUserPassword, X509Certificate x5cEnc) throws SLCommandoBuildException, CertificateEncodingException { - final ObjectNode params = mapper.getMapper().createObjectNode(); - addSingleStringElement(params, SL20Constants.SL20_COMMAND_PARAM_BINDING_CREATE_KONTOID, kontoId, true); - addSingleStringElement(params, SL20Constants.SL20_COMMAND_PARAM_BINDING_CREATE_SN, subjectName, true); - addSingleNumberElement(params, SL20Constants.SL20_COMMAND_PARAM_BINDING_CREATE_KEYLENGTH, keySize, true); - addSingleStringElement(params, SL20Constants.SL20_COMMAND_PARAM_BINDING_CREATE_KEYALG, keyAlg, true); - addArrayOfStringElements(params, SL20Constants.SL20_COMMAND_PARAM_BINDING_CREATE_POLICIES, policies); - addSingleStringElement(params, SL20Constants.SL20_COMMAND_PARAM_BINDING_CREATE_DATAURL, dataUrl, true); - addSingleCertificateElement(params, SL20Constants.SL20_COMMAND_PARAM_BINDING_CREATE_X5CVDATRUST, x5cVdaTrust, false); - addSingleBooleanElement(params, SL20Constants.SL20_COMMAND_PARAM_BINDING_CREATE_REQUESTUSERPASSWORD, reqUserPassword, false); - addSingleCertificateElement(params, SL20Constants.SL20_COMMAND_PARAM_BINDING_CREATE_X5CENC, x5cEnc, false); - return params; - - } - - /** - * Create Binding-Key command result - * - * @param appId - * @param csr - * @param attCert - * @param password - * @return - * @throws SLCommandoBuildException - * @throws CertificateEncodingException - */ - public static ObjectNode createBindingKeyCommandResult(String appId, byte[] csr, X509Certificate attCert, byte[] password) throws SLCommandoBuildException, CertificateEncodingException { - final ObjectNode result = mapper.getMapper().createObjectNode(); - addSingleStringElement(result, SL20Constants.SL20_COMMAND_PARAM_BINDING_CREATE_RESULT_APPID, appId, true); - addSingleByteElement(result, SL20Constants.SL20_COMMAND_PARAM_BINDING_CREATE_RESULT_CSR, csr, true); - addSingleCertificateElement(result, SL20Constants.SL20_COMMAND_PARAM_BINDING_CREATE_RESULT_KEYATTESTATIONZERTIFICATE, attCert, false); - addSingleByteElement(result, SL20Constants.SL20_COMMAND_PARAM_BINDING_CREATE_RESULT_USERPASSWORD, password, false); - return result; - - } - - /** - * Create Store Binding-Certificate command parameters - * - * @param cert - * @param dataUrl - * @return - * @throws CertificateEncodingException - * @throws SLCommandoBuildException - */ - public static ObjectNode createStoreBindingCertCommandParams(X509Certificate cert, String dataUrl) throws CertificateEncodingException, SLCommandoBuildException { - final ObjectNode params = mapper.getMapper().createObjectNode(); - addSingleCertificateElement(params, SL20Constants.SL20_COMMAND_PARAM_BINDING_STORE_CERTIFICATE, cert, true); - addSingleStringElement(params, SL20Constants.SL20_COMMAND_PARAM_BINDING_STORE_DATAURL, dataUrl, true); - return params; - - } - - /** - * Create Store Binding-Certificate command result - * - * @return - * @throws SLCommandoBuildException - */ - public static ObjectNode createStoreBindingCertCommandSuccessResult() throws SLCommandoBuildException { - final ObjectNode result = mapper.getMapper().createObjectNode(); - addSingleStringElement(result, SL20Constants.SL20_COMMAND_PARAM_BINDING_STORE_RESULT_SUCESS, - SL20Constants.SL20_COMMAND_PARAM_BINDING_STORE_RESULT_SUCESS_VALUE, true); - return result; - - } - - - /** - * Create idAndPassword command parameters - * - * @param keyAlg - * @param dataUrl - * @param x5cEnc - * @return - * @throws SLCommandoBuildException - * @throws CertificateEncodingException - */ - public static ObjectNode createIdAndPasswordCommandParameters(String keyAlg, String dataUrl, X509Certificate x5cEnc) throws SLCommandoBuildException, CertificateEncodingException { - final ObjectNode params = mapper.getMapper().createObjectNode(); - addSingleStringElement(params, SL20Constants.SL20_COMMAND_PARAM_AUTH_IDANDPASSWORD_KEYALG, keyAlg, true); - addSingleStringElement(params, SL20Constants.SL20_COMMAND_PARAM_AUTH_IDANDPASSWORD_DATAURL, dataUrl, true); - addSingleCertificateElement(params, SL20Constants.SL20_COMMAND_PARAM_AUTH_IDANDPASSWORD_X5CENC, x5cEnc, false); - return params; - - } - - /** - * Create idAndPassword command result - * - * @param kontoId - * @param password - * @return - * @throws SLCommandoBuildException - */ - public static ObjectNode createIdAndPasswordCommandResult(String kontoId, byte[] password) throws SLCommandoBuildException { - final ObjectNode result = mapper.getMapper().createObjectNode(); - addSingleStringElement(result, SL20Constants.SL20_COMMAND_PARAM_AUTH_IDANDPASSWORD_RESULT_KONTOID, kontoId, true); - addSingleByteElement(result, SL20Constants.SL20_COMMAND_PARAM_AUTH_IDANDPASSWORD_RESULT_USERPASSWORD, password, true); - return result; - - } - - /** - * Create JWS Token Authentication command - * - * @param nonce - * @param dataUrl - * @param displayData - * @param displayUrl - * @return - * @throws SLCommandoBuildException - */ - public static ObjectNode createJwsTokenAuthCommandParams(String nonce, String dataUrl, List displayData, List displayUrl) throws SLCommandoBuildException { - final ObjectNode params = mapper.getMapper().createObjectNode(); - addSingleStringElement(params, SL20Constants.SL20_COMMAND_PARAM_AUTH_JWSTOKEN_NONCE, nonce, true); - addSingleStringElement(params, SL20Constants.SL20_COMMAND_PARAM_AUTH_JWSTOKEN_DATAURL, dataUrl, true); - addArrayOfStrings(params, SL20Constants.SL20_COMMAND_PARAM_AUTH_JWSTOKEN_DISPLAYDATA, displayData); - addArrayOfStrings(params, SL20Constants.SL20_COMMAND_PARAM_AUTH_JWSTOKEN_DISPLAYURL, displayUrl); - return params; - - } - - /** - * Create JWS Token Authentication command result - * - * @param nonce - * @return - * @throws SLCommandoBuildException - */ - public static ObjectNode createJwsTokenAuthCommandResult(String nonce) throws SLCommandoBuildException { - final ObjectNode result = mapper.getMapper().createObjectNode(); - addSingleStringElement(result, SL20Constants.SL20_COMMAND_PARAM_AUTH_JWSTOKEN_RESULT_NONCE, nonce, true); - return result; - - } - - - /** - * Create Generic Request Container - * - * @param reqId - * @param transactionId - * @param payLoad - * @param signedPayload - * @return - * @throws SLCommandoBuildException - */ - public static ObjectNode createGenericRequest(String reqId, String transactionId, ObjectNode payLoad, String signedPayload) throws SLCommandoBuildException { - final ObjectNode req = mapper.getMapper().createObjectNode(); - addSingleIntegerElement(req, SL20Constants.SL20_VERSION, SL20Constants.CURRENT_SL20_VERSION, true); - addSingleStringElement(req, SL20Constants.SL20_REQID, reqId, true); - addSingleStringElement(req, SL20Constants.SL20_TRANSACTIONID, transactionId, false); - addOnlyOnceOfTwo(req, SL20Constants.SL20_PAYLOAD, SL20Constants.SL20_SIGNEDPAYLOAD, - payLoad, signedPayload); - return req; - - } - - /** - * Create Generic Response Container - * - * @param respId - * @param inResponseTo - * @param transactionId - * @param payLoad - * @param signedPayload - * @return - * @throws SLCommandoBuildException - */ - public static final ObjectNode createGenericResponse(String respId, String inResponseTo, String transactionId, - ObjectNode payLoad, String signedPayload) throws SLCommandoBuildException { - final ObjectNode req = mapper.getMapper().createObjectNode(); - addSingleIntegerElement(req, SL20Constants.SL20_VERSION, SL20Constants.CURRENT_SL20_VERSION, true); - addSingleStringElement(req, SL20Constants.SL20_RESPID, respId, true); - addSingleStringElement(req, SL20Constants.SL20_INRESPTO, inResponseTo, false); - addSingleStringElement(req, SL20Constants.SL20_TRANSACTIONID, transactionId, false); - addOnlyOnceOfTwo(req, SL20Constants.SL20_PAYLOAD, SL20Constants.SL20_SIGNEDPAYLOAD, - payLoad, signedPayload); - return req; - - } - - /** - * Add one element of two possible elements
    - * This method adds either the first element or the second element to parent JSON, but never both. - * - * @param parent Parent JSON element - * @param firstKeyId first element Id - * @param secondKeyId second element Id - * @param first first element - * @param second second element - * @throws SLCommandoBuildException - */ - public static void addOnlyOnceOfTwo(ObjectNode parent, String firstKeyId, String secondKeyId, ObjectNode first, String second) throws SLCommandoBuildException { - if (first == null && (second == null || second.isEmpty())) - throw new SLCommandoBuildException(firstKeyId + " and " + secondKeyId + " is NULL"); - - else if (first != null && second != null) - throw new SLCommandoBuildException(firstKeyId + " and " + secondKeyId + " can not SET TWICE"); - - else if (first != null) - parent.set(firstKeyId, first); - - else if (second != null && !second.isEmpty()) - parent.put(secondKeyId, second); - - else - throw new SLCommandoBuildException("Internal build error"); - } - - - - //TODO!!!! - private static ObjectNode createJsonSignedHeader(JsonSecurityUtils signer) throws SLCommandoBuildException { - final ObjectNode header = mapper.getMapper().createObjectNode(); - addSingleStringElement(header, SL20Constants.JSON_ALGORITHM, SL20Constants.JSON_ALGORITHM_SIGNING_RS256, true); - addSingleStringElement(header, SL20Constants.JSON_CONTENTTYPE, SL20Constants.SL20_CONTENTTYPE_SIGNED_COMMAND, true); - addArrayOfStrings(header, SL20Constants.JSON_X509_CERTIFICATE, Arrays.asList(Constants.DUMMY_SIGNING_CERT)); - - return header; - } - - //TODO!!!! - private static ObjectNode createJsonEncryptionHeader(JsonSecurityUtils signer) throws SLCommandoBuildException { - final ObjectNode header = mapper.getMapper().createObjectNode(); - addSingleStringElement(header, SL20Constants.JSON_ALGORITHM, SL20Constants.JSON_ALGORITHM_ENC_KEY_RSAOAEP, true); - addSingleStringElement(header, SL20Constants.JSON_ENCRYPTION_PAYLOAD, SL20Constants.JSON_ALGORITHM_ENC_PAYLOAD_A128CBCHS256, true); - addSingleStringElement(header, SL20Constants.JSON_CONTENTTYPE, SL20Constants.SL20_CONTENTTYPE_ENCRYPTED_RESULT, true); - addSingleStringElement(header, SL20Constants.JSON_X509_FINGERPRINT, Constants.DUMMY_SIGNING_CERT_FINGERPRINT, true); - - return header; - } - - //TODO!!!! - private static String createJsonSignedFooter(JsonSecurityUtils signer) { - return "cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZmh7\n" + - " AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjbKBYNX4\n" + - " BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHlb1L07Qe7K\n" + - " 0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZESc6BfI7noOPqv\n" + - " hJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrB\n" + - " p0igcN_IoypGlUPQGe77Rw"; - } - - - - private static void addArrayOfStrings(ObjectNode parent, String keyId, List values) throws SLCommandoBuildException { - validateParentAndKey(parent, keyId); - if (values != null) { - final ArrayNode callReqParamsArray = mapper.getMapper().createArrayNode(); - parent.set(keyId, callReqParamsArray ); - for(final String el : values) - callReqParamsArray.add(el); - - } - } - - - private static void addArrayOfStringElements(ObjectNode parent, String keyId, Map keyValuePairs) throws SLCommandoBuildException { - validateParentAndKey(parent, keyId); - if (keyValuePairs != null) { - final ArrayNode callReqParamsArray = mapper.getMapper().createArrayNode(); - parent.set(keyId, callReqParamsArray); - - for(final Entry el : keyValuePairs.entrySet()) { - final ObjectNode callReqParams = mapper.getMapper().createObjectNode(); - callReqParams.put(el.getKey(), el.getValue()); - callReqParamsArray.add(callReqParams); - - } - } - } - - private static void addSingleCertificateElement(ObjectNode parent, String keyId, X509Certificate cert, boolean isRequired) throws CertificateEncodingException, SLCommandoBuildException { - if (cert != null) - addSingleByteElement(parent, keyId, cert.getEncoded(), isRequired); - - else if (isRequired) - throw new SLCommandoBuildException(keyId + " is marked as REQUIRED"); - - } - - - - private static void addSingleByteElement(ObjectNode parent, String keyId, byte[] value, boolean isRequired) throws SLCommandoBuildException { - validateParentAndKey(parent, keyId); - - if (isRequired && value == null) - throw new SLCommandoBuildException(keyId + " has NULL value"); - - else if (value != null) - parent.put(keyId, Base64.getEncoder().encodeToString(value)); - - } - - private static void addSingleBooleanElement(ObjectNode parent, String keyId, Boolean value, boolean isRequired) throws SLCommandoBuildException { - validateParentAndKey(parent, keyId); - - if (isRequired && value == null) - throw new SLCommandoBuildException(keyId + " has a NULL value"); - - else if (value != null) - parent.put(keyId, value); - - } - - private static void addSingleNumberElement(ObjectNode parent, String keyId, Integer value, boolean isRequired) throws SLCommandoBuildException { - validateParentAndKey(parent, keyId); - - if (isRequired && value == null) - throw new SLCommandoBuildException(keyId + " has a NULL value"); - - else if (value != null) - parent.put(keyId, value);; - - } - - private static void addSingleStringElement(ObjectNode parent, String keyId, String value, boolean isRequired) throws SLCommandoBuildException { - validateParentAndKey(parent, keyId); - - if (isRequired && (value == null || value.isEmpty())) - throw new SLCommandoBuildException(keyId + " has an empty value"); - - else if (value != null && !value.isEmpty()) - parent.put(keyId, value); - - } - - private static void addSingleIntegerElement(ObjectNode parent, String keyId, Integer value, boolean isRequired) throws SLCommandoBuildException { - validateParentAndKey(parent, keyId); - - if (isRequired && value == null) - throw new SLCommandoBuildException(keyId + " has an empty value"); - - else if (value != null) - parent.put(keyId, value); - - } - - private static void addSingleJSONElement(ObjectNode parent, String keyId, ObjectNode element, boolean isRequired) throws SLCommandoBuildException { - validateParentAndKey(parent, keyId); - - if (isRequired && element == null) - throw new SLCommandoBuildException("No commando name included"); - - else if (element != null) - parent.set(keyId, element); - - } - - private static void addOnlyOnceOfTwo(ObjectNode parent, String firstKeyId, String secondKeyId, ObjectNode first, ObjectNode second) throws SLCommandoBuildException { - if (first == null && second == null) - throw new SLCommandoBuildException(firstKeyId + " and " + secondKeyId + " is NULL"); - - else if (first != null && second != null) - throw new SLCommandoBuildException(firstKeyId + " and " + secondKeyId + " can not SET TWICE"); - - else if (first != null) - parent.set(firstKeyId, first); - - else if (second != null) - parent.set(secondKeyId, second); - - else - throw new SLCommandoBuildException("Internal build error"); - } - - private static void validateParentAndKey(ObjectNode parent, String keyId) throws SLCommandoBuildException { - if (parent == null) - throw new SLCommandoBuildException("NO parent JSON element"); - - if (keyId == null || keyId.isEmpty()) - throw new SLCommandoBuildException("NO JSON element identifier"); - } -} diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20JSONExtractorUtils.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20JSONExtractorUtils.java deleted file mode 100644 index 314dde17..00000000 --- a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20JSONExtractorUtils.java +++ /dev/null @@ -1,368 +0,0 @@ -package at.gv.egiz.eaaf.modules.auth.sl20.utils; - -import java.util.ArrayList; -import java.util.Base64; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.utils.URIBuilder; -import org.apache.http.util.EntityUtils; -import org.jose4j.base64url.Base64Url; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ObjectNode; - -import at.gv.egiz.eaaf.modules.auth.sl20.data.VerificationResult; -import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SL20Exception; -import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SLCommandoParserException; - -public class SL20JSONExtractorUtils { - private static final Logger log = LoggerFactory.getLogger(SL20JSONExtractorUtils.class); - private static JsonMapper mapper = new JsonMapper(); - - - /** - * Extract String value from JSON - * - * @param input - * @param keyID - * @param isRequired - * @return - * @throws SLCommandoParserException - */ - public static String getStringValue(JsonNode input, String keyID, boolean isRequired) throws SLCommandoParserException { - try { - final JsonNode internal = getAndCheck(input, keyID, isRequired); - - if (internal != null) - return internal.asText(); - else - return null; - - } catch (final SLCommandoParserException e) { - throw e; - - } catch (final Exception e) { - throw new SLCommandoParserException("Can not extract String value with keyId: " + keyID, e); - - } - } - - /** - * Extract Boolean value from JSON - * - * @param input - * @param keyID - * @param isRequired - * @return - * @throws SLCommandoParserException - */ - public static boolean getBooleanValue(ObjectNode input, String keyID, boolean isRequired, boolean defaultValue) throws SLCommandoParserException { - try { - final JsonNode internal = getAndCheck(input, keyID, isRequired); - - if (internal != null) - return internal.asBoolean(); - else - return defaultValue; - - } catch (final SLCommandoParserException e) { - throw e; - - } catch (final Exception e) { - throw new SLCommandoParserException("Can not extract Boolean value with keyId: " + keyID, e); - - } - } - - /** - * Extract JSONObject value from JSON - * - * @param input - * @param keyID - * @param isRequired - * @return - * @throws SLCommandoParserException - */ - public static JsonNode getJSONObjectValue(JsonNode input, String keyID, boolean isRequired) throws SLCommandoParserException { - try { - final JsonNode internal = getAndCheck(input, keyID, isRequired); - - if (internal != null) - return internal; - else - return null; - - } catch (final SLCommandoParserException e) { - throw e; - - } catch (final Exception e) { - throw new SLCommandoParserException("Can not extract Boolean value with keyId: " + keyID, e); - - } - } - - /** - * Extract a List of String elements from a JSON element - * - * @param input - * @return - * @throws SLCommandoParserException - */ - public static List getListOfStringElements(JsonNode input) throws SLCommandoParserException { - final List result = new ArrayList(); - if (input != null) { - if (input.isArray()) { - final Iterator arrayIterator = input.iterator(); - while(arrayIterator.hasNext()) { - final JsonNode next = arrayIterator.next(); - if (next.isTextual()) - result.add(next.asText()); - } - - } else if (input.isTextual()) { - result.add(input.asText()); - - } else { - log.warn("JSON Element IS NOT a JSON array or a JSON Primitive"); - throw new SLCommandoParserException("JSON Element IS NOT a JSON array or a JSON Primitive"); - - } - } - - return result; - } - - /** - * Extract Map of Key/Value pairs from a JSON Element - * - * @param input parent JSON object - * @param keyID KeyId of the child that should be parsed - * @param isRequired - * @return - * @throws SLCommandoParserException - */ - public static Map getMapOfStringElements(JsonNode input, String keyID, boolean isRequired) throws SLCommandoParserException { - final JsonNode internal = getAndCheck(input, keyID, isRequired); - return getMapOfStringElements(internal); - - } - - /** - * Extract Map of Key/Value pairs from a JSON Element - * - * @param input - * @return - * @throws SLCommandoParserException - */ - public static Map getMapOfStringElements(JsonNode input) throws SLCommandoParserException { - final Map result = new HashMap(); - - if (input != null) { - if (input.isArray()) { - final Iterator arrayIterator = input.iterator(); - while(arrayIterator.hasNext()) { - final JsonNode next = arrayIterator.next(); - final Iterator> entry = next.fields(); - entitySetToMap(result, entry); - - } - - } else if (input.isObject()) { - final Iterator> objectKeys = input.fields(); - entitySetToMap(result, objectKeys); - - } else - throw new SLCommandoParserException("JSON Element IS NOT a JSON array or a JSON object"); - - } - - return result; - } - - private static void entitySetToMap(Map result, Iterator> entry) { - while (entry.hasNext()) { - final Entry el = entry.next(); - if (result.containsKey(el.getKey())) - log.info("Attr. Map already contains Element with Key: " + el.getKey() + ". Overwrite element ... "); - - result.put(el.getKey(), el.getValue().asText()); - - } - - } - - - public static JsonNode extractSL20Result(JsonNode command, IJOSETools decrypter, boolean mustBeEncrypted) throws SL20Exception { - final JsonNode result = command.get(SL20Constants.SL20_COMMAND_CONTAINER_RESULT); - final JsonNode encryptedResult = command.get(SL20Constants.SL20_COMMAND_CONTAINER_ENCRYPTEDRESULT); - - if (result == null && encryptedResult == null) - throw new SLCommandoParserException("NO result OR encryptedResult FOUND."); - - else if (encryptedResult == null && mustBeEncrypted) - throw new SLCommandoParserException("result MUST be encrypted."); - - else if (encryptedResult != null && encryptedResult.isTextual()) { - try { - return decrypter.decryptPayload(encryptedResult.asText()); - - } catch (final Exception e) { - log.info("Can NOT decrypt SL20 result. Reason:" + e.getMessage()); - if (!mustBeEncrypted) { - log.warn("Decrypted results are disabled by configuration. Parse result in plain if it is possible"); - - //dummy code - try { - final String[] signedPayload = encryptedResult.toString().split("\\."); - final JsonNode payLoad = mapper.getMapper().readTree(new String(Base64.getUrlDecoder().decode(signedPayload[1]))); - return payLoad; - - } catch (final Exception e1) { - log.debug("DummyCode FAILED, Reason: " + e1.getMessage() + " Ignore it ..."); - throw new SL20Exception(e.getMessage(), null, e); - - } - - } else - throw e; - - } - - } else if (result != null) { - return result; - - } else - throw new SLCommandoParserException("Internal build error"); - - - } - - /** - * Extract payLoad from generic transport container - * - * @param container - * @param joseTools - * @return - * @throws SLCommandoParserException - */ - public static VerificationResult extractSL20PayLoad(JsonNode container, IJOSETools joseTools, boolean mustBeSigned) throws SL20Exception { - - final JsonNode sl20Payload = container.get(SL20Constants.SL20_PAYLOAD); - final JsonNode sl20SignedPayload = container.get(SL20Constants.SL20_SIGNEDPAYLOAD); - - if (mustBeSigned && joseTools == null) - throw new SLCommandoParserException("'joseTools' MUST be set if 'mustBeSigned' is 'true'"); - - if (sl20Payload == null && sl20SignedPayload == null) - throw new SLCommandoParserException("NO payLoad OR signedPayload FOUND."); - - else if (sl20SignedPayload == null && mustBeSigned) - throw new SLCommandoParserException("payLoad MUST be signed."); - - else if (joseTools != null && sl20SignedPayload != null && sl20SignedPayload.isTextual()) { - return joseTools.validateSignature(sl20SignedPayload.asText()); - - } else if (sl20Payload != null) - return new VerificationResult(sl20Payload); - - else - throw new SLCommandoParserException("Internal build error"); - - - } - - - /** - * Extract generic transport container from httpResponse - * - * @param httpResp - * @return - * @throws SLCommandoParserException - */ - public static JsonNode getSL20ContainerFromResponse(HttpResponse httpResp) throws SLCommandoParserException { - try { - JsonNode sl20Resp = null; - if (httpResp.getStatusLine().getStatusCode() == 303 || httpResp.getStatusLine().getStatusCode() == 307) { - final Header[] locationHeader = httpResp.getHeaders("Location"); - if (locationHeader == null) - throw new SLCommandoParserException("Find Redirect statuscode but not Location header"); - - final String sl20RespString = new URIBuilder(locationHeader[0].getValue()).getQueryParams().get(0).getValue(); - sl20Resp = mapper.getMapper().readTree(Base64Url.decode(sl20RespString)); - - } else if (httpResp.getStatusLine().getStatusCode() == 200) { - if (httpResp.getEntity().getContentType() == null) - throw new SLCommandoParserException("SL20 response contains NO ContentType"); - - if (!httpResp.getEntity().getContentType().getValue().startsWith("application/json")) - throw new SLCommandoParserException("SL20 response with a wrong ContentType: " + httpResp.getEntity().getContentType().getValue()); - sl20Resp = parseSL20ResultFromResponse(httpResp.getEntity()); - - } else if ( (httpResp.getStatusLine().getStatusCode() == 500) || - (httpResp.getStatusLine().getStatusCode() == 401) || - (httpResp.getStatusLine().getStatusCode() == 400) ) { - log.info("SL20 response with http-code: " + httpResp.getStatusLine().getStatusCode() - + ". Search for error message"); - - try { - sl20Resp = parseSL20ResultFromResponse(httpResp.getEntity()); - - } catch (final Exception e) { - log.warn("SL20 response contains no valid JSON", e); - throw new SLCommandoParserException("SL20 response with http-code: " + httpResp.getStatusLine().getStatusCode() - + " AND NO valid JSON errormsg", e); - - } - - - - } else - throw new SLCommandoParserException("SL20 response with http-code: " + httpResp.getStatusLine().getStatusCode()); - - log.info("Find JSON object in http response"); - return sl20Resp; - - } catch (final Exception e) { - throw new SLCommandoParserException("SL20 response parsing FAILED! Reason: " + e.getMessage(), e); - - } - } - - private static JsonNode parseSL20ResultFromResponse(HttpEntity resp) throws Exception { - if (resp != null && resp.getContent() != null) { - final String rawSL20Resp = EntityUtils.toString(resp); - final JsonNode sl20Resp = mapper.getMapper().readTree(rawSL20Resp); - - //TODO: check sl20Resp type like && sl20Resp.isJsonObject() - if (sl20Resp != null) { - return sl20Resp; - - } else - throw new SLCommandoParserException("SL2.0 can NOT parse to a JSON object"); - - - } else - throw new SLCommandoParserException("Can NOT find content in http response"); - - } - - - private static JsonNode getAndCheck(JsonNode input, String keyID, boolean isRequired) throws SLCommandoParserException { - final JsonNode internal = input.get(keyID); - - if (internal == null && isRequired) - throw new SLCommandoParserException("REQUIRED Element with keyId: " + keyID + " does not exist"); - - return internal; - - } -} diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20JsonBuilderUtils.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20JsonBuilderUtils.java new file mode 100644 index 00000000..f505f28d --- /dev/null +++ b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20JsonBuilderUtils.java @@ -0,0 +1,731 @@ +package at.gv.egiz.eaaf.modules.auth.sl20.utils; + +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import at.gv.egiz.eaaf.modules.auth.sl20.Constants; +import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SlCommandoBuildException; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + +public class SL20JsonBuilderUtils { + + private static JsonMapper mapper = new JsonMapper(); + + /** + * Create command request. + * + * @param name Commando name + * @param params Commando parameters + * @return JSON Object + * @throws SlCommandoBuildException In case of a build error + */ + public static ObjectNode createCommand(final String name, final ObjectNode params) + throws SlCommandoBuildException { + + final ObjectNode command = mapper.getMapper().createObjectNode(); + addSingleStringElement(command, SL20Constants.SL20_COMMAND_CONTAINER_NAME, name, true); + addSingleJsonElement(command, SL20Constants.SL20_COMMAND_CONTAINER_PARAMS, params, true); + return command; + + } + + /** + * Create signed command request. + * + * @param name Commando name + * @param params commando parameter + * @param signer JWS signer implementation + * @return Serialized JWS + * @throws SlCommandoBuildException In case of a build error + */ + public static String createSignedCommand(final String name, final ObjectNode params, + final IJoseTools signer) throws SlCommandoBuildException { + final ObjectNode command = mapper.getMapper().createObjectNode(); + addSingleStringElement(command, SL20Constants.SL20_COMMAND_CONTAINER_NAME, name, true); + addSingleJsonElement(command, SL20Constants.SL20_COMMAND_CONTAINER_PARAMS, params, true); + return signer.createSignature(command.toString()); + + } + + + /** + * Create encrypted command result. + * + * @param result JSON to encrypt + * @param encrypter JWE encrypter implementation + * @return Serialized JWE + * @throws SlCommandoBuildException In case of a processing error + */ + public static String createEncryptedCommandoResult(final ObjectNode result, + final JsonSecurityUtils encrypter) throws SlCommandoBuildException { + // TODO: add real implementation + // create header and footer + final String dummyHeader = createJsonEncryptionHeader(encrypter).toString(); + final String payLoad = result.toString(); + final String dummyFooter = createJsonSignedFooter(encrypter); + + return Base64.getUrlEncoder().encodeToString(dummyHeader.getBytes()) + "." + + Base64.getUrlEncoder().encodeToString(payLoad.getBytes()) + "." + + Base64.getUrlEncoder().encodeToString(dummyFooter.getBytes()); + + } + + + /** + * Create command result. + * + * @param name Commando name + * @param result commande result + * @param encryptedResult encrypted commando result + * @return Result json + * @throws SlCommandoBuildException In case of an error + */ + public static ObjectNode createCommandResponse(final String name, final ObjectNode result, + final String encryptedResult) throws SlCommandoBuildException { + final ObjectNode command = mapper.getMapper().createObjectNode(); + addSingleStringElement(command, SL20Constants.SL20_COMMAND_CONTAINER_NAME, name, true); + addOnlyOnceOfTwo(command, SL20Constants.SL20_COMMAND_CONTAINER_RESULT, + SL20Constants.SL20_COMMAND_CONTAINER_ENCRYPTEDRESULT, result, encryptedResult); + return command; + + } + + /** + * Create signed command result. + * + * @param name commando name + * @param result commando result + * @param encryptedResult encrypted commando result + * @return JWS in serialized form + * @throws SlCommandoBuildException in case of an error + + */ + public static String createSignedCommandResponse(final String name, final ObjectNode result, + final String encryptedResult, final JsonSecurityUtils signer) + throws SlCommandoBuildException { + final ObjectNode command = mapper.getMapper().createObjectNode(); + addSingleStringElement(command, SL20Constants.SL20_COMMAND_CONTAINER_NAME, name, true); + addOnlyOnceOfTwo(command, SL20Constants.SL20_COMMAND_CONTAINER_RESULT, + SL20Constants.SL20_COMMAND_CONTAINER_ENCRYPTEDRESULT, result, encryptedResult); + final String encodedCommand = command.toString(); + + // TODO: add real implementation + // create header and footer + final String dummyHeader = createJsonSignedHeader(signer).toString(); + final String dummyFooter = createJsonSignedFooter(signer); + + return Base64.getUrlEncoder().encodeToString(dummyHeader.getBytes()) + "." + + Base64.getUrlEncoder().encodeToString(encodedCommand.getBytes()) + "." + + Base64.getUrlEncoder().encodeToString(dummyFooter.getBytes()); + + } + + /** + * Create parameters for Redirect command. + * + * @param url redirect URL + * @param command embedded command + * @param signedCommand Signed embedded command + * @param ipcRedirect IPC redirect flag + * @return result JSON + * @throws SlCommandoBuildException In case of an error + */ + public static ObjectNode createRedirectCommandParameters(final String url, + final ObjectNode command, final ObjectNode signedCommand, final Boolean ipcRedirect) + throws SlCommandoBuildException { + final ObjectNode redirectReqParams = mapper.getMapper().createObjectNode(); + addOnlyOnceOfTwo(redirectReqParams, SL20Constants.SL20_COMMAND_PARAM_GENERAL_REDIRECT_COMMAND, + SL20Constants.SL20_COMMAND_PARAM_GENERAL_REDIRECT_SIGNEDCOMMAND, command, signedCommand); + addSingleStringElement(redirectReqParams, SL20Constants.SL20_COMMAND_PARAM_GENERAL_REDIRECT_URL, + url, false); + addSingleBooleanElement(redirectReqParams, + SL20Constants.SL20_COMMAND_PARAM_GENERAL_REDIRECT_IPCREDIRECT, ipcRedirect, false); + return redirectReqParams; + + } + + /** + * Create parameters for Call command. + * + * @param url http URL for Call command + * @param method http method used by call commando result + * @param includeTransactionId TransactionId + * @param reqParameters Request parameters on CALL command + * @return JSON + * @throws SlCommandoBuildException In case of an error + */ + public static ObjectNode createCallCommandParameters(final String url, final String method, + final Boolean includeTransactionId, final Map reqParameters) + throws SlCommandoBuildException { + final ObjectNode callReqParams = mapper.getMapper().createObjectNode(); + addSingleStringElement(callReqParams, SL20Constants.SL20_COMMAND_PARAM_GENERAL_CALL_URL, url, + true); + addSingleStringElement(callReqParams, SL20Constants.SL20_COMMAND_PARAM_GENERAL_CALL_METHOD, + method, true); + addSingleBooleanElement(callReqParams, + SL20Constants.SL20_COMMAND_PARAM_GENERAL_CALL_INCLUDETRANSACTIONID, includeTransactionId, + false); + addArrayOfStringElements(callReqParams, + SL20Constants.SL20_COMMAND_PARAM_GENERAL_CALL_REQPARAMETER, reqParameters); + return callReqParams; + + } + + /** + * Create result for Error command. + * + * @param errorCode Error-Code + * @param errorMsg Error-message + * @return JSON + * @throws SlCommandoBuildException In case of an error + */ + public static ObjectNode createErrorCommandResult(final String errorCode, final String errorMsg) + throws SlCommandoBuildException { + final ObjectNode result = mapper.getMapper().createObjectNode(); + addSingleStringElement(result, SL20Constants.SL20_COMMAND_PARAM_GENERAL_RESPONSE_ERRORCODE, + errorCode, true); + addSingleStringElement(result, SL20Constants.SL20_COMMAND_PARAM_GENERAL_RESPONSE_ERRORMESSAGE, + errorMsg, true); + return result; + + } + + /** + * Create parameters for qualifiedeID command. + * + * @param consentTemplateId Identifier of the template that is used for consent visualization + * @param consent Consent that has to be signed by user + * @param dataUrl DataURL for result + * @param x5cEnc Response encryption certificate + * @return JSON + * @throws CertificateEncodingException In case of a encryption certificate encoding problem + * @throws SlCommandoBuildException In case of a generel error + */ + public static ObjectNode createQualifiedeEidConsent(final String consentTemplateId, + final byte[] consent, final String dataUrl, final X509Certificate x5cEnc) + throws CertificateEncodingException, SlCommandoBuildException { + final ObjectNode params = mapper.getMapper().createObjectNode(); + addSingleStringElement(params, SL20Constants.SL20_COMMAND_PARAM_EID_CONSENTTEMPLATEID, + consentTemplateId, true); + addSingleByteElement(params, SL20Constants.SL20_COMMAND_PARAM_EID_CONSENT, consent, true); + addSingleStringElement(params, SL20Constants.SL20_COMMAND_PARAM_EID_DATAURL, dataUrl, true); + addSingleCertificateElement(params, SL20Constants.SL20_COMMAND_PARAM_EID_X5CENC, x5cEnc, false); + return params; + + } + + + /** + * Create parameters for qualifiedeID command. + * + * @param authBlockId AuthBlock transformation Id + * @param dataUrl DataURL for result + * @param additionalReqParameters additional parameters + * @param x5cEnc Response encryption certificate + * @return JSON + * @throws CertificateEncodingException In case of a encryption certificate encoding problem + * @throws SlCommandoBuildException In case of a generel error + */ + @Deprecated + public static ObjectNode createQualifiedEidCommandParameters(final String authBlockId, + final String dataUrl, final Map additionalReqParameters, + final X509Certificate x5cEnc) throws CertificateEncodingException, SlCommandoBuildException { + final ObjectNode params = mapper.getMapper().createObjectNode(); + addSingleStringElement(params, SL20Constants.SL20_COMMAND_PARAM_EID_AUTHBLOCKID, authBlockId, + true); + addSingleStringElement(params, SL20Constants.SL20_COMMAND_PARAM_EID_DATAURL, dataUrl, true); + addArrayOfStringElements(params, SL20Constants.SL20_COMMAND_PARAM_EID_ATTRIBUTES, + additionalReqParameters); + addSingleCertificateElement(params, SL20Constants.SL20_COMMAND_PARAM_EID_X5CENC, x5cEnc, false); + return params; + + } + + /** + * Create result for qualifiedeID command. + * + * @param idl IdentityLink + * @param authBlock AuthBlock + * @param ccsUrl VDA URL + * @param loa LoA + * @return JSON + * @throws SlCommandoBuildException In case of an error + */ + public static ObjectNode createQualifiedEidCommandResult(final byte[] idl, final byte[] authBlock, + final String ccsUrl, final String loa) throws SlCommandoBuildException { + final ObjectNode result = mapper.getMapper().createObjectNode(); + addSingleByteElement(result, SL20Constants.SL20_COMMAND_PARAM_EID_RESULT_IDL, idl, true); + addSingleByteElement(result, SL20Constants.SL20_COMMAND_PARAM_EID_RESULT_AUTHBLOCK, authBlock, + true); + addSingleStringElement(result, SL20Constants.SL20_COMMAND_PARAM_EID_RESULT_CCSURL, ccsUrl, + true); + addSingleStringElement(result, SL20Constants.SL20_COMMAND_PARAM_EID_RESULT_LOA, loa, true); + return result; + + } + + + /** + * Create Binding-Key command parameters. + * + * @param kontoId KontoId + * @param subjectName SubjectName + * @param keySize KeySize + * @param keyAlg Key-algorithm + * @param policies Key policy + * @param dataUrl DataURL + * @param x5cVdaTrust trusted certificate from VDA + * @param reqUserPassword User passwort initialize request + * @param x5cEnc Result encryption certificate + * @return JSON + * @throws SlCommandoBuildException in case of an errr + * @throws CertificateEncodingException In case of a certificate error + */ + public static ObjectNode createBindingKeyCommandParams(final String kontoId, + final String subjectName, final int keySize, final String keyAlg, + final Map policies, final String dataUrl, final X509Certificate x5cVdaTrust, + final Boolean reqUserPassword, final X509Certificate x5cEnc) + throws SlCommandoBuildException, CertificateEncodingException { + final ObjectNode params = mapper.getMapper().createObjectNode(); + addSingleStringElement(params, SL20Constants.SL20_COMMAND_PARAM_BINDING_CREATE_KONTOID, kontoId, + true); + addSingleStringElement(params, SL20Constants.SL20_COMMAND_PARAM_BINDING_CREATE_SN, subjectName, + true); + addSingleNumberElement(params, SL20Constants.SL20_COMMAND_PARAM_BINDING_CREATE_KEYLENGTH, + keySize, true); + addSingleStringElement(params, SL20Constants.SL20_COMMAND_PARAM_BINDING_CREATE_KEYALG, keyAlg, + true); + addArrayOfStringElements(params, SL20Constants.SL20_COMMAND_PARAM_BINDING_CREATE_POLICIES, + policies); + addSingleStringElement(params, SL20Constants.SL20_COMMAND_PARAM_BINDING_CREATE_DATAURL, dataUrl, + true); + addSingleCertificateElement(params, SL20Constants.SL20_COMMAND_PARAM_BINDING_CREATE_X5CVDATRUST, + x5cVdaTrust, false); + addSingleBooleanElement(params, + SL20Constants.SL20_COMMAND_PARAM_BINDING_CREATE_REQUESTUSERPASSWORD, reqUserPassword, + false); + addSingleCertificateElement(params, SL20Constants.SL20_COMMAND_PARAM_BINDING_CREATE_X5CENC, + x5cEnc, false); + return params; + + } + + /** + * Create Binding-Key command result. + * + * @param appId AppId + * @param csr CSR + * @param attCert Key-Attestation certificate + * @param password user's password + * @return JSON + * @throws SlCommandoBuildException In case of an error + * @throws CertificateEncodingException In case of a certificate processing error + */ + public static ObjectNode createBindingKeyCommandResult(final String appId, final byte[] csr, + final X509Certificate attCert, final byte[] password) + throws SlCommandoBuildException, CertificateEncodingException { + final ObjectNode result = mapper.getMapper().createObjectNode(); + addSingleStringElement(result, SL20Constants.SL20_COMMAND_PARAM_BINDING_CREATE_RESULT_APPID, + appId, true); + addSingleByteElement(result, SL20Constants.SL20_COMMAND_PARAM_BINDING_CREATE_RESULT_CSR, csr, + true); + addSingleCertificateElement(result, + SL20Constants.SL20_COMMAND_PARAM_BINDING_CREATE_RESULT_KEYATTESTATIONZERTIFICATE, attCert, + false); + addSingleByteElement(result, + SL20Constants.SL20_COMMAND_PARAM_BINDING_CREATE_RESULT_USERPASSWORD, password, false); + return result; + + } + + /** + * Create Store Binding-Certificate command parameters. + * + * @param cert Certificate + * @param dataUrl DATA URL + * @return JSON + * @throws CertificateEncodingException In case of a certificate processing error + * @throws SlCommandoBuildException In case of a error + */ + public static ObjectNode createStoreBindingCertCommandParams(final X509Certificate cert, + final String dataUrl) throws CertificateEncodingException, SlCommandoBuildException { + final ObjectNode params = mapper.getMapper().createObjectNode(); + addSingleCertificateElement(params, SL20Constants.SL20_COMMAND_PARAM_BINDING_STORE_CERTIFICATE, + cert, true); + addSingleStringElement(params, SL20Constants.SL20_COMMAND_PARAM_BINDING_STORE_DATAURL, dataUrl, + true); + return params; + + } + + /** + * Create Store Binding-Certificate command result. + * + * @return JSON + * @throws SlCommandoBuildException In case of an error + */ + public static ObjectNode createStoreBindingCertCommandSuccessResult() + throws SlCommandoBuildException { + final ObjectNode result = mapper.getMapper().createObjectNode(); + addSingleStringElement(result, SL20Constants.SL20_COMMAND_PARAM_BINDING_STORE_RESULT_SUCESS, + SL20Constants.SL20_COMMAND_PARAM_BINDING_STORE_RESULT_SUCESS_VALUE, true); + return result; + + } + + + /** + * Create idAndPassword command parameters. + * + * @param keyAlg key algorithm + * @param dataUrl DATA Url + * @param x5cEnc result encryption certificate + * @return JSON + * @throws SlCommandoBuildException In case of an error + * @throws CertificateEncodingException In case of a certificate processing error + */ + public static ObjectNode createIdAndPasswordCommandParameters(final String keyAlg, + final String dataUrl, final X509Certificate x5cEnc) + throws SlCommandoBuildException, CertificateEncodingException { + final ObjectNode params = mapper.getMapper().createObjectNode(); + addSingleStringElement(params, SL20Constants.SL20_COMMAND_PARAM_AUTH_IDANDPASSWORD_KEYALG, + keyAlg, true); + addSingleStringElement(params, SL20Constants.SL20_COMMAND_PARAM_AUTH_IDANDPASSWORD_DATAURL, + dataUrl, true); + addSingleCertificateElement(params, SL20Constants.SL20_COMMAND_PARAM_AUTH_IDANDPASSWORD_X5CENC, + x5cEnc, false); + return params; + + } + + /** + * Create idAndPassword command result. + * + * @param kontoId User's Id + * @param password User's password + * @return JSON + * @throws SlCommandoBuildException In case of an error + */ + public static ObjectNode createIdAndPasswordCommandResult(final String kontoId, + final byte[] password) throws SlCommandoBuildException { + final ObjectNode result = mapper.getMapper().createObjectNode(); + addSingleStringElement(result, + SL20Constants.SL20_COMMAND_PARAM_AUTH_IDANDPASSWORD_RESULT_KONTOID, kontoId, true); + addSingleByteElement(result, + SL20Constants.SL20_COMMAND_PARAM_AUTH_IDANDPASSWORD_RESULT_USERPASSWORD, password, true); + return result; + + } + + /** + * Create JWS Token Authentication command. + * + * @param nonce nonce that should be signed + * @param dataUrl Data URL + * @param displayData Data that should be displayed + * @param displayUrl URL to data that should be displayed + * @return JSON + * @throws SlCommandoBuildException In case of an error + */ + public static ObjectNode createJwsTokenAuthCommandParams(final String nonce, final String dataUrl, + final List displayData, final List displayUrl) + throws SlCommandoBuildException { + final ObjectNode params = mapper.getMapper().createObjectNode(); + addSingleStringElement(params, SL20Constants.SL20_COMMAND_PARAM_AUTH_JWSTOKEN_NONCE, nonce, + true); + addSingleStringElement(params, SL20Constants.SL20_COMMAND_PARAM_AUTH_JWSTOKEN_DATAURL, dataUrl, + true); + addArrayOfStrings(params, SL20Constants.SL20_COMMAND_PARAM_AUTH_JWSTOKEN_DISPLAYDATA, + displayData); + addArrayOfStrings(params, SL20Constants.SL20_COMMAND_PARAM_AUTH_JWSTOKEN_DISPLAYURL, + displayUrl); + return params; + + } + + /** + * Create JWS Token Authentication command result. + * + * @param nonce Serialzed JWS that contains the signed nonce + * @return JSON + * @throws SlCommandoBuildException In case of an error + */ + public static ObjectNode createJwsTokenAuthCommandResult(final String nonce) + throws SlCommandoBuildException { + final ObjectNode result = mapper.getMapper().createObjectNode(); + addSingleStringElement(result, SL20Constants.SL20_COMMAND_PARAM_AUTH_JWSTOKEN_RESULT_NONCE, + nonce, true); + return result; + + } + + + /** + * Create Generic Request Container. + * + * @param reqId RequestId + * @param transactionId TransactionId + * @param payLoad unsigned payload + * @param signedPayload Signed payload + * @return JSON + * @throws SlCommandoBuildException In case of an error + */ + public static ObjectNode createGenericRequest(final String reqId, final String transactionId, + final ObjectNode payLoad, final String signedPayload) throws SlCommandoBuildException { + final ObjectNode req = mapper.getMapper().createObjectNode(); + addSingleIntegerElement(req, SL20Constants.SL20_VERSION, SL20Constants.CURRENT_SL20_VERSION, + true); + addSingleStringElement(req, SL20Constants.SL20_REQID, reqId, true); + addSingleStringElement(req, SL20Constants.SL20_TRANSACTIONID, transactionId, false); + addOnlyOnceOfTwo(req, SL20Constants.SL20_PAYLOAD, SL20Constants.SL20_SIGNEDPAYLOAD, payLoad, + signedPayload); + return req; + + } + + /** + * Create Generic Response Container. + * + * @param respId Response Id + * @param inResponseTo RequestId to this response + * @param transactionId transactionId + * @param payLoad Unsigned payload + * @param signedPayload Signed payload + * @return JSON + * @throws SlCommandoBuildException In case of an error + */ + public static final ObjectNode createGenericResponse(final String respId, + final String inResponseTo, final String transactionId, final ObjectNode payLoad, + final String signedPayload) throws SlCommandoBuildException { + final ObjectNode req = mapper.getMapper().createObjectNode(); + addSingleIntegerElement(req, SL20Constants.SL20_VERSION, SL20Constants.CURRENT_SL20_VERSION, + true); + addSingleStringElement(req, SL20Constants.SL20_RESPID, respId, true); + addSingleStringElement(req, SL20Constants.SL20_INRESPTO, inResponseTo, false); + addSingleStringElement(req, SL20Constants.SL20_TRANSACTIONID, transactionId, false); + addOnlyOnceOfTwo(req, SL20Constants.SL20_PAYLOAD, SL20Constants.SL20_SIGNEDPAYLOAD, payLoad, + signedPayload); + return req; + + } + + private static void addOnlyOnceOfTwo(final ObjectNode parent, final String firstKeyId, + final String secondKeyId, final ObjectNode first, final ObjectNode second) + throws SlCommandoBuildException { + if (first == null && second == null) { + throw new SlCommandoBuildException(firstKeyId + " and " + secondKeyId + " is NULL"); + } else if (first != null && second != null) { + throw new SlCommandoBuildException(firstKeyId + " and " + secondKeyId + " can not SET TWICE"); + } else if (first != null) { + parent.set(firstKeyId, first); + } else if (second != null) { + parent.set(secondKeyId, second); + } else { + throw new SlCommandoBuildException("Internal build error"); + } + } + + /** + * Add one element of two possible elements
    + * This method adds either the first element or the second element to parent JSON, but never both. + * + * @param parent Parent JSON element + * @param firstKeyId first element Id + * @param secondKeyId second element Id + * @param first first element + * @param second second element + * @throws SlCommandoBuildException In case of an error. + */ + public static void addOnlyOnceOfTwo(final ObjectNode parent, final String firstKeyId, + final String secondKeyId, final ObjectNode first, final String second) + throws SlCommandoBuildException { + if (first == null && (second == null || second.isEmpty())) { + throw new SlCommandoBuildException(firstKeyId + " and " + secondKeyId + " is NULL"); + } else if (first != null && second != null) { + throw new SlCommandoBuildException(firstKeyId + " and " + secondKeyId + " can not SET TWICE"); + } else if (first != null) { + parent.set(firstKeyId, first); + } else if (second != null && !second.isEmpty()) { + parent.put(secondKeyId, second); + } else { + throw new SlCommandoBuildException("Internal build error"); + } + } + + + + // TODO!!!! + private static ObjectNode createJsonSignedHeader(final JsonSecurityUtils signer) + throws SlCommandoBuildException { + final ObjectNode header = mapper.getMapper().createObjectNode(); + addSingleStringElement(header, SL20Constants.JSON_ALGORITHM, + SL20Constants.JSON_ALGORITHM_SIGNING_RS256, true); + addSingleStringElement(header, SL20Constants.JSON_CONTENTTYPE, + SL20Constants.SL20_CONTENTTYPE_SIGNED_COMMAND, true); + addArrayOfStrings(header, SL20Constants.JSON_X509_CERTIFICATE, + Arrays.asList(Constants.DUMMY_SIGNING_CERT)); + + return header; + } + + // TODO!!!! + private static ObjectNode createJsonEncryptionHeader(final JsonSecurityUtils signer) + throws SlCommandoBuildException { + final ObjectNode header = mapper.getMapper().createObjectNode(); + addSingleStringElement(header, SL20Constants.JSON_ALGORITHM, + SL20Constants.JSON_ALGORITHM_ENC_KEY_RSAOAEP, true); + addSingleStringElement(header, SL20Constants.JSON_ENCRYPTION_PAYLOAD, + SL20Constants.JSON_ALGORITHM_ENC_PAYLOAD_A128CBCHS256, true); + addSingleStringElement(header, SL20Constants.JSON_CONTENTTYPE, + SL20Constants.SL20_CONTENTTYPE_ENCRYPTED_RESULT, true); + addSingleStringElement(header, SL20Constants.JSON_X509_FINGERPRINT, + Constants.DUMMY_SIGNING_CERT_FINGERPRINT, true); + + return header; + } + + // TODO!!!! + private static String createJsonSignedFooter(final JsonSecurityUtils signer) { + return "cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZmh7\n" + + " AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjbKBYNX4\n" + + " BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHlb1L07Qe7K\n" + + " 0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZESc6BfI7noOPqv\n" + + " hJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrB\n" + + " p0igcN_IoypGlUPQGe77Rw"; + } + + + + private static void addArrayOfStrings(final ObjectNode parent, final String keyId, + final List values) throws SlCommandoBuildException { + validateParentAndKey(parent, keyId); + if (values != null) { + final ArrayNode callReqParamsArray = mapper.getMapper().createArrayNode(); + parent.set(keyId, callReqParamsArray); + for (final String el : values) { + callReqParamsArray.add(el); + } + + } + } + + + private static void addArrayOfStringElements(final ObjectNode parent, final String keyId, + final Map keyValuePairs) throws SlCommandoBuildException { + validateParentAndKey(parent, keyId); + if (keyValuePairs != null) { + final ArrayNode callReqParamsArray = mapper.getMapper().createArrayNode(); + parent.set(keyId, callReqParamsArray); + + for (final Entry el : keyValuePairs.entrySet()) { + final ObjectNode callReqParams = mapper.getMapper().createObjectNode(); + callReqParams.put(el.getKey(), el.getValue()); + callReqParamsArray.add(callReqParams); + + } + } + } + + private static void addSingleCertificateElement(final ObjectNode parent, final String keyId, + final X509Certificate cert, final boolean isRequired) + throws CertificateEncodingException, SlCommandoBuildException { + if (cert != null) { + addSingleByteElement(parent, keyId, cert.getEncoded(), isRequired); + } else if (isRequired) { + throw new SlCommandoBuildException(keyId + " is marked as REQUIRED"); + } + + } + + + + private static void addSingleByteElement(final ObjectNode parent, final String keyId, + final byte[] value, final boolean isRequired) throws SlCommandoBuildException { + validateParentAndKey(parent, keyId); + + if (isRequired && value == null) { + throw new SlCommandoBuildException(keyId + " has NULL value"); + } else if (value != null) { + parent.put(keyId, Base64.getEncoder().encodeToString(value)); + } + + } + + private static void addSingleBooleanElement(final ObjectNode parent, final String keyId, + final Boolean value, final boolean isRequired) throws SlCommandoBuildException { + validateParentAndKey(parent, keyId); + + if (isRequired && value == null) { + throw new SlCommandoBuildException(keyId + " has a NULL value"); + } else if (value != null) { + parent.put(keyId, value); + } + + } + + private static void addSingleNumberElement(final ObjectNode parent, final String keyId, + final Integer value, final boolean isRequired) throws SlCommandoBuildException { + validateParentAndKey(parent, keyId); + + if (isRequired && value == null) { + throw new SlCommandoBuildException(keyId + " has a NULL value"); + } else if (value != null) { + parent.put(keyId, value); + } + + } + + private static void addSingleStringElement(final ObjectNode parent, final String keyId, + final String value, final boolean isRequired) throws SlCommandoBuildException { + validateParentAndKey(parent, keyId); + + if (isRequired && (value == null || value.isEmpty())) { + throw new SlCommandoBuildException(keyId + " has an empty value"); + } else if (value != null && !value.isEmpty()) { + parent.put(keyId, value); + } + + } + + private static void addSingleIntegerElement(final ObjectNode parent, final String keyId, + final Integer value, final boolean isRequired) throws SlCommandoBuildException { + validateParentAndKey(parent, keyId); + + if (isRequired && value == null) { + throw new SlCommandoBuildException(keyId + " has an empty value"); + } else if (value != null) { + parent.put(keyId, value); + } + + } + + private static void addSingleJsonElement(final ObjectNode parent, final String keyId, + final ObjectNode element, final boolean isRequired) throws SlCommandoBuildException { + validateParentAndKey(parent, keyId); + + if (isRequired && element == null) { + throw new SlCommandoBuildException("No commando name included"); + } else if (element != null) { + parent.set(keyId, element); + } + + } + + + + private static void validateParentAndKey(final ObjectNode parent, final String keyId) + throws SlCommandoBuildException { + if (parent == null) { + throw new SlCommandoBuildException("NO parent JSON element"); + } + + if (keyId == null || keyId.isEmpty()) { + throw new SlCommandoBuildException("NO JSON element identifier"); + } + } +} diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20JsonExtractorUtils.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20JsonExtractorUtils.java new file mode 100644 index 00000000..f4b5a724 --- /dev/null +++ b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20JsonExtractorUtils.java @@ -0,0 +1,407 @@ +package at.gv.egiz.eaaf.modules.auth.sl20.utils; + +import java.util.ArrayList; +import java.util.Base64; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import at.gv.egiz.eaaf.modules.auth.sl20.data.VerificationResult; +import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SL20Exception; +import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SlCommandoParserException; +import org.apache.http.Header; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.util.EntityUtils; +import org.jose4j.base64url.Base64Url; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + +public class SL20JsonExtractorUtils { + private static final Logger log = LoggerFactory.getLogger(SL20JsonExtractorUtils.class); + private static JsonMapper mapper = new JsonMapper(); + + + /** + * Extract String value from JSON. + * + * @param input JSON + * @param keyID Element identifier + * @param isRequired true, if the element must not null + * @return Value of this element + * @throws SlCommandoParserException In case an error + */ + public static String getStringValue(final JsonNode input, final String keyID, + final boolean isRequired) throws SlCommandoParserException { + try { + final JsonNode internal = getAndCheck(input, keyID, isRequired); + + if (internal != null) { + return internal.asText(); + } else { + return null; + } + + } catch (final SlCommandoParserException e) { + throw e; + + } catch (final Exception e) { + throw new SlCommandoParserException("Can not extract String value with keyId: " + keyID, e); + + } + } + + /** + * Extract Boolean value from JSON. + * + * @param input JSON + * @param keyID Element identifier + * @param isRequired true, if the element must not null + * @return Boolean + * @throws SlCommandoParserException In case of an error + */ + public static boolean getBooleanValue(final ObjectNode input, final String keyID, + final boolean isRequired, final boolean defaultValue) throws SlCommandoParserException { + try { + final JsonNode internal = getAndCheck(input, keyID, isRequired); + + if (internal != null) { + return internal.asBoolean(); + } else { + return defaultValue; + } + + } catch (final SlCommandoParserException e) { + throw e; + + } catch (final Exception e) { + throw new SlCommandoParserException("Can not extract Boolean value with keyId: " + keyID, e); + + } + } + + /** + * Extract JSONObject value from JSON. + * + * @param input JSON + * @param keyID Element identifier + * @param isRequired true, if the element must not null + * @return JSON node + * @throws SlCommandoParserException In case of an error + */ + public static JsonNode getJsonObjectValue(final JsonNode input, final String keyID, + final boolean isRequired) throws SlCommandoParserException { + try { + final JsonNode internal = getAndCheck(input, keyID, isRequired); + + if (internal != null) { + return internal; + } else { + return null; + } + + } catch (final SlCommandoParserException e) { + throw e; + + } catch (final Exception e) { + throw new SlCommandoParserException("Can not extract Boolean value with keyId: " + keyID, e); + + } + } + + /** + * Extract a List of String elements from a JSON element. + * + * @param input JSON + * @return List of Elements in this node + * @throws SlCommandoParserException In case of an error + */ + public static List getListOfStringElements(final JsonNode input) + throws SlCommandoParserException { + final List result = new ArrayList<>(); + if (input != null) { + if (input.isArray()) { + final Iterator arrayIterator = input.iterator(); + while (arrayIterator.hasNext()) { + final JsonNode next = arrayIterator.next(); + if (next.isTextual()) { + result.add(next.asText()); + } + } + + } else if (input.isTextual()) { + result.add(input.asText()); + + } else { + log.warn("JSON Element IS NOT a JSON array or a JSON Primitive"); + throw new SlCommandoParserException("JSON Element IS NOT a JSON array or a JSON Primitive"); + + } + } + + return result; + } + + /** + * Extract Map of Key/Value pairs from a JSON Element. + * + * @param input parent JSON object + * @param keyID KeyId of the child that should be parsed + * @param isRequired true, if the element must not null + * @return Map of element pairs + * @throws SlCommandoParserException In case of an error + */ + public static Map getMapOfStringElements(final JsonNode input, final String keyID, + final boolean isRequired) throws SlCommandoParserException { + final JsonNode internal = getAndCheck(input, keyID, isRequired); + return getMapOfStringElements(internal); + + } + + /** + * Extract Map of Key/Value pairs from a JSON Element. + * + * @param input JSON + * @return Map of element pairs + * @throws SlCommandoParserException in case of an error + */ + public static Map getMapOfStringElements(final JsonNode input) + throws SlCommandoParserException { + final Map result = new HashMap<>(); + + if (input != null) { + if (input.isArray()) { + final Iterator arrayIterator = input.iterator(); + while (arrayIterator.hasNext()) { + final JsonNode next = arrayIterator.next(); + final Iterator> entry = next.fields(); + entitySetToMap(result, entry); + + } + + } else if (input.isObject()) { + final Iterator> objectKeys = input.fields(); + entitySetToMap(result, objectKeys); + + } else { + throw new SlCommandoParserException("JSON Element IS NOT a JSON array or a JSON object"); + } + + } + + return result; + } + + private static void entitySetToMap(final Map result, + final Iterator> entry) { + while (entry.hasNext()) { + final Entry el = entry.next(); + if (result.containsKey(el.getKey())) { + log.info("Attr. Map already contains Element with Key: " + el.getKey() + + ". Overwrite element ... "); + } + + result.put(el.getKey(), el.getValue().asText()); + + } + + } + + + /** + * Extract Security-Layer 2.0 result from response object. + * + * @param command SL2.0 command + * @param decrypter JWS decrypter implementation + * @param mustBeEncrypted if true, the result must be encrypted + * @return decrypted JSON + * @throws SL20Exception In case of an error + */ + public static JsonNode extractSL20Result(final JsonNode command, final IJoseTools decrypter, + final boolean mustBeEncrypted) throws SL20Exception { + final JsonNode result = command.get(SL20Constants.SL20_COMMAND_CONTAINER_RESULT); + final JsonNode encryptedResult = + command.get(SL20Constants.SL20_COMMAND_CONTAINER_ENCRYPTEDRESULT); + + if (result == null && encryptedResult == null) { + throw new SlCommandoParserException("NO result OR encryptedResult FOUND."); + } else if (encryptedResult == null && mustBeEncrypted) { + throw new SlCommandoParserException("result MUST be encrypted."); + } else if (encryptedResult != null && encryptedResult.isTextual()) { + try { + return decrypter.decryptPayload(encryptedResult.asText()); + + } catch (final Exception e) { + log.info("Can NOT decrypt SL20 result. Reason:" + e.getMessage()); + if (!mustBeEncrypted) { + log.warn( + "Decrypted results are disabled by configuration. Parse result in plain if it is possible"); + + // dummy code + try { + final String[] signedPayload = encryptedResult.toString().split("\\."); + final JsonNode payLoad = mapper.getMapper() + .readTree(new String(Base64.getUrlDecoder().decode(signedPayload[1]))); + return payLoad; + + } catch (final Exception e1) { + log.debug("DummyCode FAILED, Reason: " + e1.getMessage() + " Ignore it ..."); + throw new SL20Exception(e.getMessage(), null, e); + + } + + } else { + throw e; + } + + } + + } else if (result != null) { + return result; + + } else { + throw new SlCommandoParserException("Internal build error"); + } + + + } + + /** + * Extract payLoad from generic transport container. + * + * @param container JSON + * @param joseTools JWS implementation + * @return Signature verification result that contains the payLoad + * @throws SlCommandoParserException In case of an error + */ + public static VerificationResult extractSL20PayLoad(final JsonNode container, + final IJoseTools joseTools, final boolean mustBeSigned) throws SL20Exception { + + final JsonNode sl20Payload = container.get(SL20Constants.SL20_PAYLOAD); + final JsonNode sl20SignedPayload = container.get(SL20Constants.SL20_SIGNEDPAYLOAD); + + if (mustBeSigned && joseTools == null) { + throw new SlCommandoParserException("'joseTools' MUST be set if 'mustBeSigned' is 'true'"); + } + + if (sl20Payload == null && sl20SignedPayload == null) { + throw new SlCommandoParserException("NO payLoad OR signedPayload FOUND."); + } else if (sl20SignedPayload == null && mustBeSigned) { + throw new SlCommandoParserException("payLoad MUST be signed."); + } else if (joseTools != null && sl20SignedPayload != null && sl20SignedPayload.isTextual()) { + return joseTools.validateSignature(sl20SignedPayload.asText()); + + } else if (sl20Payload != null) { + return new VerificationResult(sl20Payload); + } else { + throw new SlCommandoParserException("Internal build error"); + } + + + } + + + /** + * Extract generic transport container from httpResponse. + * + * @param httpResp Http response object + * @return JSON with SL2.0 response + * @throws SlCommandoParserException In case of an error + */ + public static JsonNode getSL20ContainerFromResponse(final HttpResponse httpResp) + throws SlCommandoParserException { + try { + JsonNode sl20Resp = null; + if (httpResp.getStatusLine().getStatusCode() == 303 + || httpResp.getStatusLine().getStatusCode() == 307) { + final Header[] locationHeader = httpResp.getHeaders("Location"); + if (locationHeader == null) { + throw new SlCommandoParserException("Find Redirect statuscode but not Location header"); + } + + final String sl20RespString = + new URIBuilder(locationHeader[0].getValue()).getQueryParams().get(0).getValue(); + sl20Resp = mapper.getMapper().readTree(Base64Url.decode(sl20RespString)); + + } else if (httpResp.getStatusLine().getStatusCode() == 200) { + if (httpResp.getEntity().getContentType() == null) { + throw new SlCommandoParserException("SL20 response contains NO ContentType"); + } + + if (!httpResp.getEntity().getContentType().getValue().startsWith("application/json")) { + throw new SlCommandoParserException("SL20 response with a wrong ContentType: " + + httpResp.getEntity().getContentType().getValue()); + } + sl20Resp = parseSL20ResultFromResponse(httpResp.getEntity()); + + } else if ((httpResp.getStatusLine().getStatusCode() == 500) + || (httpResp.getStatusLine().getStatusCode() == 401) + || (httpResp.getStatusLine().getStatusCode() == 400)) { + log.info("SL20 response with http-code: " + httpResp.getStatusLine().getStatusCode() + + ". Search for error message"); + + try { + sl20Resp = parseSL20ResultFromResponse(httpResp.getEntity()); + + } catch (final Exception e) { + log.warn("SL20 response contains no valid JSON", e); + throw new SlCommandoParserException("SL20 response with http-code: " + + httpResp.getStatusLine().getStatusCode() + " AND NO valid JSON errormsg", e); + + } + + + + } else { + throw new SlCommandoParserException( + "SL20 response with http-code: " + httpResp.getStatusLine().getStatusCode()); + } + + log.info("Find JSON object in http response"); + return sl20Resp; + + } catch (final Exception e) { + throw new SlCommandoParserException("SL20 response parsing FAILED! Reason: " + e.getMessage(), + e); + + } + } + + private static JsonNode parseSL20ResultFromResponse(final HttpEntity resp) throws Exception { + if (resp != null && resp.getContent() != null) { + final String rawSL20Resp = EntityUtils.toString(resp); + final JsonNode sl20Resp = mapper.getMapper().readTree(rawSL20Resp); + + // TODO: check sl20Resp type like && sl20Resp.isJsonObject() + if (sl20Resp != null) { + return sl20Resp; + + } else { + throw new SlCommandoParserException("SL2.0 can NOT parse to a JSON object"); + } + + + } else { + throw new SlCommandoParserException("Can NOT find content in http response"); + } + + } + + + private static JsonNode getAndCheck(final JsonNode input, final String keyID, + final boolean isRequired) throws SlCommandoParserException { + final JsonNode internal = input.get(keyID); + + if (internal == null && isRequired) { + throw new SlCommandoParserException( + "REQUIRED Element with keyId: " + keyID + " does not exist"); + } + + return internal; + + } +} diff --git a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/api/ISignatureVerificationService.java b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/api/ISignatureVerificationService.java index a3243635..155bfadd 100644 --- a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/api/ISignatureVerificationService.java +++ b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/api/ISignatureVerificationService.java @@ -1,84 +1,90 @@ package at.gv.egiz.eid.authhandler.modules.sigverify.moasig.api; import java.util.List; - import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.api.data.ICMSSignatureVerificationResponse; import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.api.data.IXMLSignatureVerificationResponse; -import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.exceptions.MOASigServiceException; +import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.exceptions.MoaSigServiceException; public interface ISignatureVerificationService { - /** - * Verify a CAdES or CMS signature - *

    - * This method only validates the first CMS or CAdES signature if more than one signature exists - * - * @param signature Enveloped CMS or CAdES signature - * @param trustProfileID Id of the Trust-Profile from MOA-Sig configuration - * @return @link {@link ICMSSignatureVerificationResponse}, or null if no signature was found - * @throws MOASigServiceException on signatue-verification error - */ - ICMSSignatureVerificationResponse verifyCMSSignature(byte[] signature, String trustProfileID) - throws MOASigServiceException; + /** + * Verify a CAdES or CMS signature.
    + *
    + * This method only validates the first CMS or CAdES signature if more than one signature + * exists + * + * @param signature Enveloped CMS or CAdES signature + * @param trustProfileID Id of the Trust-Profile from MOA-Sig configuration + * @return @link {@link ICMSSignatureVerificationResponse}, or null if no signature was found + * @throws MoaSigServiceException on signatue-verification error + */ + ICMSSignatureVerificationResponse verifyCmsSignature(byte[] signature, String trustProfileID) + throws MoaSigServiceException; - /** - * Verify a XML or XAdES signature - *

    - * This method only validates the first XML or XAdES signature if more than one signature exists - * - * @param signature Serialized XML or XAdES signature - * @param trustProfileID Id of the Trust-Profile from MOA-Sig configuration - * @return @link {@link IXMLSignatureVerificationResponse}, or null if no signature was found - * @throws MOASigServiceException on signatue-verification error - */ - IXMLSignatureVerificationResponse verifyXMLSignature(byte[] signature, String trustProfileID) - throws MOASigServiceException; + /** + * Verify a XML or XAdES signature.
    + *
    + * This method only validates the first XML or XAdES signature if more than one signature + * exists + * + * @param signature Serialized XML or XAdES signature + * @param trustProfileID Id of the Trust-Profile from MOA-Sig configuration + * @return @link {@link IXMLSignatureVerificationResponse}, or null if no signature was found + * @throws MoaSigServiceException on signatue-verification error + */ + IXMLSignatureVerificationResponse verifyXmlSignature(byte[] signature, String trustProfileID) + throws MoaSigServiceException; - /** - * Verify a XML or XAdES signature - *

    - * This method only validates the first XML or XAdES signature if more than one signature exists - * - * @param signature Serialized XML or XAdES signature - * @param trustProfileID Id of the Trust-Profile from MOA-Sig configuration - * @param verifyTransformsInfoProfileID {@link List} of XML Transformations that should be used for signature-verification - * @return @link {@link IXMLSignatureVerificationResponse}, or null if no signature was found - * @throws MOASigServiceException on signatue-verification error - */ - IXMLSignatureVerificationResponse verifyXMLSignature(byte[] signature, String trustProfileID, - List verifyTransformsInfoProfileID) throws MOASigServiceException; + /** + * Verify a XML or XAdES signature.
    + *
    + * This method only validates the first XML or XAdES signature if more than one signature + * exists + * + * @param signature Serialized XML or XAdES signature + * @param trustProfileID Id of the Trust-Profile from MOA-Sig configuration + * @param verifyTransformsInfoProfileID {@link List} of XML Transformations that should be used + * for signature-verification + * @return @link {@link IXMLSignatureVerificationResponse}, or null if no signature was found + * @throws MoaSigServiceException on signatue-verification error + */ + IXMLSignatureVerificationResponse verifyXmlSignature(byte[] signature, String trustProfileID, + List verifyTransformsInfoProfileID) throws MoaSigServiceException; - /** - * Verify a XML or XAdES signature - *

    - * This method only validates the first XML or XAdES signature if more than one signature exists - * - * @param signature Serialized XML or XAdES signature - * @param trustProfileID Id of the Trust-Profile from MOA-Sig configuration - * @param signatureLocationXpath Xpath that points to location of Signature element - * @return @link {@link IXMLSignatureVerificationResponse}, or null if no signature was found - * @throws MOASigServiceException on signatue-verification error - */ - IXMLSignatureVerificationResponse verifyXMLSignature(byte[] signature, String trustProfileID, - String signatureLocationXpath) throws MOASigServiceException; + /** + * Verify a XML or XAdES signature.
    + *
    + * This method only validates the first XML or XAdES signature if more than one signature + * exists + * + * @param signature Serialized XML or XAdES signature + * @param trustProfileID Id of the Trust-Profile from MOA-Sig configuration + * @param signatureLocationXpath Xpath that points to location of Signature element + * @return @link {@link IXMLSignatureVerificationResponse}, or null if no signature was found + * @throws MoaSigServiceException on signatue-verification error + */ + IXMLSignatureVerificationResponse verifyXmlSignature(byte[] signature, String trustProfileID, + String signatureLocationXpath) throws MoaSigServiceException; - /** - * Verify a XML or XAdES signature - *

    - * This method only validates the first XML or XAdES signature if more than one signature exists - * - * @param signature Serialized XML or XAdES signature - * @param trustProfileID Id of the Trust-Profile from MOA-Sig configuration - * @param verifyTransformsInfoProfileID {@link List} of XML Transformations that should be used for signature-verification - * @param signatureLocationXpath Xpath that points to location of Signature element - * @return @link {@link IXMLSignatureVerificationResponse}, or null if no signature was found - * @throws MOASigServiceException on signatue-verification error - */ - IXMLSignatureVerificationResponse verifyXMLSignature(byte[] signature, String trustProfileID, - List verifyTransformsInfoProfileID, - String signatureLocationXpath) throws MOASigServiceException; + /** + * Verify a XML or XAdES signature.
    + *
    + * This method only validates the first XML or XAdES signature if more than one signature + * exists + * + * @param signature Serialized XML or XAdES signature + * @param trustProfileID Id of the Trust-Profile from MOA-Sig configuration + * @param verifyTransformsInfoProfileID {@link List} of XML Transformations that should be used + * for signature-verification + * @param signatureLocationXpath Xpath that points to location of Signature element + * @return @link {@link IXMLSignatureVerificationResponse}, or null if no signature was found + * @throws MoaSigServiceException on signatue-verification error + */ + IXMLSignatureVerificationResponse verifyXmlSignature(byte[] signature, String trustProfileID, + List verifyTransformsInfoProfileID, String signatureLocationXpath) + throws MoaSigServiceException; -} \ No newline at end of file +} diff --git a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/api/data/IGenericSignatureVerificationResponse.java b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/api/data/IGenericSignatureVerificationResponse.java index 00d98c86..13a9b08f 100644 --- a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/api/data/IGenericSignatureVerificationResponse.java +++ b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/api/data/IGenericSignatureVerificationResponse.java @@ -5,65 +5,71 @@ import java.util.Date; import org.springframework.lang.Nullable; -import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.exceptions.MOASigServiceException; +import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.exceptions.MoaSigServiceException; public interface IGenericSignatureVerificationResponse { - /** - * Returns the signing time - * - * @return Signing time, or null if signature contains no time information - */ - @Nullable - Date getSigningDateTime(); - - /** - * Returns the signatureCheckCode. - * @return int - */ - int getSignatureCheckCode(); - - /** - * Returns the certificateCheckCode. - * @return int - */ - int getCertificateCheckCode(); + /** + * Returns the signing time + * + * @return Signing time, or null if signature contains no time information + */ + @Nullable + Date getSigningDateTime(); - /** - * Returns the qualifiedCertificate. - * @return boolean - */ - boolean isQualifiedCertificate(); + /** + * Returns the signatureCheckCode. + * + * @return int + */ + int getSignatureCheckCode(); - /** - * Returns the X509 certificate. - * @return X509Certificate, or null if no certificate information exists - * @throws MOASigServiceException if X509 certificate can not be deserialized - */ - @Nullable - X509Certificate getX509Certificate() throws MOASigServiceException; + /** + * Returns the certificateCheckCode. + * + * @return int + */ + int getCertificateCheckCode(); - - /** - * Returns the X509 certificate in serialized form - * - * @return Serialized X509 certificate, or null if no certificate information exists - */ - @Nullable - byte[] getX509CertificateEncoded(); - - /** - * Returns the publicAuthority. - * @return boolean - */ - boolean isPublicAuthority(); - - /** - * Returns the publicAuthorityCode. - * @return String OID, or null if no OID exists - */ - @Nullable - String getPublicAuthorityCode(); + /** + * Returns the qualifiedCertificate. + * + * @return boolean + */ + boolean isQualifiedCertificate(); + + /** + * Returns the X509 certificate. + * + * @return X509Certificate, or null if no certificate information exists + * @throws MoaSigServiceException if X509 certificate can not be deserialized + */ + @Nullable + X509Certificate getX509Certificate() throws MoaSigServiceException; + + + /** + * Returns the X509 certificate in serialized form + * + * @return Serialized X509 certificate, or null if no certificate information exists + */ + @Nullable + byte[] getX509CertificateEncoded(); + + /** + * Returns the publicAuthority. + * + * @return boolean + */ + boolean isPublicAuthority(); + + /** + * Returns the publicAuthorityCode. + * + * @return String OID, or null if no OID exists + */ + @Nullable + String getPublicAuthorityCode(); } diff --git a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/api/data/ISchemaRessourceProvider.java b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/api/data/ISchemaRessourceProvider.java index 9548d96b..9bd5791f 100644 --- a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/api/data/ISchemaRessourceProvider.java +++ b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/api/data/ISchemaRessourceProvider.java @@ -5,16 +5,17 @@ import java.util.Map; /** * Inject additional XML schemes into MOA-Sig - * + * * @author tlenz * */ public interface ISchemaRessourceProvider { - /** - * Get a Map of additional XML schemes that should be injected into MOA-Sig - * - * @return A Set of {@link Entry} consist of Name of the Scheme and XML scheme as {@link InputStream} - */ - public Map getSchemas(); + /** + * Get a Map of additional XML schemes that should be injected into MOA-Sig + * + * @return A Set of {@link Entry} consist of Name of the Scheme and XML scheme as + * {@link InputStream} + */ + public Map getSchemas(); } diff --git a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/api/data/IXMLSignatureVerificationResponse.java b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/api/data/IXMLSignatureVerificationResponse.java index 3e86fb63..6273bb9e 100644 --- a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/api/data/IXMLSignatureVerificationResponse.java +++ b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/api/data/IXMLSignatureVerificationResponse.java @@ -7,31 +7,34 @@ package at.gv.egiz.eid.authhandler.modules.sigverify.moasig.api.data; public interface IXMLSignatureVerificationResponse extends IGenericSignatureVerificationResponse { - /** - * Returns the xmlDSIGManifestCheckCode. - * @return int - */ - int getXmlDSIGManifestCheckCode(); - - /** - * Returns the xmlDsigSubjectName. - * @return String - */ - String getXmlDsigSubjectName(); - - - /** - * Returns the xmlDSIGManigest. - * @return boolean - */ - boolean isXmlDSIGManigest(); - - - /** - * Returns the the resulting code of the signature manifest check. - * - * @return The code of the sigature manifest check. - */ - int getSignatureManifestCheckCode(); - -} \ No newline at end of file + /** + * Returns the xmlDSIGManifestCheckCode. + * + * @return int + */ + int getXmlDSIGManifestCheckCode(); + + /** + * Returns the xmlDsigSubjectName. + * + * @return String + */ + String getXmlDsigSubjectName(); + + + /** + * Returns the xmlDSIGManigest. + * + * @return boolean + */ + boolean isXmlDSIGManigest(); + + + /** + * Returns the the resulting code of the signature manifest check. + * + * @return The code of the sigature manifest check. + */ + int getSignatureManifestCheckCode(); + +} diff --git a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MOASigServiceBuilderException.java b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MOASigServiceBuilderException.java deleted file mode 100644 index ded3f900..00000000 --- a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MOASigServiceBuilderException.java +++ /dev/null @@ -1,14 +0,0 @@ -package at.gv.egiz.eid.authhandler.modules.sigverify.moasig.exceptions; - -public class MOASigServiceBuilderException extends MOASigServiceException { - - private static final long serialVersionUID = 5178393157255309476L; - - public MOASigServiceBuilderException(String errorId, Object[] params) { - super(errorId, params); - } - - public MOASigServiceBuilderException(String errorId, Object[] params, Throwable e) { - super(errorId, params, e); - } -} diff --git a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MOASigServiceConfigurationException.java b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MOASigServiceConfigurationException.java deleted file mode 100644 index f3c02fe1..00000000 --- a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MOASigServiceConfigurationException.java +++ /dev/null @@ -1,11 +0,0 @@ -package at.gv.egiz.eid.authhandler.modules.sigverify.moasig.exceptions; - -public class MOASigServiceConfigurationException extends MOASigServiceException { - - private static final long serialVersionUID = -4710795384615456488L; - - public MOASigServiceConfigurationException(String errorId, Object[] params, Throwable e) { - super(errorId, params, e); - } - -} diff --git a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MOASigServiceException.java b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MOASigServiceException.java deleted file mode 100644 index 243b4b1d..00000000 --- a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MOASigServiceException.java +++ /dev/null @@ -1,26 +0,0 @@ -package at.gv.egiz.eid.authhandler.modules.sigverify.moasig.exceptions; - -import at.gv.egiz.eaaf.core.exceptions.EAAFServiceException; - -public class MOASigServiceException extends EAAFServiceException { - - private static final long serialVersionUID = -6088238428550563658L; - private static final String MOA_SIG_SERVICE_ID = "MOA-SIG-VERIFY"; - - public MOASigServiceException(String errorId, Object[] params) { - super(errorId, params); - - } - - public MOASigServiceException(String errorId, Object[] params, Throwable e) { - super(errorId, params, e); - - } - - @Override - protected String getServiceIdentifier() { - return MOA_SIG_SERVICE_ID; - - } - -} diff --git a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MOASigServiceParserException.java b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MOASigServiceParserException.java deleted file mode 100644 index 63a51001..00000000 --- a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MOASigServiceParserException.java +++ /dev/null @@ -1,14 +0,0 @@ -package at.gv.egiz.eid.authhandler.modules.sigverify.moasig.exceptions; - -public class MOASigServiceParserException extends MOASigServiceException { - - private static final long serialVersionUID = 5178393157255309476L; - - public MOASigServiceParserException(String errorId, Object[] params) { - super(errorId, params); - } - - public MOASigServiceParserException(String errorId, Object[] params, Throwable e) { - super(errorId, params, e); - } -} diff --git a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MoaSigServiceBuilderException.java b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MoaSigServiceBuilderException.java new file mode 100644 index 00000000..e32ab932 --- /dev/null +++ b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MoaSigServiceBuilderException.java @@ -0,0 +1,14 @@ +package at.gv.egiz.eid.authhandler.modules.sigverify.moasig.exceptions; + +public class MoaSigServiceBuilderException extends MoaSigServiceException { + + private static final long serialVersionUID = 5178393157255309476L; + + public MoaSigServiceBuilderException(final String errorId, final Object[] params) { + super(errorId, params); + } + + public MoaSigServiceBuilderException(final String errorId, final Object[] params, final Throwable e) { + super(errorId, params, e); + } +} diff --git a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MoaSigServiceConfigurationException.java b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MoaSigServiceConfigurationException.java new file mode 100644 index 00000000..fd5f8caf --- /dev/null +++ b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MoaSigServiceConfigurationException.java @@ -0,0 +1,11 @@ +package at.gv.egiz.eid.authhandler.modules.sigverify.moasig.exceptions; + +public class MoaSigServiceConfigurationException extends MoaSigServiceException { + + private static final long serialVersionUID = -4710795384615456488L; + + public MoaSigServiceConfigurationException(final String errorId, final Object[] params, final Throwable e) { + super(errorId, params, e); + } + +} diff --git a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MoaSigServiceException.java b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MoaSigServiceException.java new file mode 100644 index 00000000..a4fb6290 --- /dev/null +++ b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MoaSigServiceException.java @@ -0,0 +1,26 @@ +package at.gv.egiz.eid.authhandler.modules.sigverify.moasig.exceptions; + +import at.gv.egiz.eaaf.core.exceptions.EaafServiceException; + +public class MoaSigServiceException extends EaafServiceException { + + private static final long serialVersionUID = -6088238428550563658L; + private static final String MOA_SIG_SERVICE_ID = "MOA-SIG-VERIFY"; + + public MoaSigServiceException(final String errorId, final Object[] params) { + super(errorId, params); + + } + + public MoaSigServiceException(final String errorId, final Object[] params, final Throwable e) { + super(errorId, params, e); + + } + + @Override + protected String getServiceIdentifier() { + return MOA_SIG_SERVICE_ID; + + } + +} diff --git a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MoaSigServiceParserException.java b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MoaSigServiceParserException.java new file mode 100644 index 00000000..a47b45e0 --- /dev/null +++ b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/exceptions/MoaSigServiceParserException.java @@ -0,0 +1,14 @@ +package at.gv.egiz.eid.authhandler.modules.sigverify.moasig.exceptions; + +public class MoaSigServiceParserException extends MoaSigServiceException { + + private static final long serialVersionUID = 5178393157255309476L; + + public MoaSigServiceParserException(final String errorId, final Object[] params) { + super(errorId, params); + } + + public MoaSigServiceParserException(final String errorId, final Object[] params, final Throwable e) { + super(errorId, params, e); + } +} diff --git a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/AbstractSignatureService.java b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/AbstractSignatureService.java index 7e65cec7..cbf80c39 100644 --- a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/AbstractSignatureService.java +++ b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/AbstractSignatureService.java @@ -6,72 +6,71 @@ import javax.xml.parsers.ParserConfigurationException; import at.gv.egovernment.moa.spss.server.config.ConfigurationException; import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; import at.gv.egovernment.moa.spss.server.iaik.config.IaikConfigurator; -import at.gv.egovernment.moa.spss.server.logging.TransactionId; import at.gv.egovernment.moa.spss.server.transaction.TransactionContext; import at.gv.egovernment.moa.spss.server.transaction.TransactionContextManager; import at.gv.egovernment.moaspss.logging.LoggingContext; import at.gv.egovernment.moaspss.logging.LoggingContextManager; -import iaik.server.Configurator; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.w3c.dom.Document; public abstract class AbstractSignatureService { - private static final Logger log = LoggerFactory.getLogger(AbstractSignatureService.class); + private static final Logger log = LoggerFactory.getLogger(AbstractSignatureService.class); + + @Autowired(required = true) + MoaSigInitializer moaSigConfig; + + /** + * Get a new {@link Document} from {@link DocumentBuilder} in synchronized form, because + * {@link DocumentBuilderFactory} and {@link DocumentBuilder} are not thread-safe. + * + * @return {@link Document} + * @throws ParserConfigurationException In case of an error + */ + protected synchronized Document getNewDocumentBuilder() throws ParserConfigurationException { + final DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + return docBuilder.newDocument(); - @Autowired(required = true) MoaSigInitializer moaSigConfig; - - /** - * Get a new {@link Document} from {@link DocumentBuilder} in synchronized form, because - * {@link DocumentBuilderFactory} and {@link DocumentBuilder} are not thread-safe. - * - * @return {@link Document} - * @throws ParserConfigurationException - */ - protected synchronized Document getNewDocumentBuilder() throws ParserConfigurationException { - final DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - return docBuilder.newDocument(); + } - } + /** + * Set up the thread-local context information needed for calling the various Invoker + * classes. + * + * @throws ConfigurationException An error occurred setting up the configuration in the + * TransactionContext. + */ + protected final void setUpContexts(final String transactionID) throws ConfigurationException { + final TransactionContextManager txMgr = TransactionContextManager.getInstance(); + final LoggingContextManager logMgr = LoggingContextManager.getInstance(); - /** - * Set up the thread-local context information needed for calling the various - * Invoker classes. - * - * @throws ConfigurationException An error occurred setting up the - * configuration in the TransactionContext. - */ - protected final void setUpContexts( String transactionID) throws ConfigurationException { - final TransactionContextManager txMgr = TransactionContextManager.getInstance(); - final LoggingContextManager logMgr = LoggingContextManager.getInstance(); + if (txMgr.getTransactionContext() == null) { + log.debug("Set not MOA-Sig transaction context"); + final TransactionContext ctx = + new TransactionContext(transactionID, null, ConfigurationProvider.getInstance()); + txMgr.setTransactionContext(ctx); - if (txMgr.getTransactionContext() == null) { - log.debug("Set not MOA-Sig transaction context"); - final TransactionContext ctx = new TransactionContext(transactionID, null, ConfigurationProvider.getInstance()); - txMgr.setTransactionContext(ctx); + } - } + if (logMgr.getLoggingContext() == null) { + final LoggingContext ctx = new LoggingContext(transactionID); + logMgr.setLoggingContext(ctx); - if (logMgr.getLoggingContext() == null) { - final LoggingContext ctx = new LoggingContext(transactionID); - logMgr.setLoggingContext(ctx); + } - } - - new IaikConfigurator().configure(ConfigurationProvider.getInstance()); + new IaikConfigurator().configure(ConfigurationProvider.getInstance()); - } + } - /** - * Tear down thread-local context information. - */ - protected void tearDownContexts() { - TransactionContextManager.getInstance().setTransactionContext(null); - LoggingContextManager.getInstance().setLoggingContext(null); - log.debug("Closing MOA-Sig transaction context"); + /** + * Tear down thread-local context information. + */ + protected void tearDownContexts() { + TransactionContextManager.getInstance().setTransactionContext(null); + LoggingContextManager.getInstance().setLoggingContext(null); + log.debug("Closing MOA-Sig transaction context"); - } + } } diff --git a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/MOASigSpringResourceProvider.java b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/MOASigSpringResourceProvider.java deleted file mode 100644 index ecda7eb1..00000000 --- a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/MOASigSpringResourceProvider.java +++ /dev/null @@ -1,27 +0,0 @@ -package at.gv.egiz.eid.authhandler.modules.sigverify.moasig.impl; - -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; - -import at.gv.egiz.components.spring.api.SpringResourceProvider; - -public class MOASigSpringResourceProvider implements SpringResourceProvider { - - @Override - public Resource[] getResourcesToLoad() { - ClassPathResource moaSigConfig = new ClassPathResource("/moa-sig-service.beans.xml", MOASigSpringResourceProvider.class); - return new Resource[] {moaSigConfig}; - } - - @Override - public String[] getPackagesToScan() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getName() { - return "Signature-verification service based on MOA-Sig (MOA-SPSS)"; - } - -} diff --git a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/MoaSigInitializer.java b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/MoaSigInitializer.java index 1628b71a..f0ee4612 100644 --- a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/MoaSigInitializer.java +++ b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/MoaSigInitializer.java @@ -6,11 +6,10 @@ import java.security.Provider; import java.security.Security; import java.util.Iterator; import java.util.Map.Entry; - import javax.annotation.Nonnull; import javax.annotation.PostConstruct; import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.api.data.ISchemaRessourceProvider; -import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.exceptions.MOASigServiceConfigurationException; +import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.exceptions.MoaSigServiceConfigurationException; import at.gv.egovernment.moa.spss.MOAException; import at.gv.egovernment.moa.spss.api.Configurator; import at.gv.egovernment.moaspss.logging.LoggingContext; @@ -24,103 +23,108 @@ import iaik.security.ec.provider.ECCelerate; import iaik.security.provider.IAIK; public class MoaSigInitializer { - private static final Logger log = LoggerFactory.getLogger(MoaSigInitializer.class); - - @Autowired(required=false) ISchemaRessourceProvider[] schemas; - - private Configurator moaSigConfigurator; - - - /** - * Get MOA-Sig configuration object - * - * @return moa-sig configuration - */ - @Nonnull - public Configurator getMoaSigConfigurator() { - return moaSigConfigurator; - - } - - @PostConstruct - private synchronized void initialize() throws MOASigServiceConfigurationException { - log.info("Initializing MOA-Sig signature-verification service ... "); - - log.info("Loading Java security providers."); - IAIK.addAsProvider(); - ECCelerate.addAsProvider(); - - try { - LoggingContextManager.getInstance().setLoggingContext( - new LoggingContext("startup")); - log.debug("MOA-Sig library initialization process ... "); - Configurator.getInstance().init(); - log.info("MOA-Sig library initialization complete "); - - Security.insertProviderAt(IAIK.getInstance(), 0); - - final ECCelerate eccProvider = ECCelerate.getInstance(); - if (Security.getProvider(eccProvider.getName()) != null) - Security.removeProvider(eccProvider.getName()); - Security.addProvider(new ECCelerate()); - - fixJava8_141ProblemWithSSLAlgorithms(); - - if (log.isDebugEnabled()) { - log.debug("Loaded Security Provider:"); - final Provider[] providerList = Security.getProviders(); - for (int i=0; i 0) { - log.debug("Infjecting additional XML schemes ... "); - for (final ISchemaRessourceProvider el : schemas) { - final Iterator> xmlSchemeIt = el.getSchemas().entrySet().iterator(); - while (xmlSchemeIt.hasNext()) { - final Entry xmlDef = xmlSchemeIt.next(); - try { - DOMUtils.addSchemaToPool(xmlDef.getValue(), xmlDef.getKey()); - log.info("Inject XML scheme: {}", xmlDef.getKey()); + fixJava8_141ProblemWithSslAlgorithms(); - } catch (final IOException e) { - log.warn("Can NOT inject XML scheme: " + xmlDef.getKey(), e); + if (log.isDebugEnabled()) { + log.debug("Loaded Security Provider:"); + final Provider[] providerList = Security.getProviders(); + for (int i = 0; i < providerList.length; i++) { + log.debug( + i + ": " + providerList[i].getName() + " Version " + providerList[i].getVersion()); + } - } + } + + + // Inject additional XML schemes + if (schemas != null && schemas.length > 0) { + log.debug("Infjecting additional XML schemes ... "); + for (final ISchemaRessourceProvider el : schemas) { + final Iterator> xmlSchemeIt = + el.getSchemas().entrySet().iterator(); + while (xmlSchemeIt.hasNext()) { + final Entry xmlDef = xmlSchemeIt.next(); + try { + DOMUtils.addSchemaToPool(xmlDef.getValue(), xmlDef.getKey()); + log.info("Inject XML scheme: {}", xmlDef.getKey()); + + } catch (final IOException e) { + log.warn("Can NOT inject XML scheme: " + xmlDef.getKey(), e); - } - } } - - moaSigConfigurator = Configurator.getInstance(); - - - } catch (final MOAException e) { - log.error("MOA-SP initialization FAILED!", e.getWrapped()); - throw new MOASigServiceConfigurationException("service.moasig.04", new Object[] { e - .toString() }, e); - } - - - } - - private static void fixJava8_141ProblemWithSSLAlgorithms() { - log.info("Change AlgorithmIDs to fix problems with Java8 >= 141 ..."); - //new AlgorithmID("1.2.840.113549.1.1.4", "md5WithRSAEncryption", new String[] { "MD5withRSA", "MD5/RSA", }, null, true); - new AlgorithmID("1.2.840.113549.1.1.5", "sha1WithRSAEncryption", - new String[] { "SHA1withRSA" , "SHA1/RSA", "SHA-1/RSA", "SHA/RSA", }, null, true); - new AlgorithmID("1.2.840.113549.1.1.14", "sha224WithRSAEncryption", - new String[] { "SHA224withRSA", "SHA224/RSA", "SHA-224/RSA", }, null, true); - new AlgorithmID("1.2.840.113549.1.1.11", "sha256WithRSAEncryption", - new String[] { "SHA256withRSA", "SHA256/RSA", "SHA-256/RSA", }, null, true); - new AlgorithmID("1.2.840.113549.1.1.12", "sha384WithRSAEncryption", - new String[] { "SHA384withRSA", "SHA384/RSA", "SHA-384/RSA", }, null, true); - new AlgorithmID("1.2.840.113549.1.1.13", "sha512WithRSAEncryption", - new String[] { "SHA512withRSA", "SHA512/RSA", "SHA-512/RSA" }, null, true); - - log.info("Change AlgorithmIDs finished"); + + } + } + } + + moaSigConfigurator = Configurator.getInstance(); + + + } catch (final MOAException e) { + log.error("MOA-SP initialization FAILED!", e.getWrapped()); + throw new MoaSigServiceConfigurationException("service.moasig.04", + new Object[] {e.toString()}, e); } + + + } + + private static void fixJava8_141ProblemWithSslAlgorithms() { + log.info("Change AlgorithmIDs to fix problems with Java8 >= 141 ..."); + // new AlgorithmID("1.2.840.113549.1.1.4", "md5WithRSAEncryption", new String[] { "MD5withRSA", + // "MD5/RSA", }, null, true); + new AlgorithmID("1.2.840.113549.1.1.5", "sha1WithRSAEncryption", + new String[] {"SHA1withRSA", "SHA1/RSA", "SHA-1/RSA", "SHA/RSA",}, null, true); + new AlgorithmID("1.2.840.113549.1.1.14", "sha224WithRSAEncryption", + new String[] {"SHA224withRSA", "SHA224/RSA", "SHA-224/RSA",}, null, true); + new AlgorithmID("1.2.840.113549.1.1.11", "sha256WithRSAEncryption", + new String[] {"SHA256withRSA", "SHA256/RSA", "SHA-256/RSA",}, null, true); + new AlgorithmID("1.2.840.113549.1.1.12", "sha384WithRSAEncryption", + new String[] {"SHA384withRSA", "SHA384/RSA", "SHA-384/RSA",}, null, true); + new AlgorithmID("1.2.840.113549.1.1.13", "sha512WithRSAEncryption", + new String[] {"SHA512withRSA", "SHA512/RSA", "SHA-512/RSA"}, null, true); + + log.info("Change AlgorithmIDs finished"); + } } diff --git a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/MoaSigSpringResourceProvider.java b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/MoaSigSpringResourceProvider.java new file mode 100644 index 00000000..c8275264 --- /dev/null +++ b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/MoaSigSpringResourceProvider.java @@ -0,0 +1,28 @@ +package at.gv.egiz.eid.authhandler.modules.sigverify.moasig.impl; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; + +import at.gv.egiz.components.spring.api.SpringResourceProvider; + +public class MoaSigSpringResourceProvider implements SpringResourceProvider { + + @Override + public Resource[] getResourcesToLoad() { + final ClassPathResource moaSigConfig = + new ClassPathResource("/moa-sig-service.beans.xml", MoaSigSpringResourceProvider.class); + return new Resource[] {moaSigConfig}; + } + + @Override + public String[] getPackagesToScan() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getName() { + return "Signature-verification service based on MOA-Sig (MOA-SPSS)"; + } + +} diff --git a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/SignatureCreationService.java b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/SignatureCreationService.java index 59e7b516..5cb001ef 100644 --- a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/SignatureCreationService.java +++ b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/SignatureCreationService.java @@ -10,21 +10,22 @@ import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.api.ISignatureCreatio import at.gv.egovernment.moa.spss.server.invoke.CMSSignatureCreationInvoker; import at.gv.egovernment.moa.spss.server.invoke.XMLSignatureCreationInvoker; -@Service(value="moaSigCreateService") -public class SignatureCreationService extends AbstractSignatureService implements ISignatureCreationService{ - private static final Logger log = LoggerFactory.getLogger(SignatureCreationService.class); - - private XMLSignatureCreationInvoker xadesInvoker; - private CMSSignatureCreationInvoker cadesInvoker; - - - @PostConstruct - protected void internalInitializer() { - log.debug("Instanzing SignatureCreationService implementation ... "); - xadesInvoker = XMLSignatureCreationInvoker.getInstance(); - cadesInvoker = CMSSignatureCreationInvoker.getInstance(); - log.info("MOA-Sig signature-creation service initialized"); - - } +@Service(value = "moaSigCreateService") +public class SignatureCreationService extends AbstractSignatureService + implements ISignatureCreationService { + private static final Logger log = LoggerFactory.getLogger(SignatureCreationService.class); + + private XMLSignatureCreationInvoker xadesInvoker; + private CMSSignatureCreationInvoker cadesInvoker; + + + @PostConstruct + protected void internalInitializer() { + log.debug("Instanzing SignatureCreationService implementation ... "); + xadesInvoker = XMLSignatureCreationInvoker.getInstance(); + cadesInvoker = CMSSignatureCreationInvoker.getInstance(); + log.info("MOA-Sig signature-creation service initialized"); + + } } diff --git a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/SignatureVerificationService.java b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/SignatureVerificationService.java index f610e59e..3dbda391 100644 --- a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/SignatureVerificationService.java +++ b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/SignatureVerificationService.java @@ -7,9 +7,9 @@ import javax.annotation.PostConstruct; import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.api.ISignatureVerificationService; import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.api.data.ICMSSignatureVerificationResponse; import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.api.data.IXMLSignatureVerificationResponse; -import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.exceptions.MOASigServiceBuilderException; -import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.exceptions.MOASigServiceException; -import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.impl.parser.VerifyXMLSignatureResponseParser; +import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.exceptions.MoaSigServiceBuilderException; +import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.exceptions.MoaSigServiceException; +import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.impl.parser.VerifyXmlSignatureResponseParser; import at.gv.egovernment.moa.spss.MOAException; import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureRequest; import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureResponse; @@ -33,270 +33,321 @@ import org.w3c.dom.Node; /** + * MOA-Sig based signature verification implementation. + * * @author tlenz * */ -@Service(value="moaSigVerifyService") -public class SignatureVerificationService extends AbstractSignatureService implements ISignatureVerificationService { - private static final Logger log = LoggerFactory.getLogger(SignatureVerificationService.class); - - private static final String XMLNS_NS_URI = Constants.XMLNS_NS_URI; - private static final String MOA_NS_URI = Constants.MOA_NS_URI; - private static final String DSIG = Constants.DSIG_PREFIX + ":"; - private static final String DEFAULT_XPATH_SIGNATURE_LOCATION = "//" + DSIG + "Signature"; - - private CMSSignatureVerificationInvoker cadesInvoker; - private XMLSignatureVerificationInvoker xadesInvocer; - - /* (non-Javadoc) - * @see at.gv.egiz.eid.authhandler.modules.sigverify.moasig.impl.ISignatureVerificationService#verifyCMSSignature(byte[], java.lang.String) - */ - @Override - @Nullable - public ICMSSignatureVerificationResponse verifyCMSSignature(byte[] signature, String trustProfileID) throws MOASigServiceException { - try { - //setup context - setUpContexts(Thread.currentThread().getName()); - - //verify signature - final VerifyCMSSignatureRequest cmsSigVerifyReq = buildVerfifyCMSRequest(signature, trustProfileID, false, false); - final VerifyCMSSignatureResponse cmsSigVerifyResp = cadesInvoker.verifyCMSSignature(cmsSigVerifyReq ); - return parseCMSVerificationResult(cmsSigVerifyResp); - - } catch (final MOAException e) { - log.warn("CMS signature verification has an error.", e); - throw new MOASigServiceException("service.03", new Object[] { e.toString()}, e); - - } catch (final CertificateEncodingException e) { - log.warn("Can NOT serialize X509 certificate from CMS/CAdES signature-verification response", e); - throw new MOASigServiceException("service.03", new Object[] { e.toString()}, e); - - } finally { - tearDownContexts(); +@Service(value = "moaSigVerifyService") +public class SignatureVerificationService extends AbstractSignatureService + implements ISignatureVerificationService { + private static final Logger log = LoggerFactory.getLogger(SignatureVerificationService.class); + + private static final String XMLNS_NS_URI = Constants.XMLNS_NS_URI; + private static final String MOA_NS_URI = Constants.MOA_NS_URI; + private static final String DSIG = Constants.DSIG_PREFIX + ":"; + private static final String DEFAULT_XPATH_SIGNATURE_LOCATION = "//" + DSIG + "Signature"; + + private CMSSignatureVerificationInvoker cadesInvoker; + private XMLSignatureVerificationInvoker xadesInvocer; + + /* + * (non-Javadoc) + * + * @see at.gv.egiz.eid.authhandler.modules.sigverify.moasig.impl.ISignatureVerificationService# + * verifyCMSSignature(byte[], java.lang.String) + */ + @Override + @Nullable + public ICMSSignatureVerificationResponse verifyCmsSignature(final byte[] signature, + final String trustProfileID) throws MoaSigServiceException { + try { + // setup context + setUpContexts(Thread.currentThread().getName()); + + // verify signature + final VerifyCMSSignatureRequest cmsSigVerifyReq = + buildVerfifyCmsRequest(signature, trustProfileID, false, false); + final VerifyCMSSignatureResponse cmsSigVerifyResp = + cadesInvoker.verifyCMSSignature(cmsSigVerifyReq); + return parseCmsVerificationResult(cmsSigVerifyResp); + + } catch (final MOAException e) { + log.warn("CMS signature verification has an error.", e); + throw new MoaSigServiceException("service.03", new Object[] {e.toString()}, e); + + } catch (final CertificateEncodingException e) { + log.warn("Can NOT serialize X509 certificate from CMS/CAdES signature-verification response", + e); + throw new MoaSigServiceException("service.03", new Object[] {e.toString()}, e); + + } finally { + tearDownContexts(); + + } + + } + + /* + * (non-Javadoc) + * + * @see at.gv.egiz.eid.authhandler.modules.sigverify.moasig.impl.ISignatureVerificationService# + * verifyXMLSignature(byte[], java.lang.String) + */ + @Override + public IXMLSignatureVerificationResponse verifyXmlSignature(final byte[] signature, + final String trustProfileID) throws MoaSigServiceException { + return verifyXmlSignature(signature, trustProfileID, null, DEFAULT_XPATH_SIGNATURE_LOCATION); + + } + + /* + * (non-Javadoc) + * + * @see at.gv.egiz.eid.authhandler.modules.sigverify.moasig.impl.ISignatureVerificationService# + * verifyXMLSignature(byte[], java.lang.String, java.util.List) + */ + @Override + public IXMLSignatureVerificationResponse verifyXmlSignature(final byte[] signature, + final String trustProfileID, final List verifyTransformsInfoProfileID) + throws MoaSigServiceException { + return verifyXmlSignature(signature, trustProfileID, verifyTransformsInfoProfileID, + DEFAULT_XPATH_SIGNATURE_LOCATION); + } + + /* + * (non-Javadoc) + * + * @see at.gv.egiz.eid.authhandler.modules.sigverify.moasig.impl.ISignatureVerificationService# + * verifyXMLSignature(byte[], java.lang.String, java.lang.String) + */ + @Override + public IXMLSignatureVerificationResponse verifyXmlSignature(final byte[] signature, + final String trustProfileID, final String signatureLocationXpath) + throws MoaSigServiceException { + return verifyXmlSignature(signature, trustProfileID, null, signatureLocationXpath); + } + + /* + * (non-Javadoc) + * + * @see at.gv.egiz.eid.authhandler.modules.sigverify.moasig.impl.ISignatureVerificationService# + * verifyXMLSignature(byte[], java.lang.String, java.util.List, java.lang.String) + */ + @Override + public IXMLSignatureVerificationResponse verifyXmlSignature(final byte[] signature, + final String trustProfileID, final List verifyTransformsInfoProfileID, + final String xpathSignatureLocation) throws MoaSigServiceException { + try { + // setup context + setUpContexts(Thread.currentThread().getName()); + + // build signature-verification request + final Element domVerifyXmlSignatureRequest = buildVerifyXmlRequest(signature, trustProfileID, + verifyTransformsInfoProfileID, xpathSignatureLocation); + + // send signature-verification to MOA-Sig + final VerifyXMLSignatureRequest vsrequest = + new VerifyXMLSignatureRequestParser().parse(domVerifyXmlSignatureRequest); + final VerifyXMLSignatureResponse vsresponse = xadesInvocer.verifyXMLSignature(vsrequest); + final Document result = new VerifyXMLSignatureResponseBuilder(true).build(vsresponse); + + // parses the + final IXMLSignatureVerificationResponse verifyXmlSignatureResponse = + new VerifyXmlSignatureResponseParser(result.getDocumentElement()).parseData(); + + return verifyXmlSignatureResponse; + + } catch (final MoaSigServiceException e) { + throw e; + + } catch (final MOAException e) { + log.warn("MOA-Sig signature-verification has an internal error." + " MsgCode: " + + e.getMessageId() + " Msg: " + e.getMessage(), e); + throw new MoaSigServiceException("service.moasig.03", new Object[] {e.getMessage()}, e); + + } finally { + tearDownContexts(); + + } + } + + private ICMSSignatureVerificationResponse parseCmsVerificationResult( + final VerifyCMSSignatureResponse cmsSigVerifyResp) throws CertificateEncodingException { + + if (cmsSigVerifyResp.getResponseElements() == null + || cmsSigVerifyResp.getResponseElements().isEmpty()) { + log.info("No CMS signature FOUND. "); + return null; + + } + + if (cmsSigVerifyResp.getResponseElements().size() > 1) { + log.warn( + "CMS or CAdES signature contains more than one technical signatures. Only validate the first signature"); + } + + final VerifyCMSSignatureResponseElement firstSig = + (VerifyCMSSignatureResponseElement) cmsSigVerifyResp.getResponseElements().get(0); + + final at.gv.egiz.eid.authhandler.modules.sigverify.moasig.impl.data.VerifyCMSSignatureResponse result = + new at.gv.egiz.eid.authhandler.modules.sigverify.moasig.impl.data.VerifyCMSSignatureResponse(); + + // parse results into response container + result.setSignatureCheckCode(firstSig.getSignatureCheck().getCode()); + result.setCertificateCheckCode(firstSig.getCertificateCheck().getCode()); + + if (firstSig.getSignerInfo() != null) { + result.setSigningDateTime(firstSig.getSignerInfo().getSigningTime()); + result + .setX509CertificateEncoded(firstSig.getSignerInfo().getSignerCertificate().getEncoded()); + result.setQualifiedCertificate(firstSig.getSignerInfo().isQualifiedCertificate()); + + result.setPublicAuthority(firstSig.getSignerInfo().isPublicAuthority()); + result.setPublicAuthorityCode(firstSig.getSignerInfo().getPublicAuhtorityID()); + + } else { + log.info("CMS or CAdES verification result contains no SignerInfo"); + } + + return result; + } + + /** + * Build a VerifyCMS-Siganture request for MOA-Sig.
    + *
    + * This builder only generates verification-request for enveloped CMS or CAdES signatures
    + * This + * + * @param signature CMS or CAdES signature + * @param trustProfileID trustProfileID MOA-Sig Trust-Profile + * @param isPdfSignature Make CAdES signature as part of an PAdES document + * @param performExtendedValidation To extended validation. See MOA-Sig documentation for detailed + * information + * @return + */ + private VerifyCMSSignatureRequest buildVerfifyCmsRequest(final byte[] signature, + final String trustProfileID, final boolean isPdfSignature, + final boolean performExtendedValidation) { + final VerifyCMSSignatureRequestImpl verifyCmsSignatureRequest = + new VerifyCMSSignatureRequestImpl(); + verifyCmsSignatureRequest.setDateTime(null); + verifyCmsSignatureRequest.setCMSSignature(new ByteArrayInputStream(signature)); + verifyCmsSignatureRequest.setDataObject(null); + verifyCmsSignatureRequest.setTrustProfileId(trustProfileID); + verifyCmsSignatureRequest.setSignatories(VerifyCMSSignatureRequest.ALL_SIGNATORIES); + verifyCmsSignatureRequest.setPDF(isPdfSignature); + verifyCmsSignatureRequest.setExtended(performExtendedValidation); + return verifyCmsSignatureRequest; + + } + + /** + * Build a VerifyXML-Signature request for MOA-Sig. + * + * @param signature Serialized XML signature + * @param trustProfileID MOA-Sig Trust-Profile + * @param verifyTransformsInfoProfileID {@link List} of Transformation-Profiles used for + * validation + * @param xpathSignatureLocation Xpath that points to location of Signature element + * @return MOA-Sig verification request element + * @throws MoaSigServiceBuilderException In case of an error + */ + private Element buildVerifyXmlRequest(final byte[] signature, final String trustProfileID, + final List verifyTransformsInfoProfileID, final String xpathSignatureLocation) + throws MoaSigServiceBuilderException { + try { + // build empty document + final Document requestDoc_ = getNewDocumentBuilder(); + final Element requestElem_ = + requestDoc_.createElementNS(MOA_NS_URI, "VerifyXMLSignatureRequest"); + requestElem_.setAttributeNS(XMLNS_NS_URI, "xmlns", MOA_NS_URI); + requestElem_.setAttributeNS(XMLNS_NS_URI, "xmlns:" + Constants.DSIG_PREFIX, + Constants.DSIG_NS_URI); + requestDoc_.appendChild(requestElem_); + + + // build the request + final Element verifiySignatureInfoElem = + requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureInfo"); + requestElem_.appendChild(verifiySignatureInfoElem); + final Element verifySignatureEnvironmentElem = + requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureEnvironment"); + verifiySignatureInfoElem.appendChild(verifySignatureEnvironmentElem); + final Element base64ContentElem = requestDoc_.createElementNS(MOA_NS_URI, "Base64Content"); + verifySignatureEnvironmentElem.appendChild(base64ContentElem); + + // insert the base64 encoded signature + String base64EncodedAssertion = Base64Utils.encodeToString(signature); + // replace all '\r' characters by no char. + final StringBuffer replaced = new StringBuffer(); + for (int i = 0; i < base64EncodedAssertion.length(); i++) { + final char c = base64EncodedAssertion.charAt(i); + if (c != '\r') { + replaced.append(c); + } + } + base64EncodedAssertion = replaced.toString(); + final Node base64Content = requestDoc_.createTextNode(base64EncodedAssertion); + base64ContentElem.appendChild(base64Content); + + // specify the signature location + final Element verifySignatureLocationElem = + requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureLocation"); + verifiySignatureInfoElem.appendChild(verifySignatureLocationElem); + final Node signatureLocation = requestDoc_.createTextNode(xpathSignatureLocation); + verifySignatureLocationElem.appendChild(signatureLocation); + + // signature manifest params + if (verifyTransformsInfoProfileID != null && !verifyTransformsInfoProfileID.isEmpty()) { + final Element signatureManifestCheckParamsElem = + requestDoc_.createElementNS(MOA_NS_URI, "SignatureManifestCheckParams"); + requestElem_.appendChild(signatureManifestCheckParamsElem); + signatureManifestCheckParamsElem.setAttribute("ReturnReferenceInputData", "false"); + + // verify transformations + final Element referenceInfoElem = requestDoc_.createElementNS(MOA_NS_URI, "ReferenceInfo"); + signatureManifestCheckParamsElem.appendChild(referenceInfoElem); + for (final String element : verifyTransformsInfoProfileID) { + final Element verifyTransformsInfoProfileIdElem = + requestDoc_.createElementNS(MOA_NS_URI, "VerifyTransformsInfoProfileID"); + referenceInfoElem.appendChild(verifyTransformsInfoProfileIdElem); + verifyTransformsInfoProfileIdElem.appendChild(requestDoc_.createTextNode(element)); } + } - } - - /* (non-Javadoc) - * @see at.gv.egiz.eid.authhandler.modules.sigverify.moasig.impl.ISignatureVerificationService#verifyXMLSignature(byte[], java.lang.String) - */ - @Override - public IXMLSignatureVerificationResponse verifyXMLSignature(byte[] signature, String trustProfileID) throws MOASigServiceException { - return verifyXMLSignature(signature, trustProfileID, null, DEFAULT_XPATH_SIGNATURE_LOCATION); - - } - - /* (non-Javadoc) - * @see at.gv.egiz.eid.authhandler.modules.sigverify.moasig.impl.ISignatureVerificationService#verifyXMLSignature(byte[], java.lang.String, java.util.List) - */ - @Override - public IXMLSignatureVerificationResponse verifyXMLSignature(byte[] signature, String trustProfileID, List verifyTransformsInfoProfileID) throws MOASigServiceException { - return verifyXMLSignature(signature, trustProfileID, verifyTransformsInfoProfileID, DEFAULT_XPATH_SIGNATURE_LOCATION); - } - - /* (non-Javadoc) - * @see at.gv.egiz.eid.authhandler.modules.sigverify.moasig.impl.ISignatureVerificationService#verifyXMLSignature(byte[], java.lang.String, java.lang.String) - */ - @Override - public IXMLSignatureVerificationResponse verifyXMLSignature(byte[] signature, String trustProfileID, String signatureLocationXpath) throws MOASigServiceException { - return verifyXMLSignature(signature, trustProfileID, null, signatureLocationXpath); - } - - /* (non-Javadoc) - * @see at.gv.egiz.eid.authhandler.modules.sigverify.moasig.impl.ISignatureVerificationService#verifyXMLSignature(byte[], java.lang.String, java.util.List, java.lang.String) - */ - @Override - public IXMLSignatureVerificationResponse verifyXMLSignature(byte[] signature, String trustProfileID, List verifyTransformsInfoProfileID, String xpathSignatureLocation) throws MOASigServiceException { - try { - //setup context - setUpContexts(Thread.currentThread().getName()); - - //build signature-verification request - final Element domVerifyXMLSignatureRequest = buildVerifyXMLRequest(signature, trustProfileID, verifyTransformsInfoProfileID, xpathSignatureLocation); - - //send signature-verification to MOA-Sig - final VerifyXMLSignatureRequest vsrequest = new VerifyXMLSignatureRequestParser().parse(domVerifyXMLSignatureRequest); - final VerifyXMLSignatureResponse vsresponse = xadesInvocer.verifyXMLSignature(vsrequest); - final Document result = new VerifyXMLSignatureResponseBuilder(true).build(vsresponse); - - // parses the - final IXMLSignatureVerificationResponse verifyXMLSignatureResponse = new VerifyXMLSignatureResponseParser(result.getDocumentElement()).parseData(); - - return verifyXMLSignatureResponse; - - } catch (final MOASigServiceException e) { - throw e; - - } catch (final MOAException e) { - log.warn("MOA-Sig signature-verification has an internal error." - + " MsgCode: " + e.getMessageId() - + " Msg: " + e.getMessage(), - e); - throw new MOASigServiceException("service.moasig.03", new Object[]{e.getMessage()}, e); - - } finally { - tearDownContexts(); + // hashinput data + final Element returnHashInputDataElem = + requestDoc_.createElementNS(MOA_NS_URI, "ReturnHashInputData"); + requestElem_.appendChild(returnHashInputDataElem); - } - } - -private ICMSSignatureVerificationResponse parseCMSVerificationResult(VerifyCMSSignatureResponse cmsSigVerifyResp) throws CertificateEncodingException { - - if (cmsSigVerifyResp.getResponseElements() == null || - cmsSigVerifyResp.getResponseElements().isEmpty()) { - log.info("No CMS signature FOUND. "); - return null; - - } - - if (cmsSigVerifyResp.getResponseElements().size() > 1) - log.warn("CMS or CAdES signature contains more than one technical signatures. Only validate the first signature"); - - final VerifyCMSSignatureResponseElement firstSig = (VerifyCMSSignatureResponseElement) cmsSigVerifyResp.getResponseElements().get(0); - - final at.gv.egiz.eid.authhandler.modules.sigverify.moasig.impl.data.VerifyCMSSignatureResponse result = - new at.gv.egiz.eid.authhandler.modules.sigverify.moasig.impl.data.VerifyCMSSignatureResponse(); - - //parse results into response container - result.setSignatureCheckCode(firstSig.getSignatureCheck().getCode()); - result.setCertificateCheckCode(firstSig.getCertificateCheck().getCode()); - - if (firstSig.getSignerInfo() != null) { - result.setSigningDateTime(firstSig.getSignerInfo().getSigningTime()); - result.setX509CertificateEncoded(firstSig.getSignerInfo().getSignerCertificate().getEncoded()); - result.setQualifiedCertificate(firstSig.getSignerInfo().isQualifiedCertificate()); - - result.setPublicAuthority(firstSig.getSignerInfo().isPublicAuthority()); - result.setPublicAuthorityCode(firstSig.getSignerInfo().getPublicAuhtorityID()); - - } else - log.info("CMS or CAdES verification result contains no SignerInfo"); - - return result; - } - - /** - * Build a VerifyCMS-Siganture request for MOA-Sig. - *

    - * This builder only generates verification-request for enveloped CMS or CAdES signatures - *
    - * This - * - * @param signature CMS or CAdES signature - * @param trustProfileID trustProfileID MOA-Sig Trust-Profile - * @param isPdfSignature Make CAdES signature as part of an PAdES document - * @param performExtendedValidation To extended validation. See MOA-Sig documentation for detailed information - * @return - */ - private VerifyCMSSignatureRequest buildVerfifyCMSRequest(byte[] signature, String trustProfileID, - boolean isPdfSignature, boolean performExtendedValidation) { - final VerifyCMSSignatureRequestImpl verifyCMSSignatureRequest = new VerifyCMSSignatureRequestImpl(); - verifyCMSSignatureRequest.setDateTime(null); - verifyCMSSignatureRequest.setCMSSignature(new ByteArrayInputStream(signature)); - verifyCMSSignatureRequest.setDataObject(null); - verifyCMSSignatureRequest.setTrustProfileId(trustProfileID); - verifyCMSSignatureRequest.setSignatories(VerifyCMSSignatureRequest.ALL_SIGNATORIES); - verifyCMSSignatureRequest.setPDF(isPdfSignature); - verifyCMSSignatureRequest.setExtended(performExtendedValidation); - return verifyCMSSignatureRequest; - - } - - /** - * Build a VerifyXML-Signature request for MOA-Sig - * - * @param signature Serialized XML signature - * @param trustProfileID MOA-Sig Trust-Profile - * @param verifyTransformsInfoProfileID {@link List} of Transformation-Profiles used for validation - * @param xpathSignatureLocation Xpath that points to location of Signature element - * @return - * @throws MOASigServiceBuilderException - */ - private Element buildVerifyXMLRequest(byte[] signature, String trustProfileID, List verifyTransformsInfoProfileID, String xpathSignatureLocation) throws MOASigServiceBuilderException { - try { - //build empty document - final Document requestDoc_ = getNewDocumentBuilder(); - final Element requestElem_ = requestDoc_.createElementNS(MOA_NS_URI, "VerifyXMLSignatureRequest"); - requestElem_.setAttributeNS(XMLNS_NS_URI, "xmlns", MOA_NS_URI); - requestElem_.setAttributeNS(XMLNS_NS_URI, "xmlns:" + Constants.DSIG_PREFIX, Constants.DSIG_NS_URI); - requestDoc_.appendChild(requestElem_); - - - // build the request - final Element verifiySignatureInfoElem = requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureInfo"); - requestElem_.appendChild(verifiySignatureInfoElem); - final Element verifySignatureEnvironmentElem = requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureEnvironment"); - verifiySignatureInfoElem.appendChild(verifySignatureEnvironmentElem); - final Element base64ContentElem = requestDoc_.createElementNS(MOA_NS_URI, "Base64Content"); - verifySignatureEnvironmentElem.appendChild(base64ContentElem); - - // insert the base64 encoded signature - String base64EncodedAssertion = Base64Utils.encodeToString(signature); - //replace all '\r' characters by no char. - final StringBuffer replaced = new StringBuffer(); - for (int i = 0; i < base64EncodedAssertion.length(); i ++) { - final char c = base64EncodedAssertion.charAt(i); - if (c != '\r') { - replaced.append(c); - } - } - base64EncodedAssertion = replaced.toString(); - final Node base64Content = requestDoc_.createTextNode(base64EncodedAssertion); - base64ContentElem.appendChild(base64Content); - - // specify the signature location - final Element verifySignatureLocationElem = requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureLocation"); - verifiySignatureInfoElem.appendChild(verifySignatureLocationElem); - final Node signatureLocation = requestDoc_.createTextNode(xpathSignatureLocation); - verifySignatureLocationElem.appendChild(signatureLocation); - - // signature manifest params - if (verifyTransformsInfoProfileID != null && !verifyTransformsInfoProfileID.isEmpty()) { - final Element signatureManifestCheckParamsElem = requestDoc_.createElementNS(MOA_NS_URI, "SignatureManifestCheckParams"); - requestElem_.appendChild(signatureManifestCheckParamsElem); - signatureManifestCheckParamsElem.setAttribute("ReturnReferenceInputData", "false"); - - //verify transformations - final Element referenceInfoElem = requestDoc_.createElementNS(MOA_NS_URI, "ReferenceInfo"); - signatureManifestCheckParamsElem.appendChild(referenceInfoElem); - for (final String element : verifyTransformsInfoProfileID) { - final Element verifyTransformsInfoProfileIDElem = requestDoc_.createElementNS(MOA_NS_URI, "VerifyTransformsInfoProfileID"); - referenceInfoElem.appendChild(verifyTransformsInfoProfileIDElem); - verifyTransformsInfoProfileIDElem.appendChild(requestDoc_.createTextNode(element)); - - } - } - - //hashinput data - final Element returnHashInputDataElem = requestDoc_.createElementNS(MOA_NS_URI, "ReturnHashInputData"); - requestElem_.appendChild(returnHashInputDataElem); - - //add trustProfileID - final Element trustProfileIDElem = requestDoc_.createElementNS(MOA_NS_URI, "TrustProfileID"); - trustProfileIDElem.appendChild(requestDoc_.createTextNode(trustProfileID)); - requestElem_.appendChild(trustProfileIDElem); - - return requestElem_; - - } catch (final Throwable t) { - log.warn("Can NOT build VerifyXML-Signature request for MOA-Sig", t); - throw new MOASigServiceBuilderException("service.moasig.03", new Object[] { t.getMessage() }, t); - - } - - } - - - - @PostConstruct - protected void internalInitializer() { - log.debug("Instanzing SignatureVerificationService implementation ... "); - //svs = at.gv.egovernment.moa.spss.api.SignatureVerificationService.getInstance(); - cadesInvoker = CMSSignatureVerificationInvoker.getInstance(); - xadesInvocer = XMLSignatureVerificationInvoker.getInstance(); - log.info("MOA-Sig signature-verification service initialized"); - - } + // add trustProfileID + final Element trustProfileIdElem = requestDoc_.createElementNS(MOA_NS_URI, "TrustProfileID"); + trustProfileIdElem.appendChild(requestDoc_.createTextNode(trustProfileID)); + requestElem_.appendChild(trustProfileIdElem); + + return requestElem_; + + } catch (final Throwable t) { + log.warn("Can NOT build VerifyXML-Signature request for MOA-Sig", t); + throw new MoaSigServiceBuilderException("service.moasig.03", new Object[] {t.getMessage()}, + t); + + } + + } + + + + @PostConstruct + protected void internalInitializer() { + log.debug("Instanzing SignatureVerificationService implementation ... "); + // svs = at.gv.egovernment.moa.spss.api.SignatureVerificationService.getInstance(); + cadesInvoker = CMSSignatureVerificationInvoker.getInstance(); + xadesInvocer = XMLSignatureVerificationInvoker.getInstance(); + log.info("MOA-Sig signature-verification service initialized"); + + } } diff --git a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/data/GenericSignatureVerificationResponse.java b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/data/GenericSignatureVerificationResponse.java index f3c724d8..701e2072 100644 --- a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/data/GenericSignatureVerificationResponse.java +++ b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/data/GenericSignatureVerificationResponse.java @@ -9,122 +9,125 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.api.data.IGenericSignatureVerificationResponse; -import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.exceptions.MOASigServiceException; -import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.exceptions.MOASigServiceParserException; - -public class GenericSignatureVerificationResponse implements IGenericSignatureVerificationResponse, Serializable { - - private static final long serialVersionUID = -7751001050689401118L; - private static final Logger log = LoggerFactory.getLogger(GenericSignatureVerificationResponse.class); - - - /** The signing time */ - private Date signingDateTime; - - /** The signatureCheckCode to be stored */ - private int signatureCheckCode; - - /** The certificateCheckCode to be stored */ - private int certificateCheckCode; - - /** The publicAuthority to be stored */ - private boolean publicAuthority; - - /** The publicAuthorityCode to be stored */ - private String publicAuthorityCode; - - /** The qualifiedCertificate to be stored */ - private boolean qualifiedCertificate; - - private byte[] x509CertificateEncoded; - - @Override - public Date getSigningDateTime() { - return this.signingDateTime; - - } - - @Override - public int getSignatureCheckCode() { - return this.signatureCheckCode; - - } - - @Override - public int getCertificateCheckCode() { - return this.certificateCheckCode; - - } - - @Override - public boolean isQualifiedCertificate() { - return this.qualifiedCertificate; - - } - - @Override - public X509Certificate getX509Certificate() throws MOASigServiceException { - if (x509CertificateEncoded != null) { - try { - return new X509Certificate(x509CertificateEncoded); - - } catch (CertificateException e) { - log.error("Can NOT parse X509 certifcate in " + GenericSignatureVerificationResponse.class.getName(), e); - throw new MOASigServiceParserException("service.moasig.01", null, e); - } - - } - - return null; - - } - - @Override - public byte[] getX509CertificateEncoded() { - return this.getX509CertificateEncoded(); - - } - - @Override - public boolean isPublicAuthority() { - return this.publicAuthority; - - } - - @Override - public String getPublicAuthorityCode() { - return this.publicAuthorityCode; - - } - - public void setSigningDateTime(Date signingDateTime) { - this.signingDateTime = signingDateTime; - } - - public void setSignatureCheckCode(int signatureCheckCode) { - this.signatureCheckCode = signatureCheckCode; - } - - public void setCertificateCheckCode(int certificateCheckCode) { - this.certificateCheckCode = certificateCheckCode; - } - - public void setPublicAuthority(boolean publicAuthority) { - this.publicAuthority = publicAuthority; - } - - public void setPublicAuthorityCode(String publicAuthorityCode) { - this.publicAuthorityCode = publicAuthorityCode; - } - - public void setQualifiedCertificate(boolean qualifiedCertificate) { - this.qualifiedCertificate = qualifiedCertificate; - } - - public void setX509CertificateEncoded(byte[] x509CertificateEncoded) { - this.x509CertificateEncoded = x509CertificateEncoded; - } - - +import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.exceptions.MoaSigServiceException; +import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.exceptions.MoaSigServiceParserException; + +public class GenericSignatureVerificationResponse + implements IGenericSignatureVerificationResponse, Serializable { + + private static final long serialVersionUID = -7751001050689401118L; + private static final Logger log = + LoggerFactory.getLogger(GenericSignatureVerificationResponse.class); + + + /** The signing time */ + private Date signingDateTime; + + /** The signatureCheckCode to be stored */ + private int signatureCheckCode; + + /** The certificateCheckCode to be stored */ + private int certificateCheckCode; + + /** The publicAuthority to be stored */ + private boolean publicAuthority; + + /** The publicAuthorityCode to be stored */ + private String publicAuthorityCode; + + /** The qualifiedCertificate to be stored */ + private boolean qualifiedCertificate; + + private byte[] x509CertificateEncoded; + + @Override + public Date getSigningDateTime() { + return this.signingDateTime; + + } + + @Override + public int getSignatureCheckCode() { + return this.signatureCheckCode; + + } + + @Override + public int getCertificateCheckCode() { + return this.certificateCheckCode; + + } + + @Override + public boolean isQualifiedCertificate() { + return this.qualifiedCertificate; + + } + + @Override + public X509Certificate getX509Certificate() throws MoaSigServiceException { + if (x509CertificateEncoded != null) { + try { + return new X509Certificate(x509CertificateEncoded); + + } catch (final CertificateException e) { + log.error("Can NOT parse X509 certifcate in " + + GenericSignatureVerificationResponse.class.getName(), e); + throw new MoaSigServiceParserException("service.moasig.01", null, e); + } + + } + + return null; + + } + + @Override + public byte[] getX509CertificateEncoded() { + return this.getX509CertificateEncoded(); + + } + + @Override + public boolean isPublicAuthority() { + return this.publicAuthority; + + } + + @Override + public String getPublicAuthorityCode() { + return this.publicAuthorityCode; + + } + + public void setSigningDateTime(final Date signingDateTime) { + this.signingDateTime = signingDateTime; + } + + public void setSignatureCheckCode(final int signatureCheckCode) { + this.signatureCheckCode = signatureCheckCode; + } + + public void setCertificateCheckCode(final int certificateCheckCode) { + this.certificateCheckCode = certificateCheckCode; + } + + public void setPublicAuthority(final boolean publicAuthority) { + this.publicAuthority = publicAuthority; + } + + public void setPublicAuthorityCode(final String publicAuthorityCode) { + this.publicAuthorityCode = publicAuthorityCode; + } + + public void setQualifiedCertificate(final boolean qualifiedCertificate) { + this.qualifiedCertificate = qualifiedCertificate; + } + + public void setX509CertificateEncoded(final byte[] x509CertificateEncoded) { + this.x509CertificateEncoded = x509CertificateEncoded; + } + + } diff --git a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/data/VerifyCMSSignatureResponse.java b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/data/VerifyCMSSignatureResponse.java index 2c177c71..0583a29e 100644 --- a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/data/VerifyCMSSignatureResponse.java +++ b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/data/VerifyCMSSignatureResponse.java @@ -2,8 +2,9 @@ package at.gv.egiz.eid.authhandler.modules.sigverify.moasig.impl.data; import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.api.data.ICMSSignatureVerificationResponse; -public class VerifyCMSSignatureResponse extends GenericSignatureVerificationResponse implements ICMSSignatureVerificationResponse{ +public class VerifyCMSSignatureResponse extends GenericSignatureVerificationResponse + implements ICMSSignatureVerificationResponse { - private static final long serialVersionUID = 708260904158070696L; + private static final long serialVersionUID = 708260904158070696L; } diff --git a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/data/VerifyXMLSignatureResponse.java b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/data/VerifyXMLSignatureResponse.java index 0646bda7..003d2c46 100644 --- a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/data/VerifyXMLSignatureResponse.java +++ b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/data/VerifyXMLSignatureResponse.java @@ -3,17 +3,18 @@ package at.gv.egiz.eid.authhandler.modules.sigverify.moasig.impl.data; import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.api.data.IXMLSignatureVerificationResponse; /** - * - * + * + * * @author tlenz * */ -public class VerifyXMLSignatureResponse extends GenericSignatureVerificationResponse implements IXMLSignatureVerificationResponse { +public class VerifyXMLSignatureResponse extends GenericSignatureVerificationResponse + implements IXMLSignatureVerificationResponse { private static final long serialVersionUID = 8386070769565711601L; -/** The xmlDsigSubjectName to be stored */ + /** The xmlDsigSubjectName to be stored */ private String xmlDsigSubjectName; /** The xmlDSIGManifestCheckCode to be stored */ @@ -22,72 +23,97 @@ public class VerifyXMLSignatureResponse extends GenericSignatureVerificationResp private boolean xmlDSIGManigest; /** - * The result of the signature manifest check. The default value -1 - * indicates that the signature manifest has not been checked. + * The result of the signature manifest check. The default value -1 indicates that + * the signature manifest has not been checked. */ private int signatureManifestCheckCode = -1; - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IVerifiyXMLSignatureResponse#getXmlDSIGManifestCheckCode() - */ + + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.auth.data.IVerifiyXMLSignatureResponse#getXmlDSIGManifestCheckCode() + */ @Override -public int getXmlDSIGManifestCheckCode() { + public int getXmlDSIGManifestCheckCode() { return xmlDSIGManifestCheckCode; } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IVerifiyXMLSignatureResponse#getXmlDsigSubjectName() - */ + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IVerifiyXMLSignatureResponse#getXmlDsigSubjectName() + */ @Override -public String getXmlDsigSubjectName() { + public String getXmlDsigSubjectName() { return xmlDsigSubjectName; } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IVerifiyXMLSignatureResponse#setXmlDSIGManifestCheckCode(int) - */ -public void setXmlDSIGManifestCheckCode(int xmlDSIGManifestCheckCode) { + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.auth.data.IVerifiyXMLSignatureResponse#setXmlDSIGManifestCheckCode( + * int) + */ + public void setXmlDSIGManifestCheckCode(final int xmlDSIGManifestCheckCode) { this.xmlDSIGManifestCheckCode = xmlDSIGManifestCheckCode; } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IVerifiyXMLSignatureResponse#setXmlDsigSubjectName(java.lang.String) - */ -public void setXmlDsigSubjectName(String xmlDsigSubjectName) { + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.auth.data.IVerifiyXMLSignatureResponse#setXmlDsigSubjectName(java.lang + * .String) + */ + public void setXmlDsigSubjectName(final String xmlDsigSubjectName) { this.xmlDsigSubjectName = xmlDsigSubjectName; } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IVerifiyXMLSignatureResponse#isXmlDSIGManigest() - */ + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.auth.data.IVerifiyXMLSignatureResponse#isXmlDSIGManigest() + */ @Override -public boolean isXmlDSIGManigest() { + public boolean isXmlDSIGManigest() { return xmlDSIGManigest; } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IVerifiyXMLSignatureResponse#setXmlDSIGManigest(boolean) - */ -public void setXmlDSIGManigest(boolean xmlDSIGManigest) { + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.auth.data.IVerifiyXMLSignatureResponse#setXmlDSIGManigest(boolean) + */ + public void setXmlDSIGManigest(final boolean xmlDSIGManigest) { this.xmlDSIGManigest = xmlDSIGManigest; } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IVerifiyXMLSignatureResponse#getSignatureManifestCheckCode() - */ + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.auth.data.IVerifiyXMLSignatureResponse#getSignatureManifestCheckCode() + */ @Override -public int getSignatureManifestCheckCode() { + public int getSignatureManifestCheckCode() { return signatureManifestCheckCode; } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IVerifiyXMLSignatureResponse#setSignatureManifestCheckCode(int) - */ -public void setSignatureManifestCheckCode(int signatureManifestCheckCode) { + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.auth.data.IVerifiyXMLSignatureResponse#setSignatureManifestCheckCode( + * int) + */ + public void setSignatureManifestCheckCode(final int signatureManifestCheckCode) { this.signatureManifestCheckCode = signatureManifestCheckCode; } - + } diff --git a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/parser/VerifyXMLSignatureResponseParser.java b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/parser/VerifyXMLSignatureResponseParser.java deleted file mode 100644 index e581394b..00000000 --- a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/parser/VerifyXMLSignatureResponseParser.java +++ /dev/null @@ -1,180 +0,0 @@ -package at.gv.egiz.eid.authhandler.modules.sigverify.moasig.impl.parser; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; - -import org.joda.time.DateTime; -import org.joda.time.format.ISODateTimeFormat; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.lang.NonNull; -import org.w3c.dom.Element; - -import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.api.data.IXMLSignatureVerificationResponse; -import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.exceptions.MOASigServiceException; -import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.exceptions.MOASigServiceParserException; -import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.impl.data.VerifyXMLSignatureResponse; -import at.gv.egovernment.moaspss.util.Constants; -import at.gv.egovernment.moaspss.util.DOMUtils; -import at.gv.egovernment.moaspss.util.XPathUtils; -import iaik.utils.Base64InputStream; -import iaik.x509.X509Certificate; - - -public class VerifyXMLSignatureResponseParser { - private static final Logger log = LoggerFactory.getLogger(VerifyXMLSignatureResponseParser.class); - - // - // XPath namespace prefix shortcuts - // - /** Xpath prefix for reaching MOA Namespaces */ - private static final String MOA = Constants.MOA_PREFIX + ":"; - /** Xpath prefix for reaching DSIG Namespaces */ - private static final String DSIG = Constants.DSIG_PREFIX + ":"; - /** Xpath expression to the root element */ - private static final String ROOT = "/" + MOA + "VerifyXMLSignatureResponse/"; - - /** Xpath expression to the X509SubjectName element */ - private static final String DSIG_SUBJECT_NAME_XPATH = - ROOT + MOA + "SignerInfo/" + DSIG + "X509Data/" + - DSIG + "X509SubjectName"; - /** Xpath expression to the X509Certificate element */ - private static final String DSIG_X509_CERTIFICATE_XPATH = - ROOT + MOA + "SignerInfo/" + DSIG + "X509Data/" + - DSIG + "X509Certificate"; - /** Xpath expression to the PublicAuthority element */ - private static final String PUBLIC_AUTHORITY_XPATH = - ROOT + MOA + "SignerInfo/" + DSIG + "X509Data/" + - MOA + "PublicAuthority"; - /** Xpath expression to the PublicAuthorityCode element */ - private static final String PUBLIC_AUTHORITY_CODE_XPATH = - PUBLIC_AUTHORITY_XPATH + "/" + MOA + "Code"; - /** Xpath expression to the QualifiedCertificate element */ - private static final String QUALIFIED_CERTIFICATE_XPATH = - ROOT + MOA + "SignerInfo/" + DSIG + "X509Data/" + - MOA + "QualifiedCertificate"; - - /** Xpath expression to the SignatureCheckCode element */ - private static final String SIGNATURE_CHECK_CODE_XPATH = - ROOT + MOA + "SignatureCheck/" + MOA + "Code"; - /** Xpath expression to the XMLDSIGManifestCheckCode element */ - private static final String XMLDSIG_MANIFEST_CHECK_CODE_XPATH = - ROOT + MOA + "XMLDSIGManifestCheck/" + MOA + "Code"; - /** Xpath expression to the SignatureManifestCheckCode element */ - private static final String SIGNATURE_MANIFEST_CHECK_CODE_XPATH = - ROOT + MOA + "SignatureManifestCheck/" + MOA + "Code"; - /** Xpath expression to the CertificateCheckCode element */ - private static final String CERTIFICATE_CHECK_CODE_XPATH = - ROOT + MOA + "CertificateCheck/" + MOA + "Code"; - - private static final String SIGNING_TIME_XPATH = - ROOT + MOA + "SigningTime"; - - - /** This is the root element of the XML-Document provided by the Security Layer Card*/ - private Element verifyXMLSignatureResponse; - - /** - * Constructor for VerifyXMLSignatureResponseParser. - * A DOM-representation of the incoming String will be created - * @param xmlResponse <InfoboxReadResponse> as String - * @throws MOASigServiceParserException on any parsing error - */ - public VerifyXMLSignatureResponseParser(String xmlResponse) throws MOASigServiceParserException { - try { - final InputStream s = new ByteArrayInputStream(xmlResponse.getBytes("UTF-8")); - verifyXMLSignatureResponse = DOMUtils.parseXmlValidating(s); - - } catch (final Throwable t) { - log.warn("Can not parse MOA-Sig response." , t); - throw new MOASigServiceParserException("service.moasig.02", new Object[] { t.toString() }, t); - - } - } - - /** - * Constructor for VerifyXMLSignatureResponseParser. - * A DOM-representation of the incoming Inputstream will be created - * @param xmlResponse <InfoboxReadResponse> as InputStream - * @throws MOASigServiceParserException on any parsing error - */ - public VerifyXMLSignatureResponseParser(InputStream xmlResponse) throws MOASigServiceParserException { - try { - verifyXMLSignatureResponse = DOMUtils.parseXmlValidating(xmlResponse); - - } catch (final Throwable t) { - log.warn("Can not parse MOA-Sig response." , t); - throw new MOASigServiceParserException("service.moasig.02", new Object[] { t.toString() }, t); - - } - } - - /** - * Constructor for VerifyXMLSignatureResponseParser. - * The incoming Element will be used for further operations - * @param xmlResponse <InfoboxReadResponse> as Element - */ - public VerifyXMLSignatureResponseParser(Element xmlResponse) { - verifyXMLSignatureResponse =xmlResponse; - - } - -/** - * Parse MOA-Sig signatur-verification result into {@link IXMLSignatureVerificationResponse} - * - * @return {@link IXMLSignatureVerificationResponse} - * @throws MOASigServiceException on any parsing error - */ - @NonNull - public IXMLSignatureVerificationResponse parseData() throws MOASigServiceException { - try { - final VerifyXMLSignatureResponse respData = new VerifyXMLSignatureResponse(); - respData.setXmlDsigSubjectName(XPathUtils.getElementValue(verifyXMLSignatureResponse,DSIG_SUBJECT_NAME_XPATH,"")); - final Element e = (Element)XPathUtils.selectSingleNode(verifyXMLSignatureResponse,QUALIFIED_CERTIFICATE_XPATH); - respData.setQualifiedCertificate(e!=null); - - final Base64InputStream in = new Base64InputStream(new ByteArrayInputStream(XPathUtils.getElementValue( - verifyXMLSignatureResponse,DSIG_X509_CERTIFICATE_XPATH,"").getBytes("UTF-8")),true); - - respData.setX509CertificateEncoded(new X509Certificate(in).getEncoded()); - - final Element publicAuthority = (Element)XPathUtils.selectSingleNode(verifyXMLSignatureResponse,PUBLIC_AUTHORITY_XPATH); - respData.setPublicAuthority(publicAuthority != null); - respData.setPublicAuthorityCode(XPathUtils.getElementValue(verifyXMLSignatureResponse,PUBLIC_AUTHORITY_CODE_XPATH,"")); - respData.setSignatureCheckCode(new Integer(XPathUtils.getElementValue(verifyXMLSignatureResponse,SIGNATURE_CHECK_CODE_XPATH,"")).intValue()); - - final String xmlDsigCheckCode = XPathUtils.getElementValue(verifyXMLSignatureResponse,XMLDSIG_MANIFEST_CHECK_CODE_XPATH,null); - if (xmlDsigCheckCode!=null) { - respData.setXmlDSIGManigest(true); - respData.setXmlDSIGManifestCheckCode(new Integer(xmlDsigCheckCode).intValue()); - - } else { - respData.setXmlDSIGManigest(false); - - } - - final String signatureManifestCheckCode = XPathUtils.getElementValue(verifyXMLSignatureResponse,SIGNATURE_MANIFEST_CHECK_CODE_XPATH,null); - if (signatureManifestCheckCode != null) { - respData.setSignatureManifestCheckCode(new Integer(signatureManifestCheckCode).intValue()); - - } - respData.setCertificateCheckCode(new Integer(XPathUtils.getElementValue(verifyXMLSignatureResponse,CERTIFICATE_CHECK_CODE_XPATH,"")).intValue()); - - final String signingTimeElement = XPathUtils.getElementValue(verifyXMLSignatureResponse,SIGNING_TIME_XPATH,""); - if (signingTimeElement != null && !signingTimeElement.isEmpty()) { - final DateTime datetime = ISODateTimeFormat.dateOptionalTimeParser().parseDateTime(signingTimeElement); - respData.setSigningDateTime(datetime.toDate()); - - } - - return respData; - - } catch (final Throwable t) { - log.warn("Can not parse MOA-Sig response." , t); - throw new MOASigServiceParserException("service.moasig.02", new Object[] { t.toString() }, t); - } - - } - - -} diff --git a/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/parser/VerifyXmlSignatureResponseParser.java b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/parser/VerifyXmlSignatureResponseParser.java new file mode 100644 index 00000000..8cf941a7 --- /dev/null +++ b/eaaf_modules/eaaf_module_moa-sig/src/main/java/at/gv/egiz/eid/authhandler/modules/sigverify/moasig/impl/parser/VerifyXmlSignatureResponseParser.java @@ -0,0 +1,192 @@ +package at.gv.egiz.eid.authhandler.modules.sigverify.moasig.impl.parser; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.api.data.IXMLSignatureVerificationResponse; +import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.exceptions.MoaSigServiceException; +import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.exceptions.MoaSigServiceParserException; +import at.gv.egiz.eid.authhandler.modules.sigverify.moasig.impl.data.VerifyXMLSignatureResponse; +import at.gv.egovernment.moaspss.util.Constants; +import at.gv.egovernment.moaspss.util.DOMUtils; +import at.gv.egovernment.moaspss.util.XPathUtils; +import org.joda.time.DateTime; +import org.joda.time.format.ISODateTimeFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.lang.NonNull; +import org.w3c.dom.Element; +import iaik.utils.Base64InputStream; +import iaik.x509.X509Certificate; + + +public class VerifyXmlSignatureResponseParser { + private static final Logger log = LoggerFactory.getLogger(VerifyXmlSignatureResponseParser.class); + + // + // XPath namespace prefix shortcuts + // + /** Xpath prefix for reaching MOA Namespaces. */ + private static final String MOA = Constants.MOA_PREFIX + ":"; + /** Xpath prefix for reaching DSIG Namespaces. */ + private static final String DSIG = Constants.DSIG_PREFIX + ":"; + /** Xpath expression to the root element. */ + private static final String ROOT = "/" + MOA + "VerifyXMLSignatureResponse/"; + + /** Xpath expression to the X509SubjectName element. */ + private static final String DSIG_SUBJECT_NAME_XPATH = + ROOT + MOA + "SignerInfo/" + DSIG + "X509Data/" + DSIG + "X509SubjectName"; + /** Xpath expression to the X509Certificate element. */ + private static final String DSIG_X509_CERTIFICATE_XPATH = + ROOT + MOA + "SignerInfo/" + DSIG + "X509Data/" + DSIG + "X509Certificate"; + /** Xpath expression to the PublicAuthority element. */ + private static final String PUBLIC_AUTHORITY_XPATH = + ROOT + MOA + "SignerInfo/" + DSIG + "X509Data/" + MOA + "PublicAuthority"; + /** Xpath expression to the PublicAuthorityCode element. */ + private static final String PUBLIC_AUTHORITY_CODE_XPATH = + PUBLIC_AUTHORITY_XPATH + "/" + MOA + "Code"; + /** Xpath expression to the QualifiedCertificate element. */ + private static final String QUALIFIED_CERTIFICATE_XPATH = + ROOT + MOA + "SignerInfo/" + DSIG + "X509Data/" + MOA + "QualifiedCertificate"; + + /** Xpath expression to the SignatureCheckCode element. */ + private static final String SIGNATURE_CHECK_CODE_XPATH = + ROOT + MOA + "SignatureCheck/" + MOA + "Code"; + /** Xpath expression to the XMLDSIGManifestCheckCode element. */ + private static final String XMLDSIG_MANIFEST_CHECK_CODE_XPATH = + ROOT + MOA + "XMLDSIGManifestCheck/" + MOA + "Code"; + /** Xpath expression to the SignatureManifestCheckCode element. */ + private static final String SIGNATURE_MANIFEST_CHECK_CODE_XPATH = + ROOT + MOA + "SignatureManifestCheck/" + MOA + "Code"; + /** Xpath expression to the CertificateCheckCode element. */ + private static final String CERTIFICATE_CHECK_CODE_XPATH = + ROOT + MOA + "CertificateCheck/" + MOA + "Code"; + + private static final String SIGNING_TIME_XPATH = ROOT + MOA + "SigningTime"; + + + /** This is the root element of the XML-Document provided by the Security Layer Card. */ + private Element verifyXmlSignatureResponse; + + /** + * Constructor for VerifyXMLSignatureResponseParser. A DOM-representation of the incoming String + * will be created + * + * @param xmlResponse <InfoboxReadResponse> as String + * @throws MoaSigServiceParserException on any parsing error + */ + public VerifyXmlSignatureResponseParser(final String xmlResponse) + throws MoaSigServiceParserException { + try { + final InputStream s = new ByteArrayInputStream(xmlResponse.getBytes("UTF-8")); + verifyXmlSignatureResponse = DOMUtils.parseXmlValidating(s); + + } catch (final Throwable t) { + log.warn("Can not parse MOA-Sig response.", t); + throw new MoaSigServiceParserException("service.moasig.02", new Object[] {t.toString()}, t); + + } + } + + /** + * Constructor for VerifyXMLSignatureResponseParser. A DOM-representation of the incoming + * Inputstream will be created + * + * @param xmlResponse <InfoboxReadResponse> as InputStream + * @throws MoaSigServiceParserException on any parsing error + */ + public VerifyXmlSignatureResponseParser(final InputStream xmlResponse) + throws MoaSigServiceParserException { + try { + verifyXmlSignatureResponse = DOMUtils.parseXmlValidating(xmlResponse); + + } catch (final Throwable t) { + log.warn("Can not parse MOA-Sig response.", t); + throw new MoaSigServiceParserException("service.moasig.02", new Object[] {t.toString()}, t); + + } + } + + /** + * Constructor for VerifyXMLSignatureResponseParser. The incoming Element will be used for further + * operations + * + * @param xmlResponse <InfoboxReadResponse> as Element + */ + public VerifyXmlSignatureResponseParser(final Element xmlResponse) { + verifyXmlSignatureResponse = xmlResponse; + + } + + /** + * Parse MOA-Sig signatur-verification result into {@link IXMLSignatureVerificationResponse}. + * + * @return {@link IXMLSignatureVerificationResponse} + * @throws MoaSigServiceException on any parsing error + */ + @NonNull + public IXMLSignatureVerificationResponse parseData() throws MoaSigServiceException { + try { + final VerifyXMLSignatureResponse respData = new VerifyXMLSignatureResponse(); + respData.setXmlDsigSubjectName( + XPathUtils.getElementValue(verifyXmlSignatureResponse, DSIG_SUBJECT_NAME_XPATH, "")); + final Element e = (Element) XPathUtils.selectSingleNode(verifyXmlSignatureResponse, + QUALIFIED_CERTIFICATE_XPATH); + respData.setQualifiedCertificate(e != null); + + final Base64InputStream in = new Base64InputStream(new ByteArrayInputStream( + XPathUtils.getElementValue(verifyXmlSignatureResponse, DSIG_X509_CERTIFICATE_XPATH, "") + .getBytes("UTF-8")), + true); + + respData.setX509CertificateEncoded(new X509Certificate(in).getEncoded()); + + final Element publicAuthority = + (Element) XPathUtils.selectSingleNode(verifyXmlSignatureResponse, PUBLIC_AUTHORITY_XPATH); + respData.setPublicAuthority(publicAuthority != null); + respData.setPublicAuthorityCode( + XPathUtils.getElementValue(verifyXmlSignatureResponse, PUBLIC_AUTHORITY_CODE_XPATH, "")); + respData.setSignatureCheckCode(new Integer( + XPathUtils.getElementValue(verifyXmlSignatureResponse, SIGNATURE_CHECK_CODE_XPATH, "")) + .intValue()); + + final String xmlDsigCheckCode = XPathUtils.getElementValue(verifyXmlSignatureResponse, + XMLDSIG_MANIFEST_CHECK_CODE_XPATH, null); + if (xmlDsigCheckCode != null) { + respData.setXmlDSIGManigest(true); + respData.setXmlDSIGManifestCheckCode(new Integer(xmlDsigCheckCode).intValue()); + + } else { + respData.setXmlDSIGManigest(false); + + } + + final String signatureManifestCheckCode = XPathUtils + .getElementValue(verifyXmlSignatureResponse, SIGNATURE_MANIFEST_CHECK_CODE_XPATH, null); + if (signatureManifestCheckCode != null) { + respData.setSignatureManifestCheckCode(new Integer(signatureManifestCheckCode).intValue()); + + } + respData.setCertificateCheckCode(new Integer( + XPathUtils.getElementValue(verifyXmlSignatureResponse, CERTIFICATE_CHECK_CODE_XPATH, "")) + .intValue()); + + final String signingTimeElement = + XPathUtils.getElementValue(verifyXmlSignatureResponse, SIGNING_TIME_XPATH, ""); + if (signingTimeElement != null && !signingTimeElement.isEmpty()) { + final DateTime datetime = + ISODateTimeFormat.dateOptionalTimeParser().parseDateTime(signingTimeElement); + respData.setSigningDateTime(datetime.toDate()); + + } + + return respData; + + } catch (final Throwable t) { + log.warn("Can not parse MOA-Sig response.", t); + throw new MoaSigServiceParserException("service.moasig.02", new Object[] {t.toString()}, t); + } + + } + + +} diff --git a/eaaf_modules/eaaf_module_moa-sig/src/main/resources/moa-sig-service.beans.xml b/eaaf_modules/eaaf_module_moa-sig/src/main/resources/moa-sig-service.beans.xml index 60b75f3c..c5e05853 100644 --- a/eaaf_modules/eaaf_module_moa-sig/src/main/resources/moa-sig-service.beans.xml +++ b/eaaf_modules/eaaf_module_moa-sig/src/main/resources/moa-sig-service.beans.xml @@ -1,25 +1,25 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:context="http://www.springframework.org/schema/context" + xmlns:tx="http://www.springframework.org/schema/tx" + xmlns:aop="http://www.springframework.org/schema/aop" + xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd + http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> - + + + + + + + - - - - - - \ No newline at end of file diff --git a/eaaf_modules/eaaf_module_moa-sig/src/test/java/artifacts/MavenArtifactInstaller.java b/eaaf_modules/eaaf_module_moa-sig/src/test/java/artifacts/MavenArtifactInstaller.java index 7b9e2748..11c84ec0 100644 --- a/eaaf_modules/eaaf_module_moa-sig/src/test/java/artifacts/MavenArtifactInstaller.java +++ b/eaaf_modules/eaaf_module_moa-sig/src/test/java/artifacts/MavenArtifactInstaller.java @@ -6,54 +6,65 @@ import java.text.MessageFormat; public class MavenArtifactInstaller { - public static final String MVN_INSTALL_PATH = "F:\\local_work\\program\\apache-maven-3.5.2-bin\\bin\\"; - public static final String CONFIG = "/settings.xml"; - public static final String REPO_SCAN_PATH = "/repository/iaik/prod"; - - public static final String GROUP = "iaik.prod"; - public static final String PACKAGE = "jar"; - public static final String COMMAND_TEMPLATE = "{6}mvn.cmd install:install-file -s {0} -DgroupId={1} -DartifactId={2} -Dversion={3} -Dpackaging={4} -Dfile={5}"; - - public static void main(String[] args) { - String currentLocation = new java.io.File( "." ).toURI().toString(); - currentLocation = currentLocation.substring("file:/".length(), currentLocation.length() - 2); - final String settingLocation = currentLocation + CONFIG; - final File settingsFile = new File(settingLocation); - if (!settingsFile.exists()) { - System.out.println("Maven settings does not exist"); - System.exit(-1); - - } - - final String pathToScan = currentLocation + REPO_SCAN_PATH; - - final File toScan = new File(pathToScan); - - int counter=0; - for (final File dir : toScan.listFiles()) { - final String artifactName = dir.getName(); - for (final File version : dir.listFiles()) { - final String libVersion = version.getName(); - final String jarPath = version.getAbsolutePath() + "/" + artifactName + "-" + libVersion + ".jar"; - final File jar = new File(jarPath ); - if (jar.exists()) { - final String mvnCommand = MessageFormat.format(COMMAND_TEMPLATE, settingsFile.getAbsoluteFile(), GROUP, artifactName, libVersion, PACKAGE, jar.getAbsolutePath(), MVN_INSTALL_PATH); - System.out.println("Execute: " + mvnCommand); - try { - Runtime.getRuntime().exec(mvnCommand); - counter++; - } catch (final IOException e) { - e.printStackTrace(); - - } - - } else - System.out.print("Can NOT find jar with path: " + jarPath); - - } - - } - System.out.println("Install #" + counter + " maven artifacts"); - } + public static final String MVN_INSTALL_PATH = + "F:\\local_work\\program\\apache-maven-3.5.2-bin\\bin\\"; + public static final String CONFIG = "/settings.xml"; + public static final String REPO_SCAN_PATH = "/repository/iaik/prod"; + + public static final String GROUP = "iaik.prod"; + public static final String PACKAGE = "jar"; + public static final String COMMAND_TEMPLATE = + "{6}mvn.cmd install:install-file -s {0} -DgroupId={1} -DartifactId={2} -Dversion={3} -Dpackaging={4} -Dfile={5}"; + + /** + * Only for test-deployment of maven artifacts. + * + * @param args System parameters + */ + public static void main(final String[] args) { + String currentLocation = new java.io.File(".").toURI().toString(); + currentLocation = currentLocation.substring("file:/".length(), currentLocation.length() - 2); + final String settingLocation = currentLocation + CONFIG; + final File settingsFile = new File(settingLocation); + if (!settingsFile.exists()) { + System.out.println("Maven settings does not exist"); + System.exit(-1); + + } + + final String pathToScan = currentLocation + REPO_SCAN_PATH; + + final File toScan = new File(pathToScan); + + int counter = 0; + for (final File dir : toScan.listFiles()) { + final String artifactName = dir.getName(); + for (final File version : dir.listFiles()) { + final String libVersion = version.getName(); + final String jarPath = + version.getAbsolutePath() + "/" + artifactName + "-" + libVersion + ".jar"; + final File jar = new File(jarPath); + if (jar.exists()) { + final String mvnCommand = + MessageFormat.format(COMMAND_TEMPLATE, settingsFile.getAbsoluteFile(), GROUP, + artifactName, libVersion, PACKAGE, jar.getAbsolutePath(), MVN_INSTALL_PATH); + System.out.println("Execute: " + mvnCommand); + try { + Runtime.getRuntime().exec(mvnCommand); + counter++; + } catch (final IOException e) { + e.printStackTrace(); + + } + + } else { + System.out.print("Can NOT find jar with path: " + jarPath); + } + + } + + } + System.out.println("Install #" + counter + " maven artifacts"); + } } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/PVP2SProfileCoreSpringResourceProvider.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/PVP2SProfileCoreSpringResourceProvider.java deleted file mode 100644 index c72db697..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/PVP2SProfileCoreSpringResourceProvider.java +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2; - -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; - -import at.gv.egiz.components.spring.api.SpringResourceProvider; - -public class PVP2SProfileCoreSpringResourceProvider implements SpringResourceProvider { - - @Override - public String getName() { - return "EAAF PVP2 S-Profile Core SpringResourceProvider"; - } - - @Override - public String[] getPackagesToScan() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Resource[] getResourcesToLoad() { - ClassPathResource sl20AuthConfig = new ClassPathResource("/eaaf_pvp.beans.xml", PVP2SProfileCoreSpringResourceProvider.class); - - return new Resource[] {sl20AuthConfig}; - } - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/PVPConstants.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/PVPConstants.java deleted file mode 100644 index 3b57a7e3..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/PVPConstants.java +++ /dev/null @@ -1,139 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.xml.namespace.QName; - -import org.opensaml.xml.encryption.EncryptionConstants; -import org.opensaml.xml.signature.SignatureConstants; - -import at.gv.egiz.eaaf.core.api.data.PVPAttributeDefinitions; -import at.gv.egiz.eaaf.core.impl.data.Trible; - -public interface PVPConstants extends PVPAttributeDefinitions { - - public static final String DEFAULT_SIGNING_METHODE = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256; - public static final String DEFAULT_DIGESTMETHODE = SignatureConstants.ALGO_ID_DIGEST_SHA256; - public static final String DEFAULT_SYM_ENCRYPTION_METHODE = EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256; - public static final String DEFAULT_ASYM_ENCRYPTION_METHODE = EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP; - - public static final String ENTITY_CATEGORY_ATTRIBITE = "http://macedir.org/entity-category"; - public static final String EGOVTOKEN = "http://www.ref.gv.at/ns/names/agiz/pvp/egovtoken"; - public static final String CITIZENTOKEN = "http://www.ref.gv.at/ns/names/agiz/pvp/citizentoken"; - - @Deprecated - public static final String STORK_ATTRIBUTE_PREFIX = "http://www.stork.gov.eu/"; - - public static final String REDIRECT = "Redirect"; - public static final String POST = "Post"; - public static final String SOAP = "Soap"; - public static final String METADATA = "Metadata"; - public static final String ATTRIBUTEQUERY = "AttributeQuery"; - public static final String SINGLELOGOUT = "SingleLogOut"; - - /** - * - * Get required PVP attributes for egovtoken - * First : PVP attribute name (OID) - * Second: FriendlyName - * Third: Required - * - */ - public static final List> EGOVTOKEN_PVP_ATTRIBUTES = - Collections.unmodifiableList(new ArrayList>() { - private static final long serialVersionUID = 1L; - { - //currently supported attributes - add(Trible.newInstance(PVP_VERSION_NAME, PVP_VERSION_FRIENDLY_NAME, true)); - add(Trible.newInstance(PRINCIPAL_NAME_NAME, PRINCIPAL_NAME_FRIENDLY_NAME, true)); - - //currently not supported attributes - add(Trible.newInstance(USERID_NAME, USERID_FRIENDLY_NAME, false)); - add(Trible.newInstance(GID_NAME, GID_FRIENDLY_NAME, false)); - add(Trible.newInstance(PARTICIPANT_ID_NAME, PARTICIPANT_ID_FRIENDLY_NAME, false)); - add(Trible.newInstance(OU_GV_OU_ID_NAME, OU_GV_OU_ID_FRIENDLY_NAME, false)); - add(Trible.newInstance(OU_NAME, OU_FRIENDLY_NAME, false)); - add(Trible.newInstance(SECCLASS_NAME, SECCLASS_FRIENDLY_NAME, false)); - - - } - }); - - /** - * - * Get required PVP attributes for citizenToken - * First : PVP attribute name (OID) - * Second: FriendlyName - * Third: Required - * - */ - public static final List> CITIZENTOKEN_PVP_ATTRIBUTES = - Collections.unmodifiableList(new ArrayList>() { - private static final long serialVersionUID = 1L; - { - //required attributes - eIDAS minimal-data set - add(Trible.newInstance(PVP_VERSION_NAME, PVP_VERSION_FRIENDLY_NAME, true)); - add(Trible.newInstance(PRINCIPAL_NAME_NAME, PRINCIPAL_NAME_FRIENDLY_NAME, true)); - add(Trible.newInstance(GIVEN_NAME_NAME, GIVEN_NAME_FRIENDLY_NAME, true)); - add(Trible.newInstance(BIRTHDATE_NAME, BIRTHDATE_FRIENDLY_NAME, true)); - add(Trible.newInstance(BPK_NAME, BPK_FRIENDLY_NAME, true)); - - - //not required attributes - add(Trible.newInstance(EID_CITIZEN_EIDAS_QAA_LEVEL_NAME, EID_CITIZEN_EIDAS_QAA_LEVEL_FRIENDLY_NAME, false)); - add(Trible.newInstance(EID_ISSUING_NATION_NAME, EID_ISSUING_NATION_FRIENDLY_NAME, false)); - add(Trible.newInstance(EID_SECTOR_FOR_IDENTIFIER_NAME, EID_SECTOR_FOR_IDENTIFIER_FRIENDLY_NAME, false)); - add(Trible.newInstance(MANDATE_TYPE_NAME, MANDATE_TYPE_FRIENDLY_NAME, false)); - add(Trible.newInstance(MANDATE_TYPE_OID_NAME, MANDATE_TYPE_OID_FRIENDLY_NAME, false)); - add(Trible.newInstance(MANDATE_LEG_PER_SOURCE_PIN_NAME, MANDATE_LEG_PER_SOURCE_PIN_FRIENDLY_NAME, false)); - add(Trible.newInstance(MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME, MANDATE_LEG_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME, false)); - add(Trible.newInstance(MANDATE_NAT_PER_BPK_NAME, MANDATE_NAT_PER_BPK_FRIENDLY_NAME, false)); - add(Trible.newInstance(MANDATE_NAT_PER_GIVEN_NAME_NAME, MANDATE_NAT_PER_GIVEN_NAME_FRIENDLY_NAME, false)); - add(Trible.newInstance(MANDATE_NAT_PER_FAMILY_NAME_NAME, MANDATE_NAT_PER_FAMILY_NAME_FRIENDLY_NAME, false)); - add(Trible.newInstance(MANDATE_NAT_PER_BIRTHDATE_NAME, MANDATE_NAT_PER_BIRTHDATE_FRIENDLY_NAME, false)); - add(Trible.newInstance(MANDATE_LEG_PER_FULL_NAME_NAME, MANDATE_LEG_PER_FULL_NAME_FRIENDLY_NAME, false)); - add(Trible.newInstance(MANDATE_PROF_REP_OID_NAME, MANDATE_PROF_REP_OID_FRIENDLY_NAME, false)); - add(Trible.newInstance(MANDATE_PROF_REP_DESC_NAME, MANDATE_PROF_REP_DESC_FRIENDLY_NAME, false)); - add(Trible.newInstance(MANDATE_REFERENCE_VALUE_NAME, MANDATE_REFERENCE_VALUE_FRIENDLY_NAME, false)); - - - - } - }); - - //constants for requested SAML2 attribtes by using own namespace - public static final String EIDAT10_SAML_NS = "http://eid.gv.at/eID/attributes/saml-extensions"; - public static final String EIDAT10_PREFIX = "eid"; - - public static final QName EIDAS_REQUESTED_ATTRIBUTE_VALUE_TYPE = - new QName(EIDAT10_SAML_NS, "AttributeValue", EIDAT10_PREFIX); - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/PVPEventConstants.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/PVPEventConstants.java deleted file mode 100644 index d1f619bf..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/PVPEventConstants.java +++ /dev/null @@ -1,36 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2; - -public class PVPEventConstants { - - //TODO!!! - public static final int AUTHPROTOCOL_PVP_METADATA = 3100; - public static final int AUTHPROTOCOL_PVP_REQUEST_AUTHREQUEST = 3101; - public static final int AUTHPROTOCOL_PVP_RESPONSE_ASSERTION = 3105; - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/Pvp2SProfileCoreSpringResourceProvider.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/Pvp2SProfileCoreSpringResourceProvider.java new file mode 100644 index 00000000..c0482c9d --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/Pvp2SProfileCoreSpringResourceProvider.java @@ -0,0 +1,48 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; + +import at.gv.egiz.components.spring.api.SpringResourceProvider; + +public class Pvp2SProfileCoreSpringResourceProvider implements SpringResourceProvider { + + @Override + public String getName() { + return "EAAF PVP2 S-Profile Core SpringResourceProvider"; + } + + @Override + public String[] getPackagesToScan() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Resource[] getResourcesToLoad() { + final ClassPathResource sl20AuthConfig = + new ClassPathResource("/eaaf_pvp.beans.xml", Pvp2SProfileCoreSpringResourceProvider.class); + + return new Resource[] {sl20AuthConfig}; + } + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/PvpConstants.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/PvpConstants.java new file mode 100644 index 00000000..e8d42e80 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/PvpConstants.java @@ -0,0 +1,138 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import javax.xml.namespace.QName; +import at.gv.egiz.eaaf.core.api.data.PVPAttributeDefinitions; +import at.gv.egiz.eaaf.core.impl.data.Trible; +import org.opensaml.xml.encryption.EncryptionConstants; +import org.opensaml.xml.signature.SignatureConstants; + +public interface PvpConstants extends PVPAttributeDefinitions { + + public static final String DEFAULT_SIGNING_METHODE = + SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256; + public static final String DEFAULT_DIGESTMETHODE = SignatureConstants.ALGO_ID_DIGEST_SHA256; + public static final String DEFAULT_SYM_ENCRYPTION_METHODE = + EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256; + public static final String DEFAULT_ASYM_ENCRYPTION_METHODE = + EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP; + + public static final String ENTITY_CATEGORY_ATTRIBITE = "http://macedir.org/entity-category"; + public static final String EGOVTOKEN = "http://www.ref.gv.at/ns/names/agiz/pvp/egovtoken"; + public static final String CITIZENTOKEN = "http://www.ref.gv.at/ns/names/agiz/pvp/citizentoken"; + + @Deprecated + public static final String STORK_ATTRIBUTE_PREFIX = "http://www.stork.gov.eu/"; + + public static final String REDIRECT = "Redirect"; + public static final String POST = "Post"; + public static final String SOAP = "Soap"; + public static final String METADATA = "Metadata"; + public static final String ATTRIBUTEQUERY = "AttributeQuery"; + public static final String SINGLELOGOUT = "SingleLogOut"; + + /** + * Get required PVP attributes for egovtoken First : PVP attribute name (OID) Second: FriendlyName + * Third: Required. + * + */ + public static final List> EGOVTOKEN_PVP_ATTRIBUTES = + Collections.unmodifiableList(new ArrayList>() { + private static final long serialVersionUID = 1L; + { + // currently supported attributes + add(Trible.newInstance(PVP_VERSION_NAME, PVP_VERSION_FRIENDLY_NAME, true)); + add(Trible.newInstance(PRINCIPAL_NAME_NAME, PRINCIPAL_NAME_FRIENDLY_NAME, true)); + + // currently not supported attributes + add(Trible.newInstance(USERID_NAME, USERID_FRIENDLY_NAME, false)); + add(Trible.newInstance(GID_NAME, GID_FRIENDLY_NAME, false)); + add(Trible.newInstance(PARTICIPANT_ID_NAME, PARTICIPANT_ID_FRIENDLY_NAME, false)); + add(Trible.newInstance(OU_GV_OU_ID_NAME, OU_GV_OU_ID_FRIENDLY_NAME, false)); + add(Trible.newInstance(OU_NAME, OU_FRIENDLY_NAME, false)); + add(Trible.newInstance(SECCLASS_NAME, SECCLASS_FRIENDLY_NAME, false)); + + + } + }); + + /** + * Get required PVP attributes for citizenToken First : PVP attribute name (OID) Second: + * FriendlyName Third: Required. + * + */ + public static final List> CITIZENTOKEN_PVP_ATTRIBUTES = + Collections.unmodifiableList(new ArrayList>() { + private static final long serialVersionUID = 1L; + { + // required attributes - eIDAS minimal-data set + add(Trible.newInstance(PVP_VERSION_NAME, PVP_VERSION_FRIENDLY_NAME, true)); + add(Trible.newInstance(PRINCIPAL_NAME_NAME, PRINCIPAL_NAME_FRIENDLY_NAME, true)); + add(Trible.newInstance(GIVEN_NAME_NAME, GIVEN_NAME_FRIENDLY_NAME, true)); + add(Trible.newInstance(BIRTHDATE_NAME, BIRTHDATE_FRIENDLY_NAME, true)); + add(Trible.newInstance(BPK_NAME, BPK_FRIENDLY_NAME, true)); + + + // not required attributes + add(Trible.newInstance(EID_CITIZEN_EIDAS_QAA_LEVEL_NAME, + EID_CITIZEN_EIDAS_QAA_LEVEL_FRIENDLY_NAME, false)); + add(Trible.newInstance(EID_ISSUING_NATION_NAME, EID_ISSUING_NATION_FRIENDLY_NAME, false)); + add(Trible.newInstance(EID_SECTOR_FOR_IDENTIFIER_NAME, + EID_SECTOR_FOR_IDENTIFIER_FRIENDLY_NAME, false)); + add(Trible.newInstance(MANDATE_TYPE_NAME, MANDATE_TYPE_FRIENDLY_NAME, false)); + add(Trible.newInstance(MANDATE_TYPE_OID_NAME, MANDATE_TYPE_OID_FRIENDLY_NAME, false)); + add(Trible.newInstance(MANDATE_LEG_PER_SOURCE_PIN_NAME, + MANDATE_LEG_PER_SOURCE_PIN_FRIENDLY_NAME, false)); + add(Trible.newInstance(MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME, + MANDATE_LEG_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME, false)); + add(Trible.newInstance(MANDATE_NAT_PER_BPK_NAME, MANDATE_NAT_PER_BPK_FRIENDLY_NAME, + false)); + add(Trible.newInstance(MANDATE_NAT_PER_GIVEN_NAME_NAME, + MANDATE_NAT_PER_GIVEN_NAME_FRIENDLY_NAME, false)); + add(Trible.newInstance(MANDATE_NAT_PER_FAMILY_NAME_NAME, + MANDATE_NAT_PER_FAMILY_NAME_FRIENDLY_NAME, false)); + add(Trible.newInstance(MANDATE_NAT_PER_BIRTHDATE_NAME, + MANDATE_NAT_PER_BIRTHDATE_FRIENDLY_NAME, false)); + add(Trible.newInstance(MANDATE_LEG_PER_FULL_NAME_NAME, + MANDATE_LEG_PER_FULL_NAME_FRIENDLY_NAME, false)); + add(Trible.newInstance(MANDATE_PROF_REP_OID_NAME, MANDATE_PROF_REP_OID_FRIENDLY_NAME, + false)); + add(Trible.newInstance(MANDATE_PROF_REP_DESC_NAME, MANDATE_PROF_REP_DESC_FRIENDLY_NAME, + false)); + add(Trible.newInstance(MANDATE_REFERENCE_VALUE_NAME, + MANDATE_REFERENCE_VALUE_FRIENDLY_NAME, false)); + + + + } + }); + + // constants for requested SAML2 attribtes by using own namespace + public static final String EIDAT10_SAML_NS = "http://eid.gv.at/eID/attributes/saml-extensions"; + public static final String EIDAT10_PREFIX = "eid"; + + public static final QName EIDAS_REQUESTED_ATTRIBUTE_VALUE_TYPE = + new QName(EIDAT10_SAML_NS, "AttributeValue", EIDAT10_PREFIX); + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/PvpEventConstants.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/PvpEventConstants.java new file mode 100644 index 00000000..41b64470 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/PvpEventConstants.java @@ -0,0 +1,29 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2; + +public class PvpEventConstants { + + // TODO!!! + public static final int AUTHPROTOCOL_PVP_METADATA = 3100; + public static final int AUTHPROTOCOL_PVP_REQUEST_AUTHREQUEST = 3101; + public static final int AUTHPROTOCOL_PVP_RESPONSE_ASSERTION = 3105; + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/IPVP2BasicConfiguration.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/IPVP2BasicConfiguration.java deleted file mode 100644 index 48b0efc5..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/IPVP2BasicConfiguration.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.api; - -import java.util.List; - -import org.opensaml.saml2.metadata.ContactPerson; -import org.opensaml.saml2.metadata.Organization; - -import at.gv.egiz.eaaf.core.exceptions.EAAFException; - -public interface IPVP2BasicConfiguration { - - public String getIDPEntityId(String authURL) throws EAAFException; - - public String getIDPSSOPostService(String authURL) throws EAAFException; - - public String getIDPSSORedirectService(String authURL) throws EAAFException; - - public Object getIDPSSOSOAPService(String extractAuthURLFromRequest) throws EAAFException; - - public List getIDPContacts() throws EAAFException; - - public Organization getIDPOrganisation() throws EAAFException; - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/IPvo2BasicConfiguration.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/IPvo2BasicConfiguration.java new file mode 100644 index 00000000..39c0baff --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/IPvo2BasicConfiguration.java @@ -0,0 +1,41 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.api; + +import java.util.List; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import org.opensaml.saml2.metadata.ContactPerson; +import org.opensaml.saml2.metadata.Organization; + +public interface IPvo2BasicConfiguration { + + String getIdpEntityId(String authUrl) throws EaafException; + + String getIdpSsoPostService(String authUrl) throws EaafException; + + String getIdpSsoRedirectService(String authUrl) throws EaafException; + + Object getIspSsoSoapService(String extractAuthUrlFromRequest) throws EaafException; + + List getIdpContacts() throws EaafException; + + Organization getIdpOrganisation() throws EaafException; + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/binding/IDecoder.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/binding/IDecoder.java index 3b264b6d..27a6532b 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/binding/IDecoder.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/binding/IDecoder.java @@ -1,49 +1,40 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.api.binding; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - +import at.gv.egiz.eaaf.modules.pvp2.api.message.InboundMessageInterface; +import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2Exception; import org.opensaml.common.binding.decoding.URIComparator; import org.opensaml.saml2.metadata.provider.MetadataProvider; import org.opensaml.ws.message.decoder.MessageDecodingException; import org.opensaml.xml.security.SecurityException; -import at.gv.egiz.eaaf.modules.pvp2.api.message.InboundMessageInterface; -import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; - public interface IDecoder { - public InboundMessageInterface decode(HttpServletRequest req, - HttpServletResponse resp, MetadataProvider metadataProvider, boolean isSPEndPoint, URIComparator comparator) - throws MessageDecodingException, SecurityException, PVP2Exception; - - public boolean handleDecode(String action, HttpServletRequest req); - - public String getSAML2BindingName(); + public InboundMessageInterface decode(HttpServletRequest req, HttpServletResponse resp, + MetadataProvider metadataProvider, boolean isSpEndPoint, URIComparator comparator) + throws MessageDecodingException, SecurityException, Pvp2Exception; + + public boolean handleDecode(String action, HttpServletRequest req); + + public String getSaml2BindingName(); } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/binding/IEncoder.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/binding/IEncoder.java index ec400e7a..9d8b0105 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/binding/IEncoder.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/binding/IEncoder.java @@ -1,75 +1,70 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.api.binding; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2Exception; import org.opensaml.saml2.core.RequestAbstractType; import org.opensaml.saml2.core.StatusResponseType; import org.opensaml.ws.message.encoder.MessageEncodingException; import org.opensaml.xml.security.SecurityException; import org.opensaml.xml.security.credential.Credential; -import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; - public interface IEncoder { - - /** - * - * @param req The http request - * @param resp The http response - * @param request The SAML2 request object - * @param targetLocation URL, where the request should be transmit - * @param relayState token for session handling - * @param credentials Credential to sign the request object - * @param pendingReq Internal MOA-ID request object that contains session-state informations but never null - * @throws MessageEncodingException - * @throws SecurityException - * @throws PVP2Exception - */ - public void encodeRequest(HttpServletRequest req, - HttpServletResponse resp, RequestAbstractType request, String targetLocation, String relayState, Credential credentials, IRequest pendingReq) - throws MessageEncodingException, SecurityException, PVP2Exception; - - /** - * Encoder SAML Response - * @param req The http request - * @param resp The http response - * @param response The SAML2 repsonse object - * @param targetLocation URL, where the request should be transmit - * @param relayState token for session handling - * @param credentials Credential to sign the response object - * @param pendingReq Internal MOA-ID request object that contains session-state informations but never null - * @throws MessageEncodingException - * @throws SecurityException - */ - public void encodeRespone(HttpServletRequest req, - HttpServletResponse resp, StatusResponseType response, String targetLocation, String relayState, Credential credentials, IRequest pendingReq) - throws MessageEncodingException, SecurityException, PVP2Exception; + + /** + * SAML2 Request encoder. + * + * @param req The http request + * @param resp The http response + * @param request The SAML2 request object + * @param targetLocation URL, where the request should be transmit + * @param relayState token for session handling + * @param credentials Credential to sign the request object + * @param pendingReq Internal MOA-ID request object that contains session-state informations but + * never null + * @throws MessageEncodingException In case of an error + * @throws SecurityException In case of an error + * @throws Pvp2Exception In case of an error + */ + void encodeRequest(HttpServletRequest req, HttpServletResponse resp, + RequestAbstractType request, String targetLocation, String relayState, Credential credentials, + IRequest pendingReq) throws MessageEncodingException, SecurityException, Pvp2Exception; + + /** + * Encoder SAML Response. + * + * @param req The http request + * @param resp The http response + * @param response The SAML2 repsonse object + * @param targetLocation URL, where the request should be transmit + * @param relayState token for session handling + * @param credentials Credential to sign the response object + * @param pendingReq Internal MOA-ID request object that contains session-state informations but + * never null + * @throws MessageEncodingException In case of an error + * @throws SecurityException In case of an error + */ + void encodeRespone(HttpServletRequest req, HttpServletResponse resp, + StatusResponseType response, String targetLocation, String relayState, Credential credentials, + IRequest pendingReq) throws MessageEncodingException, SecurityException, Pvp2Exception; } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/message/InboundMessageInterface.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/message/InboundMessageInterface.java index 416672a1..e5b253a2 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/message/InboundMessageInterface.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/message/InboundMessageInterface.java @@ -1,42 +1,34 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.api.message; import org.w3c.dom.Element; -/** - * @author tlenz - * - */ public interface InboundMessageInterface { - - public String getRelayState(); - public String getEntityID(); - public boolean isVerified(); - public Element getInboundMessage(); - + + String getRelayState(); + + String getEntityID(); + + boolean isVerified(); + + Element getInboundMessage(); + } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IPVPMetadataBuilderConfiguration.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IPVPMetadataBuilderConfiguration.java deleted file mode 100644 index c041ec72..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IPVPMetadataBuilderConfiguration.java +++ /dev/null @@ -1,243 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.api.metadata; - -import java.util.Collection; -import java.util.List; - -import org.opensaml.saml2.core.Attribute; -import org.opensaml.saml2.metadata.ContactPerson; -import org.opensaml.saml2.metadata.Organization; -import org.opensaml.saml2.metadata.RequestedAttribute; -import org.opensaml.xml.security.credential.Credential; - -import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException; - -/** - * @author tlenz - * - */ -public interface IPVPMetadataBuilderConfiguration { - - - /** - * Defines a unique name for this PVP Service-provider, which is used for logging - * - * @return - */ - public String getSPNameForLogging(); - - /** - * Set metadata valid area - * - * @return valid until in hours [h] - */ - public int getMetadataValidUntil(); - - /** - * Build a SAML2 Entities element as metadata root element - * - * @return true, if the metadata should start with entities element - */ - public boolean buildEntitiesDescriptorAsRootElement(); - - /** - * - * - * @return true, if an IDP SSO-descriptor element should be generated - */ - public boolean buildIDPSSODescriptor(); - - /** - * - * - * @return true, if an SP SSO-descriptor element should be generated - */ - public boolean buildSPSSODescriptor(); - - /** - * Set the PVP entityID for this SAML2 metadata. - * The entityID must be an URL and must be start with the public-URL prefix of the server - * - * @return PVP entityID postfix as String - */ - public String getEntityID(); - - /** - * Set a friendlyName for this PVP entity - * - * @return - */ - public String getEntityFriendlyName(); - - /** - * Set the contact information for this metadata entity - * - * @return - */ - public List getContactPersonInformation(); - - /** - * Set organisation information for this metadata entity - * - * @return - */ - public Organization getOrgansiationInformation(); - - - /** - * Set the credential for metadata signing - * - * @return - * @throws CredentialsNotAvailableException - */ - public Credential getMetadataSigningCredentials() throws CredentialsNotAvailableException; - - /** - * Set the credential for request/response signing - * IDP metadata: this credential is used for SAML2 response signing - * SP metadata: this credential is used for SAML2 response signing - * - * @return - * @throws CredentialsNotAvailableException - */ - public Credential getRequestorResponseSigningCredentials() throws CredentialsNotAvailableException; - - /** - * Set the credential for response encryption - * - * @return - * @throws CredentialsNotAvailableException - */ - public Credential getEncryptionCredentials() throws CredentialsNotAvailableException; - - /** - * Set the IDP Post-Binding URL for WebSSO - * - * @return - */ - public String getIDPWebSSOPostBindingURL(); - - /** - * Set the IDP Redirect-Binding URL for WebSSO - * - * @return - */ - public String getIDPWebSSORedirectBindingURL(); - - /** - * Set the IDP Post-Binding URL for Single LogOut - * - * @return - */ - public String getIDPSLOPostBindingURL(); - - /** - * Set the IDP Redirect-Binding URL for Single LogOut - * - * @return - */ - public String getIDPSLORedirectBindingURL(); - - /** - * Set the SP Post-Binding URL for for the Assertion-Consumer Service - * - * @return - */ - public String getSPAssertionConsumerServicePostBindingURL(); - - /** - * Set the SP Redirect-Binding URL for the Assertion-Consumer Service - * - * @return - */ - public String getSPAssertionConsumerServiceRedirectBindingURL(); - - /** - * Set the SP Post-Binding URL for Single LogOut - * - * @return - */ - public String getSPSLOPostBindingURL(); - - /** - * Set the SP Redirect-Binding URL for Single LogOut - * - * @return - */ - public String getSPSLORedirectBindingURL(); - - /** - * Set the SP SOAP-Binding URL for Single LogOut - * - * @return - */ - public String getSPSLOSOAPBindingURL(); - - - /** - * Set all SAML2 attributes which could be provided by this IDP - * - * @return - */ - public List getIDPPossibleAttributes(); - - /** - * Set all nameID types which could be provided by this IDP - * - * @return a List of SAML2 nameID types - */ - public List getIDPPossibleNameITTypes(); - - /** - * Set all SAML2 attributes which are required by the SP - * - * @return - */ - public Collection getSPRequiredAttributes(); - - /** - * Set all nameID types which allowed from the SP - * - * @return a List of SAML2 nameID types - */ - public List getSPAllowedNameITTypes(); - - /** - * Set the 'wantAssertionSigned' attribute in SP metadata - * - * @return - */ - public boolean wantAssertionSigned(); - - /** - * Set the 'wantAuthnRequestSigned' attribute - * - * @return - */ - public boolean wantAuthnRequestSigned(); -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IPVPMetadataConfigurationFactory.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IPVPMetadataConfigurationFactory.java deleted file mode 100644 index be36a878..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IPVPMetadataConfigurationFactory.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.api.metadata; - -import at.gv.egiz.eaaf.modules.pvp2.impl.utils.AbstractCredentialProvider; - -public interface IPVPMetadataConfigurationFactory { - - public IPVPMetadataBuilderConfiguration generateMetadataBuilderConfiguration(String authURL, AbstractCredentialProvider pvpIDPCredentials); - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IPVPMetadataProvider.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IPVPMetadataProvider.java deleted file mode 100644 index f5c6a35a..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IPVPMetadataProvider.java +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.api.metadata; - -import java.util.List; - -import javax.xml.namespace.QName; - -import org.opensaml.saml2.metadata.EntitiesDescriptor; -import org.opensaml.saml2.metadata.EntityDescriptor; -import org.opensaml.saml2.metadata.RoleDescriptor; -import org.opensaml.saml2.metadata.provider.MetadataFilter; -import org.opensaml.saml2.metadata.provider.MetadataProvider; -import org.opensaml.saml2.metadata.provider.MetadataProviderException; -import org.opensaml.xml.XMLObject; - -public interface IPVPMetadataProvider extends MetadataProvider { - - boolean requireValidMetadata(); - - void setRequireValidMetadata(boolean requireValidMetadata); - - MetadataFilter getMetadataFilter(); - - void setMetadataFilter(MetadataFilter newFilter) throws MetadataProviderException; - - XMLObject getMetadata() throws MetadataProviderException; - - EntitiesDescriptor getEntitiesDescriptor(String entitiesID) throws MetadataProviderException; - - EntityDescriptor getEntityDescriptor(String entityID) throws MetadataProviderException; - - List getRole(String entityID, QName roleName) throws MetadataProviderException; - - RoleDescriptor getRole(String entityID, QName roleName, String supportedProtocol) throws MetadataProviderException; - -} \ No newline at end of file diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IPvpMetadataBuilderConfiguration.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IPvpMetadataBuilderConfiguration.java new file mode 100644 index 00000000..f06a1684 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IPvpMetadataBuilderConfiguration.java @@ -0,0 +1,236 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.api.metadata; + +import java.util.Collection; +import java.util.List; +import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException; +import org.opensaml.saml2.core.Attribute; +import org.opensaml.saml2.metadata.ContactPerson; +import org.opensaml.saml2.metadata.Organization; +import org.opensaml.saml2.metadata.RequestedAttribute; +import org.opensaml.xml.security.credential.Credential; + +/** + * PVP Metadata builder configuration. + * + * @author tlenz + * + */ +public interface IPvpMetadataBuilderConfiguration { + + + /** + * Defines a unique name for this PVP Service-provider, which is used for logging. + * + * @return + */ + String getSpNameForLogging(); + + /** + * Set metadata valid area. + * + * @return valid until in hours [h] + */ + int getMetadataValidUntil(); + + /** + * Build a SAML2 Entities element as metadata root element. + * + * @return true, if the metadata should start with entities element + */ + boolean buildEntitiesDescriptorAsRootElement(); + + /** + * Build an IDP SSO Descriptor. + * + * @return true, if an IDP SSO-descriptor element should be generated + */ + boolean buildIdpSsoDescriptor(); + + /** + * Build a SP Descriptor. + * + * @return true, if an SP SSO-descriptor element should be generated + */ + boolean buildSpSsoDescriptor(); + + /** + * Set the PVP entityID for this SAML2 metadata. The entityID must be an URL and must be start + * with the public-URL prefix of the server. + * + * @return PVP entityID postfix as String + */ + String getEntityID(); + + /** + * Set a friendlyName for this PVP entity. + * + * @return + */ + String getEntityFriendlyName(); + + /** + * Set the contact information for this metadata entity. + * + * @return + */ + List getContactPersonInformation(); + + /** + * Set organisation information for this metadata entity. + * + * @return + */ + Organization getOrgansiationInformation(); + + + /** + * Set the credential for metadata signing. + * + * @return Credentials + * @throws CredentialsNotAvailableException In case of an error + */ + Credential getMetadataSigningCredentials() throws CredentialsNotAvailableException; + + /** + * Set the credential for request/response signing IDP metadata: this credential is used for SAML2 + * response signing SP metadata: this credential is used for SAML2 response signing. + * + * @return Credentials + * @throws CredentialsNotAvailableException In case of an error + */ + Credential getRequestorResponseSigningCredentials() + throws CredentialsNotAvailableException; + + /** + * Set the credential for response encryption. + * + * @return Credentials + * @throws CredentialsNotAvailableException In case of an error + */ + Credential getEncryptionCredentials() throws CredentialsNotAvailableException; + + /** + * Set the IDP Post-Binding URL for WebSSO. + * + * @return + */ + String getIdpWebSsoPostBindingUrl(); + + /** + * Set the IDP Redirect-Binding URL for WebSSO. + * + * @return + */ + String getIdpWebSsoRedirectBindingUrl(); + + /** + * Set the IDP Post-Binding URL for Single LogOut. + * + * @return + */ + String getIdpSloPostBindingUrl(); + + /** + * Set the IDP Redirect-Binding URL for Single LogOut. + * + * @return + */ + String getIdpSloRedirectBindingUrl(); + + /** + * Set the SP Post-Binding URL for for the Assertion-Consumer Service. + * + * @return + */ + String getSpAssertionConsumerServicePostBindingUrl(); + + /** + * Set the SP Redirect-Binding URL for the Assertion-Consumer Service. + * + * @return + */ + String getSpAssertionConsumerServiceRedirectBindingUrl(); + + /** + * Set the SP Post-Binding URL for Single LogOut. + * + * @return + */ + String getSpSloPostBindingUrl(); + + /** + * Set the SP Redirect-Binding URL for Single LogOut. + * + * @return + */ + String getSpSloRedirectBindingUrl(); + + /** + * Set the SP SOAP-Binding URL for Single LogOut. + * + * @return + */ + String getSpSloSoapBindingUrl(); + + + /** + * Set all SAML2 attributes which could be provided by this IDP. + * + * @return + */ + List getIdpPossibleAttributes(); + + /** + * Set all nameID types which could be provided by this IDP. + * + * @return a List of SAML2 nameID types + */ + List getIdpPossibleNameIdTypes(); + + /** + * Set all SAML2 attributes which are required by the SP. + * + * @return + */ + Collection getSpRequiredAttributes(); + + /** + * Set all nameID types which allowed from the SP. + * + * @return a List of SAML2 nameID types + */ + List getSpAllowedNameIdTypes(); + + /** + * Set the 'wantAssertionSigned' attribute in SP metadata. + * + * @return + */ + boolean wantAssertionSigned(); + + /** + * Set the 'wantAuthnRequestSigned' attribute. + * + * @return + */ + boolean wantAuthnRequestSigned(); +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IPvpMetadataConfigurationFactory.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IPvpMetadataConfigurationFactory.java new file mode 100644 index 00000000..4207d860 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IPvpMetadataConfigurationFactory.java @@ -0,0 +1,30 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.api.metadata; + +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.AbstractCredentialProvider; + +public interface IPvpMetadataConfigurationFactory { + + + IPvpMetadataBuilderConfiguration generateMetadataBuilderConfiguration(String authUrl, + AbstractCredentialProvider pvpIdpCredentials); + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IPvpMetadataProvider.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IPvpMetadataProvider.java new file mode 100644 index 00000000..bc90ff3f --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IPvpMetadataProvider.java @@ -0,0 +1,64 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.api.metadata; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.saml2.metadata.EntitiesDescriptor; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.saml2.metadata.provider.MetadataFilter; +import org.opensaml.saml2.metadata.provider.MetadataProvider; +import org.opensaml.saml2.metadata.provider.MetadataProviderException; +import org.opensaml.xml.XMLObject; + +public interface IPvpMetadataProvider extends MetadataProvider { + + @Override + boolean requireValidMetadata(); + + @Override + void setRequireValidMetadata(boolean requireValidMetadata); + + @Override + MetadataFilter getMetadataFilter(); + + @Override + void setMetadataFilter(MetadataFilter newFilter) throws MetadataProviderException; + + @Override + XMLObject getMetadata() throws MetadataProviderException; + + @Override + EntitiesDescriptor getEntitiesDescriptor(String entitiesID) throws MetadataProviderException; + + @Override + EntityDescriptor getEntityDescriptor(String entityID) throws MetadataProviderException; + + @Override + List getRole(String entityID, QName roleName) throws MetadataProviderException; + + @Override + RoleDescriptor getRole(String entityID, QName roleName, String supportedProtocol) + throws MetadataProviderException; + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IRefreshableMetadataProvider.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IRefreshableMetadataProvider.java index 2f9e5fea..74ee74de 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IRefreshableMetadataProvider.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/metadata/IRefreshableMetadataProvider.java @@ -1,42 +1,37 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.api.metadata; /** + * Metadata provider that supports dynamic refreshing on external events. + * * @author tlenz * */ public interface IRefreshableMetadataProvider { - /** - * Refresh a entity or load a entity in a metadata provider - * - * @param entityID - * @return true, if refresh is success, otherwise false - */ - public boolean refreshMetadataProvider(String entityID); + /** + * Refresh a entity or load a entity in a metadata provider. + * + * @param entityID EntityId + * @return true, if refresh is success, otherwise false + */ + public boolean refreshMetadataProvider(String entityID); } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/reqattr/EAAFRequestedAttribute.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/reqattr/EAAFRequestedAttribute.java deleted file mode 100644 index 0501a990..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/reqattr/EAAFRequestedAttribute.java +++ /dev/null @@ -1,154 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.api.reqattr; - -import java.util.List; - -import javax.xml.namespace.QName; - -import org.opensaml.common.SAMLObject; -import org.opensaml.xml.AttributeExtensibleXMLObject; -import org.opensaml.xml.XMLObject; -import org.opensaml.xml.schema.XSBooleanValue; - -import at.gv.egiz.eaaf.modules.pvp2.PVPConstants; - -public interface EAAFRequestedAttribute extends SAMLObject, AttributeExtensibleXMLObject , org.opensaml.saml2.metadata.RequestedAttribute{ - - /** Element local name. */ - String DEF_LOCAL_NAME = "RequestedAttribute"; - - /** Local name of the XSI type. */ - String TYPE_LOCAL_NAME = "RequestedAttributeAbstractType"; - - - /** Default element name. */ - QName DEFAULT_ELEMENT_NAME = new QName(PVPConstants.EIDAT10_SAML_NS, DEF_LOCAL_NAME, - PVPConstants.EIDAT10_PREFIX); - - /** QName of the XSI type. */ - QName TYPE_NAME = new QName(PVPConstants.EIDAT10_SAML_NS, TYPE_LOCAL_NAME, - PVPConstants.EIDAT10_PREFIX); - - - - /** NAME_ATTRIB_NAME attribute name. */ - String NAME_ATTRIB_NAME = "Name"; - - /** NAME_FORMAT_ATTRIB_NAME attribute name. */ - String NAME_FORMAT_ATTR = "NameFormat"; - - /** IS_REQUIRED_ATTRIB_NAME attribute name. */ - String IS_REQUIRED_ATTR = "isRequired"; - - /** FRIENDLY_NAME_ATTRIB_NAME attribute name. */ - String FRIENDLY_NAME_ATT = "FriendlyName"; - - /** Unspecified attribute format ID. */ - String UNSPECIFIED = "urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified"; - - /** URI reference attribute format ID. */ - String URI_REFERENCE = "urn:oasis:names:tc:SAML:2.0:attrname-format:uri"; - - /** Basic attribute format ID. */ - String BASIC = "urn:oasis:names:tc:SAML:2.0:attrname-format:basic"; - - /** - * Gets the name. - * - * @return the name - */ - String getName(); - - /** - * Sets the name. - * - * @param name the new name - */ - void setName(String name); - - /** - * Gets the name format. - * - * @return the name format - */ - String getNameFormat(); - - /** - * Sets the name format. - * - * @param nameFormat the new name format - */ - void setNameFormat(String nameFormat); - - /** - * Gets the friendly name. - * - * @return the friendly name - */ - String getFriendlyName(); - - /** - * Sets the friendly name. - * - * @param friendlyName the new friendly name - */ - void setFriendlyName(String friendlyName); - -/* *//** - * Gets the checks if is required. - * - * @return the checks if is required - *//* - String isRequired();*/ - - /** - * Gets the checks if is required xs boolean. - * - * @return the checks if is required xs boolean - */ - String getIsRequiredXSBoolean(); - - /** - * Sets the checks if is required. - * - * @param newIsRequired the new checks if is required - */ - void setIsRequired(String newIsRequired); - - /** - * Gets the attribute values. - * - * @return the attribute values - */ - List getAttributeValues(); - - XSBooleanValue isRequiredXSBoolean(); - - void setIsRequired(Boolean aBoolean); - - void setIsRequired(XSBooleanValue xsBooleanValue); - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/reqattr/EAAFRequestedAttributes.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/reqattr/EAAFRequestedAttributes.java deleted file mode 100644 index 768d5c36..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/reqattr/EAAFRequestedAttributes.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.api.reqattr; - -import java.util.List; - -import javax.xml.namespace.QName; - -import org.opensaml.common.SAMLObject; - -import at.gv.egiz.eaaf.modules.pvp2.PVPConstants; - -public interface EAAFRequestedAttributes extends SAMLObject { - /** The Constant DEFAULT_ELEMENT_LOCAL_NAME. */ - String DEF_LOCAL_NAME = "RequestedAttributes"; - - /** Default element name. */ - QName DEFAULT_ELEMENT_NAME = new QName(PVPConstants.EIDAT10_SAML_NS, DEF_LOCAL_NAME, - PVPConstants.EIDAT10_PREFIX); - - /** Local name of the XSI type. */ - String TYPE_LOCAL_NAME = "RequestedAttributesType"; - - /** QName of the XSI type. */ - QName TYPE_NAME = new QName(PVPConstants.EIDAT10_SAML_NS, TYPE_LOCAL_NAME, - PVPConstants.EIDAT10_PREFIX); - - /** - * Gets the attributes. - * - * @return the attributes - */ - List getAttributes(); -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/reqattr/EaafRequestedAttribute.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/reqattr/EaafRequestedAttribute.java new file mode 100644 index 00000000..f44a545d --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/reqattr/EaafRequestedAttribute.java @@ -0,0 +1,150 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.api.reqattr; + +import java.util.List; +import javax.xml.namespace.QName; +import at.gv.egiz.eaaf.modules.pvp2.PvpConstants; +import org.opensaml.common.SAMLObject; +import org.opensaml.xml.AttributeExtensibleXMLObject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.schema.XSBooleanValue; + +public interface EaafRequestedAttribute extends SAMLObject, AttributeExtensibleXMLObject, + org.opensaml.saml2.metadata.RequestedAttribute { + + /** Element local name. */ + String DEF_LOCAL_NAME = "RequestedAttribute"; + + /** Local name of the XSI type. */ + String TYPE_LOCAL_NAME = "RequestedAttributeAbstractType"; + + + /** Default element name. */ + QName DEFAULT_ELEMENT_NAME = + new QName(PvpConstants.EIDAT10_SAML_NS, DEF_LOCAL_NAME, PvpConstants.EIDAT10_PREFIX); + + /** QName of the XSI type. */ + QName TYPE_NAME = + new QName(PvpConstants.EIDAT10_SAML_NS, TYPE_LOCAL_NAME, PvpConstants.EIDAT10_PREFIX); + + + + /** NAME_ATTRIB_NAME attribute name. */ + String NAME_ATTRIB_NAME = "Name"; + + /** NAME_FORMAT_ATTRIB_NAME attribute name. */ + String NAME_FORMAT_ATTR = "NameFormat"; + + /** IS_REQUIRED_ATTRIB_NAME attribute name. */ + String IS_REQUIRED_ATTR = "isRequired"; + + /** FRIENDLY_NAME_ATTRIB_NAME attribute name. */ + String FRIENDLY_NAME_ATT = "FriendlyName"; + + /** Unspecified attribute format ID. */ + String UNSPECIFIED = "urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified"; + + /** URI reference attribute format ID. */ + String URI_REFERENCE = "urn:oasis:names:tc:SAML:2.0:attrname-format:uri"; + + /** Basic attribute format ID. */ + String BASIC = "urn:oasis:names:tc:SAML:2.0:attrname-format:basic"; + + /** + * Gets the name. + * + * @return the name + */ + @Override + String getName(); + + /** + * Sets the name. + * + * @param name the new name + */ + @Override + void setName(String name); + + /** + * Gets the name format. + * + * @return the name format + */ + @Override + String getNameFormat(); + + /** + * Sets the name format. + * + * @param nameFormat the new name format + */ + @Override + void setNameFormat(String nameFormat); + + /** + * Gets the friendly name. + * + * @return the friendly name + */ + @Override + String getFriendlyName(); + + /** + * Sets the friendly name. + * + * @param friendlyName the new friendly name + */ + @Override + void setFriendlyName(String friendlyName); + + /** + * Gets the checks if is required xs boolean. + * + * @return the checks if is required xs boolean + */ + String getIsRequiredXsBoolean(); + + @Override + void setIsRequired(Boolean aboolean); + + @Override + void setIsRequired(XSBooleanValue xsBooleanValue); + + /** + * Sets the checks if is required. + * + * @param newIsRequired the new checks if is required + */ + void setIsRequired(String newIsRequired); + + /** + * Gets the attribute values. + * + * @return the attribute values + */ + @Override + List getAttributeValues(); + + @Override + XSBooleanValue isRequiredXSBoolean(); + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/reqattr/EaafRequestedAttributes.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/reqattr/EaafRequestedAttributes.java new file mode 100644 index 00000000..98f118b0 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/reqattr/EaafRequestedAttributes.java @@ -0,0 +1,51 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.api.reqattr; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.opensaml.common.SAMLObject; + +import at.gv.egiz.eaaf.modules.pvp2.PvpConstants; + +public interface EaafRequestedAttributes extends SAMLObject { + /** The Constant DEFAULT_ELEMENT_LOCAL_NAME. */ + String DEF_LOCAL_NAME = "RequestedAttributes"; + + /** Default element name. */ + QName DEFAULT_ELEMENT_NAME = + new QName(PvpConstants.EIDAT10_SAML_NS, DEF_LOCAL_NAME, PvpConstants.EIDAT10_PREFIX); + + /** Local name of the XSI type. */ + String TYPE_LOCAL_NAME = "RequestedAttributesType"; + + /** QName of the XSI type. */ + QName TYPE_NAME = + new QName(PvpConstants.EIDAT10_SAML_NS, TYPE_LOCAL_NAME, PvpConstants.EIDAT10_PREFIX); + + /** + * Gets the attributes. + * + * @return the attributes + */ + List getAttributes(); +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/validation/IAuthnRequestValidator.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/validation/IAuthnRequestValidator.java index 439543fe..41dcd3b9 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/validation/IAuthnRequestValidator.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/validation/IAuthnRequestValidator.java @@ -1,39 +1,33 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.api.validation; import javax.servlet.http.HttpServletRequest; - -import org.opensaml.saml2.core.AuthnRequest; -import org.opensaml.saml2.metadata.SPSSODescriptor; - import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.exceptions.AuthnRequestValidatorException; +import org.opensaml.saml2.core.AuthnRequest; +import org.opensaml.saml2.metadata.SPSSODescriptor; public interface IAuthnRequestValidator { - void validate(HttpServletRequest httpReq, IRequest pendingReq, AuthnRequest authReq, SPSSODescriptor spSSODescriptor) throws AuthnRequestValidatorException; + void validate(HttpServletRequest httpReq, IRequest pendingReq, AuthnRequest authReq, + SPSSODescriptor spSsoDescriptor) throws AuthnRequestValidatorException; -} \ No newline at end of file +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/validation/ISAMLValidator.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/validation/ISAMLValidator.java deleted file mode 100644 index 4b8ddea6..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/validation/ISAMLValidator.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.api.validation; - -import org.opensaml.saml2.core.RequestAbstractType; - -import at.gv.egiz.eaaf.core.exceptions.EAAFException; - -public interface ISAMLValidator { - public void validateRequest(RequestAbstractType request) throws EAAFException; -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/validation/ISamlValidator.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/validation/ISamlValidator.java new file mode 100644 index 00000000..3cbe59da --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/api/validation/ISamlValidator.java @@ -0,0 +1,28 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.api.validation; + +import org.opensaml.saml2.core.RequestAbstractType; + +import at.gv.egiz.eaaf.core.exceptions.EaafException; + +public interface ISamlValidator { + void validateRequest(RequestAbstractType request) throws EaafException; +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/AttributQueryException.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/AttributQueryException.java index 189dc91e..82fb2c79 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/AttributQueryException.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/AttributQueryException.java @@ -1,48 +1,35 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.exception; -/** - * @author tlenz - * - */ -public class AttributQueryException extends PVP2Exception { +public class AttributQueryException extends Pvp2Exception { + + + private static final long serialVersionUID = -4302422507173728748L; - /** - * - */ - private static final long serialVersionUID = -4302422507173728748L; + public AttributQueryException(final String messageId, final Object[] parameters) { + super(messageId, parameters); + } - public AttributQueryException(String messageId, Object[] parameters) { - super(messageId, parameters); - } - - public AttributQueryException(String messageId, Object[] parameters, Throwable e) { - super(messageId, parameters, e); - } + public AttributQueryException(final String messageId, final Object[] parameters, final Throwable e) { + super(messageId, parameters, e); + } } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/BindingNotSupportedException.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/BindingNotSupportedException.java index d966e4a1..97971d3a 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/BindingNotSupportedException.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/BindingNotSupportedException.java @@ -1,45 +1,38 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.exception; import org.opensaml.saml2.core.StatusCode; -public class BindingNotSupportedException extends PVP2Exception { +public class BindingNotSupportedException extends Pvp2Exception { + + private static final long serialVersionUID = -7227603941387879360L; + + public BindingNotSupportedException(final String binding) { + super("pvp2.11", new Object[] {binding}); + this.statusCodeValue = StatusCode.UNSUPPORTED_BINDING_URI; + } + + + - public BindingNotSupportedException(String binding) { - super("pvp2.11", new Object[] {binding}); - this.statusCodeValue = StatusCode.UNSUPPORTED_BINDING_URI; - } - /** - * - */ - private static final long serialVersionUID = -7227603941387879360L; - - } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/CredentialsNotAvailableException.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/CredentialsNotAvailableException.java index e079cdef..ae64e134 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/CredentialsNotAvailableException.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/CredentialsNotAvailableException.java @@ -1,48 +1,40 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. + */ + package at.gv.egiz.eaaf.modules.pvp2.exception; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; + +public class CredentialsNotAvailableException extends EaafException { + + private static final long serialVersionUID = -2564476345552842599L; + + public CredentialsNotAvailableException(final String messageId, final Object[] parameters) { + super(messageId, parameters); + } + + public CredentialsNotAvailableException(final String messageId, final Object[] parameters, + final Throwable e) { + super(messageId, parameters, e); + } -public class CredentialsNotAvailableException extends EAAFException { - public CredentialsNotAvailableException(String messageId, - Object[] parameters) { - super(messageId, parameters); - } - public CredentialsNotAvailableException(String messageId, - Object[] parameters, Throwable e) { - super(messageId, parameters, e); - } - - /** - * - */ - private static final long serialVersionUID = -2564476345552842599L; } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/InvalidDateFormatException.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/InvalidDateFormatException.java index 6bcddf8a..8ca373c4 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/InvalidDateFormatException.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/InvalidDateFormatException.java @@ -1,43 +1,35 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.exception; import org.opensaml.saml2.core.StatusCode; -public class InvalidDateFormatException extends PVP2Exception { +public class InvalidDateFormatException extends Pvp2Exception { + + private static final long serialVersionUID = -6867976890237846085L; + + public InvalidDateFormatException() { + super("pvp2.02", null); + this.statusCodeValue = StatusCode.REQUESTER_URI; + } - public InvalidDateFormatException() { - super("pvp2.02", null); - this.statusCodeValue = StatusCode.REQUESTER_URI; - } - /** - * - */ - private static final long serialVersionUID = -6867976890237846085L; } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/InvalidPVPRequestException.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/InvalidPVPRequestException.java deleted file mode 100644 index 1d79ae2e..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/InvalidPVPRequestException.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.exception; - -public class InvalidPVPRequestException extends PVP2Exception { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public InvalidPVPRequestException(String messageId, Object[] parameters) { - super(messageId, parameters); - } - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/InvalidPvpRequestException.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/InvalidPvpRequestException.java new file mode 100644 index 00000000..e13731d6 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/InvalidPvpRequestException.java @@ -0,0 +1,30 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.exception; + +public class InvalidPvpRequestException extends Pvp2Exception { + + private static final long serialVersionUID = 1L; + + public InvalidPvpRequestException(final String messageId, final Object[] parameters) { + super(messageId, parameters); + } + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/NameIDFormatNotSupportedException.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/NameIDFormatNotSupportedException.java deleted file mode 100644 index a5ff811d..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/NameIDFormatNotSupportedException.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.exception; - -import org.opensaml.saml2.core.StatusCode; - -import at.gv.egiz.eaaf.core.exceptions.AuthnRequestValidatorException; - -public class NameIDFormatNotSupportedException extends AuthnRequestValidatorException { - - public NameIDFormatNotSupportedException(String nameIDFormat) { - super("pvp2.12", new Object[] {nameIDFormat}); - statusCodeValue = StatusCode.INVALID_NAMEID_POLICY_URI; - - } - - /** - * - */ - private static final long serialVersionUID = -2270762519437873336L; - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/NameIdFormatNotSupportedException.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/NameIdFormatNotSupportedException.java new file mode 100644 index 00000000..b43db603 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/NameIdFormatNotSupportedException.java @@ -0,0 +1,43 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.exception; + +import at.gv.egiz.eaaf.core.exceptions.AuthnRequestValidatorException; +import org.opensaml.saml2.core.StatusCode; + +public class NameIdFormatNotSupportedException extends AuthnRequestValidatorException { + + private static final long serialVersionUID = -2270762519437873336L; + + /** + * Invalid nameIdFormat in SAML2 request. + * + * @param nameIdFormat requested NameIdFormat + */ + public NameIdFormatNotSupportedException(final String nameIdFormat) { + super("pvp2.12", new Object[] {nameIdFormat}); + statusCodeValue = StatusCode.INVALID_NAMEID_POLICY_URI; + + } + + + + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/NoMetadataInformationException.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/NoMetadataInformationException.java index e600a1c7..f22d2d17 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/NoMetadataInformationException.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/NoMetadataInformationException.java @@ -1,43 +1,36 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.exception; import org.opensaml.saml2.core.StatusCode; -public class NoMetadataInformationException extends PVP2Exception { +public class NoMetadataInformationException extends Pvp2Exception { + + private static final long serialVersionUID = -4608068445208032193L; + + public NoMetadataInformationException() { + super("pvp2.15", null); + this.statusCodeValue = StatusCode.UNKNOWN_PRINCIPAL_URI; + } + - public NoMetadataInformationException() { - super("pvp2.15", null); - this.statusCodeValue = StatusCode.UNKNOWN_PRINCIPAL_URI; - } - /** - * - */ - private static final long serialVersionUID = -4608068445208032193L; } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/PVP2Exception.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/PVP2Exception.java deleted file mode 100644 index cfe4ca9d..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/PVP2Exception.java +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.exception; - -import org.opensaml.saml2.core.StatusCode; - -import at.gv.egiz.eaaf.core.exceptions.EAAFException; - -public abstract class PVP2Exception extends EAAFException { - //TODO:!!!!! - - protected String statusCodeValue = StatusCode.RESPONDER_URI; - protected String statusMessageValue = null; - - public PVP2Exception(String messageId, Object[] parameters, - Throwable wrapped) { - super(messageId, parameters, wrapped); - this.statusMessageValue = this.getMessage(); - } - - public PVP2Exception(String messageId, Object[] parameters) { - super(messageId, parameters); - this.statusMessageValue = this.getMessage(); - } - - - public String getStatusCodeValue() { - return (this.statusCodeValue); - } - - public String getStatusMessageValue() { - return (this.statusMessageValue); - } - - /** - * - */ - private static final long serialVersionUID = 7669537952484421069L; - - - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/PVP2MetadataException.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/PVP2MetadataException.java deleted file mode 100644 index 379fe19f..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/PVP2MetadataException.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.exception; - -public class PVP2MetadataException extends PVP2Exception { - - private static final long serialVersionUID = 1L; - - public PVP2MetadataException(String messageId, Object[] parameters) { - super(messageId, parameters); - } - - public PVP2MetadataException(String messageId, Object[] parameters, Throwable wrapped) { - super(messageId, parameters, wrapped); - } - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/Pvp2Exception.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/Pvp2Exception.java new file mode 100644 index 00000000..93980a73 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/Pvp2Exception.java @@ -0,0 +1,55 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.exception; + +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import org.opensaml.saml2.core.StatusCode; + +public abstract class Pvp2Exception extends EaafException { + private static final long serialVersionUID = 7669537952484421069L; + + protected String statusCodeValue = StatusCode.RESPONDER_URI; + protected String statusMessageValue = null; + + public Pvp2Exception(final String messageId, final Object[] parameters, final Throwable wrapped) { + super(messageId, parameters, wrapped); + this.statusMessageValue = this.getMessage(); + } + + public Pvp2Exception(final String messageId, final Object[] parameters) { + super(messageId, parameters); + this.statusMessageValue = this.getMessage(); + } + + + public String getStatusCodeValue() { + return (this.statusCodeValue); + } + + public String getStatusMessageValue() { + return (this.statusMessageValue); + } + + + + + + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/Pvp2MetadataException.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/Pvp2MetadataException.java new file mode 100644 index 00000000..ab0e8871 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/Pvp2MetadataException.java @@ -0,0 +1,34 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.exception; + +public class Pvp2MetadataException extends Pvp2Exception { + + private static final long serialVersionUID = 1L; + + public Pvp2MetadataException(final String messageId, final Object[] parameters) { + super(messageId, parameters); + } + + public Pvp2MetadataException(final String messageId, final Object[] parameters, final Throwable wrapped) { + super(messageId, parameters, wrapped); + } + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/QAANotAllowedException.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/QAANotAllowedException.java deleted file mode 100644 index a8012d85..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/QAANotAllowedException.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.exception; - -import org.opensaml.saml2.core.StatusCode; - - -public class QAANotAllowedException extends PVP2Exception { - - public QAANotAllowedException(String qaa_auth, String qaa_request, String mode) { - super("pvp2.17", new Object[] {qaa_auth, qaa_request, mode}); - this.statusCodeValue = StatusCode.REQUESTER_URI; - } - - /** - * - */ - private static final long serialVersionUID = -3964192953884089323L; - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/QAANotSupportedException.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/QAANotSupportedException.java deleted file mode 100644 index 0b53ae23..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/QAANotSupportedException.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.exception; - -import org.opensaml.saml2.core.StatusCode; - - -public class QAANotSupportedException extends PVP2Exception { - - public QAANotSupportedException(String qaa) { - super("pvp2.05", new Object[] {qaa}); - this.statusCodeValue = StatusCode.REQUESTER_URI; - } - - /** - * - */ - private static final long serialVersionUID = -3964192953884089323L; - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/QaaNotAllowedException.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/QaaNotAllowedException.java new file mode 100644 index 00000000..9edba3f2 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/QaaNotAllowedException.java @@ -0,0 +1,33 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.exception; + +import org.opensaml.saml2.core.StatusCode; + + +public class QaaNotAllowedException extends Pvp2Exception { + + private static final long serialVersionUID = -3964192953884089323L; + + public QaaNotAllowedException(final String qaaAuth, final String qaaRequest, final String mode) { + super("pvp2.17", new Object[] {qaaAuth, qaaRequest, mode}); + this.statusCodeValue = StatusCode.REQUESTER_URI; + } +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/QaaNotSupportedException.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/QaaNotSupportedException.java new file mode 100644 index 00000000..dc48508d --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/QaaNotSupportedException.java @@ -0,0 +1,37 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.exception; + +import org.opensaml.saml2.core.StatusCode; + + +public class QaaNotSupportedException extends Pvp2Exception { + + private static final long serialVersionUID = -3964192953884089323L; + + public QaaNotSupportedException(final String qaa) { + super("pvp2.05", new Object[] {qaa}); + this.statusCodeValue = StatusCode.REQUESTER_URI; + } + + + + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/SAMLMetadataSignatureException.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/SAMLMetadataSignatureException.java deleted file mode 100644 index 9e35871d..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/SAMLMetadataSignatureException.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.exception; - -import org.opensaml.saml2.core.StatusCode; - -public class SAMLMetadataSignatureException extends PVP2Exception { - - public SAMLMetadataSignatureException() { - super("pvp2.25", null); - this.statusCodeValue = StatusCode.REQUESTER_URI; - } - - public SAMLMetadataSignatureException(Throwable e) { - super("pvp2.25", null, e); - this.statusCodeValue = StatusCode.REQUESTER_URI; - } - - /** - * - */ - private static final long serialVersionUID = 1L; - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/SamlMetadataSignatureException.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/SamlMetadataSignatureException.java new file mode 100644 index 00000000..ede310f0 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/SamlMetadataSignatureException.java @@ -0,0 +1,40 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.exception; + +import org.opensaml.saml2.core.StatusCode; + +public class SamlMetadataSignatureException extends Pvp2Exception { + private static final long serialVersionUID = 1L; + + public SamlMetadataSignatureException() { + super("pvp2.25", null); + this.statusCodeValue = StatusCode.REQUESTER_URI; + } + + public SamlMetadataSignatureException(final Throwable e) { + super("pvp2.25", null, e); + this.statusCodeValue = StatusCode.REQUESTER_URI; + } + + + + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/SchemaValidationException.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/SchemaValidationException.java index f9adbf6d..39cf148b 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/SchemaValidationException.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/SchemaValidationException.java @@ -1,56 +1,35 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.exception; -/** - * @author tlenz - * - */ -public class SchemaValidationException extends PVP2Exception { +public class SchemaValidationException extends Pvp2Exception { + + private static final long serialVersionUID = 1L; + - /** - * - */ - private static final long serialVersionUID = 1L; + public SchemaValidationException(final String messageId, final Object[] parameters) { + super(messageId, parameters); + } - /** - * @param messageId - * @param parameters - */ - public SchemaValidationException(String messageId, Object[] parameters) { - super(messageId, parameters); - } - - /** - * @param messageId - * @param parameters - */ - public SchemaValidationException(String messageId, Object[] parameters, Throwable e) { - super(messageId, parameters, e); - } + public SchemaValidationException(final String messageId, final Object[] parameters, final Throwable e) { + super(messageId, parameters, e); + } } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/SignatureValidationException.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/SignatureValidationException.java index 1f1f46e5..410686f6 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/SignatureValidationException.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/exception/SignatureValidationException.java @@ -1,62 +1,43 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.exception; import org.opensaml.saml2.metadata.provider.FilterException; -/** - * @author tlenz - * - */ public class SignatureValidationException extends FilterException { - /** - * @param string - */ - public SignatureValidationException(String string) { - super(string); - - } - - /** - * @param e - */ - public SignatureValidationException(Exception e) { - super(e); - } - - /** - * @param string - * @param object - */ - public SignatureValidationException(String string, Exception e) { - super(string, e); - } - - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; + + public SignatureValidationException(final String string) { + super(string); + + } + + public SignatureValidationException(final Exception e) { + super(e); + } + + public SignatureValidationException(final String string, final Exception e) { + super(string, e); + } + + } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/binding/PostBinding.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/binding/PostBinding.java index 79578788..0933f0a2 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/binding/PostBinding.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/binding/PostBinding.java @@ -1,34 +1,43 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.impl.binding; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.gui.IGuiBuilderConfigurationFactory; +import at.gv.egiz.eaaf.core.api.gui.IVelocityGuiBuilderConfiguration; +import at.gv.egiz.eaaf.core.api.gui.IVelocityGuiFormBuilder; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.impl.gui.velocity.VelocityProvider; +import at.gv.egiz.eaaf.modules.pvp2.PvpConstants; +import at.gv.egiz.eaaf.modules.pvp2.api.binding.IDecoder; +import at.gv.egiz.eaaf.modules.pvp2.api.binding.IEncoder; +import at.gv.egiz.eaaf.modules.pvp2.api.message.InboundMessageInterface; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.InboundMessage; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.PvpSProfileRequest; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.PvpSProfileResponse; +import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.HttpPostEncoderWithOwnTemplate; +import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafDefaultSaml2Bootstrap; +import at.gv.egiz.eaaf.modules.pvp2.impl.validation.TrustEngineFactory; +import at.gv.egiz.eaaf.modules.pvp2.impl.verification.PvpSignedRequestPolicyRule; import org.apache.commons.lang3.StringUtils; import org.opensaml.common.SAMLObject; import org.opensaml.common.binding.BasicSAMLMessageContext; @@ -57,186 +66,174 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.core.api.gui.IGUIBuilderConfigurationFactory; -import at.gv.egiz.eaaf.core.api.gui.IVelocityGUIBuilderConfiguration; -import at.gv.egiz.eaaf.core.api.gui.IVelocityGuiFormBuilder; -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.impl.gui.velocity.VelocityProvider; -import at.gv.egiz.eaaf.modules.pvp2.PVPConstants; -import at.gv.egiz.eaaf.modules.pvp2.api.binding.IDecoder; -import at.gv.egiz.eaaf.modules.pvp2.api.binding.IEncoder; -import at.gv.egiz.eaaf.modules.pvp2.api.message.InboundMessageInterface; -import at.gv.egiz.eaaf.modules.pvp2.impl.message.InboundMessage; -import at.gv.egiz.eaaf.modules.pvp2.impl.message.PVPSProfileRequest; -import at.gv.egiz.eaaf.modules.pvp2.impl.message.PVPSProfileResponse; -import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.HTTPPostEncoderWithOwnTemplate; -import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EAAFDefaultSAML2Bootstrap; -import at.gv.egiz.eaaf.modules.pvp2.impl.validation.TrustEngineFactory; -import at.gv.egiz.eaaf.modules.pvp2.impl.verification.PVPSignedRequestPolicyRule; - @Service("PVPPOSTBinding") public class PostBinding implements IDecoder, IEncoder { - private static final Logger log = LoggerFactory.getLogger(PostBinding.class); - - @Autowired(required=true) IConfiguration authConfig; - @Autowired(required=true) IVelocityGuiFormBuilder guiBuilder; - @Autowired(required=true) IGUIBuilderConfigurationFactory guiConfigFactory; - - @Override - public void encodeRequest(HttpServletRequest req, HttpServletResponse resp, - RequestAbstractType request, String targetLocation, String relayState, Credential credentials, IRequest pendingReq) - throws MessageEncodingException, SecurityException { - - try { - //load default PVP security configurations - EAAFDefaultSAML2Bootstrap.initializeDefaultPVPConfiguration(); - - //initialize POST binding encoder with template decoration - final IVelocityGUIBuilderConfiguration guiConfig = guiConfigFactory.getSPSpecificSAML2PostConfiguration( - pendingReq, - "pvp_postbinding_template.html", - authConfig.getConfigurationRootDirectory()); - - final HTTPPostEncoderWithOwnTemplate encoder = new HTTPPostEncoderWithOwnTemplate(guiConfig, guiBuilder, - VelocityProvider.getClassPathVelocityEngine()); - - //set OpenSAML2 process parameter into binding context dao - final HttpServletResponseAdapter responseAdapter = new HttpServletResponseAdapter( - resp, true); - final BasicSAMLMessageContext context = new BasicSAMLMessageContext(); - final SingleSignOnService service = new SingleSignOnServiceBuilder().buildObject(); - service.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"); - service.setLocation(targetLocation);; - - context.setOutboundSAMLMessageSigningCredential(credentials); - context.setPeerEntityEndpoint(service); - context.setOutboundSAMLMessage(request); - context.setOutboundMessageTransport(responseAdapter); - context.setRelayState(relayState); - - encoder.encode(context); - - } catch (final Exception e) { - log.warn("Can not encode SAML2 request", e); - throw new SecurityException(e); - - } - } - - @Override - public void encodeRespone(HttpServletRequest req, HttpServletResponse resp, - StatusResponseType response, String targetLocation, String relayState, Credential credentials, IRequest pendingReq) - throws MessageEncodingException, SecurityException { - - try { - //load default PVP security configurations - EAAFDefaultSAML2Bootstrap.initializeDefaultPVPConfiguration(); - - log.debug("create SAML POSTBinding response"); - - //initialize POST binding encoder with template decoration - final IVelocityGUIBuilderConfiguration guiConfig = guiConfigFactory.getSPSpecificSAML2PostConfiguration( - pendingReq, - "pvp_postbinding_template.html", - authConfig.getConfigurationRootDirectory()); - final HTTPPostEncoderWithOwnTemplate encoder = new HTTPPostEncoderWithOwnTemplate(guiConfig, guiBuilder, - VelocityProvider.getClassPathVelocityEngine()); - - //set OpenSAML2 process parameter into binding context dao - final HttpServletResponseAdapter responseAdapter = new HttpServletResponseAdapter( - resp, true); - final BasicSAMLMessageContext context = new BasicSAMLMessageContext(); - final SingleSignOnService service = new SingleSignOnServiceBuilder() - .buildObject(); - service.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); - service.setLocation(targetLocation); - context.setOutboundSAMLMessageSigningCredential(credentials); - context.setPeerEntityEndpoint(service); - // context.setOutboundMessage(authReq); - context.setOutboundSAMLMessage(response); - context.setOutboundMessageTransport(responseAdapter); - context.setRelayState(relayState); - - encoder.encode(context); - - } catch (final Exception e) { - log.warn("Can not encode SAML2 response", e); - throw new SecurityException(e); - - } - } - - @Override - public InboundMessageInterface decode(HttpServletRequest req, - HttpServletResponse resp, MetadataProvider metadataProvider, boolean isSPEndPoint, URIComparator comparator) throws MessageDecodingException, - SecurityException { - - final HTTPPostDecoder decode = new HTTPPostDecoder(new BasicParserPool()); - final BasicSAMLMessageContext messageContext = new BasicSAMLMessageContext(); - messageContext - .setInboundMessageTransport(new HttpServletRequestAdapter(req)); - //set metadata descriptor type - if (isSPEndPoint) { - messageContext.setPeerEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME); - decode.setURIComparator(comparator); - - } else { - messageContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME); - decode.setURIComparator(comparator); - } - - messageContext.setMetadataProvider(metadataProvider); - - //set security policy context - final BasicSecurityPolicy policy = new BasicSecurityPolicy(); - policy.getPolicyRules().add( - new PVPSignedRequestPolicyRule(metadataProvider, - TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider), - messageContext.getPeerEntityRole())); - final SecurityPolicyResolver secResolver = new StaticSecurityPolicyResolver(policy); - messageContext.setSecurityPolicyResolver(secResolver); - - decode.decode(messageContext); - - InboundMessage msg = null; - if (messageContext.getInboundMessage() instanceof RequestAbstractType) { - final RequestAbstractType inboundMessage = (RequestAbstractType) messageContext - .getInboundMessage(); - msg = new PVPSProfileRequest(inboundMessage, getSAML2BindingName()); - msg.setEntityID(inboundMessage.getIssuer().getValue()); - - } else if (messageContext.getInboundMessage() instanceof StatusResponseType){ - final StatusResponseType inboundMessage = (StatusResponseType) messageContext.getInboundMessage(); - msg = new PVPSProfileResponse(inboundMessage); - msg.setEntityID(inboundMessage.getIssuer().getValue()); - - } else - //create empty container if request type is unknown - msg = new InboundMessage(); - - if (messageContext.getPeerEntityMetadata() != null) - msg.setEntityID(messageContext.getPeerEntityMetadata().getEntityID()); - - else { - if (StringUtils.isEmpty(msg.getEntityID())) - log.info("No Metadata found for OA with EntityID " + messageContext.getInboundMessageIssuer()); - } - - - msg.setVerified(true); - msg.setRelayState(messageContext.getRelayState()); - - return msg; - } - - @Override - public boolean handleDecode(String action, HttpServletRequest req) { - return (req.getMethod().equals("POST") && action.equals(PVPConstants.POST)); - } - - @Override - public String getSAML2BindingName() { - return SAMLConstants.SAML2_POST_BINDING_URI; - } + private static final Logger log = LoggerFactory.getLogger(PostBinding.class); + + @Autowired(required = true) + IConfiguration authConfig; + @Autowired(required = true) + IVelocityGuiFormBuilder guiBuilder; + @Autowired(required = true) + IGuiBuilderConfigurationFactory guiConfigFactory; + + @Override + public void encodeRequest(final HttpServletRequest req, final HttpServletResponse resp, + final RequestAbstractType request, final String targetLocation, final String relayState, + final Credential credentials, final IRequest pendingReq) + throws MessageEncodingException, SecurityException { + + try { + // load default PVP security configurations + EaafDefaultSaml2Bootstrap.initializeDefaultPvpConfiguration(); + + // initialize POST binding encoder with template decoration + final IVelocityGuiBuilderConfiguration guiConfig = + guiConfigFactory.getSpSpecificSaml2PostConfiguration(pendingReq, + "pvp_postbinding_template.html", authConfig.getConfigurationRootDirectory()); + + final HttpPostEncoderWithOwnTemplate encoder = new HttpPostEncoderWithOwnTemplate(guiConfig, + guiBuilder, VelocityProvider.getClassPathVelocityEngine()); + + // set OpenSAML2 process parameter into binding context dao + final HttpServletResponseAdapter responseAdapter = new HttpServletResponseAdapter(resp, true); + final BasicSAMLMessageContext context = + new BasicSAMLMessageContext<>(); + final SingleSignOnService service = new SingleSignOnServiceBuilder().buildObject(); + service.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"); + service.setLocation(targetLocation); + + context.setOutboundSAMLMessageSigningCredential(credentials); + context.setPeerEntityEndpoint(service); + context.setOutboundSAMLMessage(request); + context.setOutboundMessageTransport(responseAdapter); + context.setRelayState(relayState); + + encoder.encode(context); + + } catch (final Exception e) { + log.warn("Can not encode SAML2 request", e); + throw new SecurityException(e); + + } + } + + @Override + public void encodeRespone(final HttpServletRequest req, final HttpServletResponse resp, + final StatusResponseType response, final String targetLocation, final String relayState, + final Credential credentials, final IRequest pendingReq) + throws MessageEncodingException, SecurityException { + + try { + // load default PVP security configurations + EaafDefaultSaml2Bootstrap.initializeDefaultPvpConfiguration(); + + log.debug("create SAML POSTBinding response"); + + // initialize POST binding encoder with template decoration + final IVelocityGuiBuilderConfiguration guiConfig = + guiConfigFactory.getSpSpecificSaml2PostConfiguration(pendingReq, + "pvp_postbinding_template.html", authConfig.getConfigurationRootDirectory()); + final HttpPostEncoderWithOwnTemplate encoder = new HttpPostEncoderWithOwnTemplate(guiConfig, + guiBuilder, VelocityProvider.getClassPathVelocityEngine()); + + // set OpenSAML2 process parameter into binding context dao + final HttpServletResponseAdapter responseAdapter = new HttpServletResponseAdapter(resp, true); + final BasicSAMLMessageContext context = + new BasicSAMLMessageContext<>(); + final SingleSignOnService service = new SingleSignOnServiceBuilder().buildObject(); + service.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); + service.setLocation(targetLocation); + context.setOutboundSAMLMessageSigningCredential(credentials); + context.setPeerEntityEndpoint(service); + // context.setOutboundMessage(authReq); + context.setOutboundSAMLMessage(response); + context.setOutboundMessageTransport(responseAdapter); + context.setRelayState(relayState); + + encoder.encode(context); + + } catch (final Exception e) { + log.warn("Can not encode SAML2 response", e); + throw new SecurityException(e); + + } + } + + @Override + public InboundMessageInterface decode(final HttpServletRequest req, + final HttpServletResponse resp, final MetadataProvider metadataProvider, + final boolean isSpEndPoint, final URIComparator comparator) + throws MessageDecodingException, SecurityException { + + final HTTPPostDecoder decode = new HTTPPostDecoder(new BasicParserPool()); + final BasicSAMLMessageContext messageContext = + new BasicSAMLMessageContext<>(); + messageContext.setInboundMessageTransport(new HttpServletRequestAdapter(req)); + // set metadata descriptor type + if (isSpEndPoint) { + messageContext.setPeerEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME); + decode.setURIComparator(comparator); + + } else { + messageContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME); + decode.setURIComparator(comparator); + } + + messageContext.setMetadataProvider(metadataProvider); + + // set security policy context + final BasicSecurityPolicy policy = new BasicSecurityPolicy(); + policy.getPolicyRules() + .add(new PvpSignedRequestPolicyRule(metadataProvider, + TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider), + messageContext.getPeerEntityRole())); + final SecurityPolicyResolver secResolver = new StaticSecurityPolicyResolver(policy); + messageContext.setSecurityPolicyResolver(secResolver); + + decode.decode(messageContext); + + InboundMessage msg = null; + if (messageContext.getInboundMessage() instanceof RequestAbstractType) { + final RequestAbstractType inboundMessage = + (RequestAbstractType) messageContext.getInboundMessage(); + msg = new PvpSProfileRequest(inboundMessage, getSaml2BindingName()); + msg.setEntityID(inboundMessage.getIssuer().getValue()); + + } else if (messageContext.getInboundMessage() instanceof StatusResponseType) { + final StatusResponseType inboundMessage = + (StatusResponseType) messageContext.getInboundMessage(); + msg = new PvpSProfileResponse(inboundMessage); + msg.setEntityID(inboundMessage.getIssuer().getValue()); + + } else { + // create empty container if request type is unknown + msg = new InboundMessage(); + } + + if (messageContext.getPeerEntityMetadata() != null) { + msg.setEntityID(messageContext.getPeerEntityMetadata().getEntityID()); + } else { + if (StringUtils.isEmpty(msg.getEntityID())) { + log.info( + "No Metadata found for OA with EntityID " + messageContext.getInboundMessageIssuer()); + } + } + + + msg.setVerified(true); + msg.setRelayState(messageContext.getRelayState()); + + return msg; + } + + @Override + public boolean handleDecode(final String action, final HttpServletRequest req) { + return (req.getMethod().equals("POST") && action.equals(PvpConstants.POST)); + } + + @Override + public String getSaml2BindingName() { + return SAMLConstants.SAML2_POST_BINDING_URI; + } } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/binding/RedirectBinding.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/binding/RedirectBinding.java index ca9b3d98..4e548d57 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/binding/RedirectBinding.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/binding/RedirectBinding.java @@ -1,34 +1,38 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.impl.binding; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.modules.pvp2.PvpConstants; +import at.gv.egiz.eaaf.modules.pvp2.api.binding.IDecoder; +import at.gv.egiz.eaaf.modules.pvp2.api.binding.IEncoder; +import at.gv.egiz.eaaf.modules.pvp2.api.message.InboundMessageInterface; +import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IRefreshableMetadataProvider; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.InboundMessage; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.PvpSProfileRequest; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.PvpSProfileResponse; +import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafDefaultSaml2Bootstrap; +import at.gv.egiz.eaaf.modules.pvp2.impl.validation.TrustEngineFactory; +import at.gv.egiz.eaaf.modules.pvp2.impl.verification.PvpAuthRequestSignedRole; import org.apache.commons.lang3.StringUtils; import org.opensaml.common.SAMLObject; import org.opensaml.common.binding.BasicSAMLMessageContext; @@ -58,182 +62,179 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; -import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.modules.pvp2.PVPConstants; -import at.gv.egiz.eaaf.modules.pvp2.api.binding.IDecoder; -import at.gv.egiz.eaaf.modules.pvp2.api.binding.IEncoder; -import at.gv.egiz.eaaf.modules.pvp2.api.message.InboundMessageInterface; -import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IRefreshableMetadataProvider; -import at.gv.egiz.eaaf.modules.pvp2.impl.message.InboundMessage; -import at.gv.egiz.eaaf.modules.pvp2.impl.message.PVPSProfileRequest; -import at.gv.egiz.eaaf.modules.pvp2.impl.message.PVPSProfileResponse; -import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EAAFDefaultSAML2Bootstrap; -import at.gv.egiz.eaaf.modules.pvp2.impl.validation.TrustEngineFactory; -import at.gv.egiz.eaaf.modules.pvp2.impl.verification.PVPAuthRequestSignedRole; - @Service("PVPRedirectBinding") public class RedirectBinding implements IDecoder, IEncoder { - - private static final Logger log = LoggerFactory.getLogger(RedirectBinding.class); - - public void encodeRequest(HttpServletRequest req, HttpServletResponse resp, - RequestAbstractType request, String targetLocation, String relayState, Credential credentials, IRequest pendingReq) - throws MessageEncodingException, SecurityException { - - //load default PVP security configurations - EAAFDefaultSAML2Bootstrap.initializeDefaultPVPConfiguration(); - - log.debug("create SAML RedirectBinding response"); - - HTTPRedirectDeflateEncoder encoder = new HTTPRedirectDeflateEncoder(); - HttpServletResponseAdapter responseAdapter = new HttpServletResponseAdapter( - resp, true); - BasicSAMLMessageContext context = new BasicSAMLMessageContext(); - SingleSignOnService service = new SingleSignOnServiceBuilder() - .buildObject(); - service.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); - service.setLocation(targetLocation); - context.setOutboundSAMLMessageSigningCredential(credentials); - context.setPeerEntityEndpoint(service); - context.setOutboundSAMLMessage(request); - context.setOutboundMessageTransport(responseAdapter); - context.setRelayState(relayState); - - encoder.encode(context); - } - - public void encodeRespone(HttpServletRequest req, HttpServletResponse resp, - StatusResponseType response, String targetLocation, String relayState, - Credential credentials, IRequest pendingReq) throws MessageEncodingException, SecurityException { - - //load default PVP security configurations - EAAFDefaultSAML2Bootstrap.initializeDefaultPVPConfiguration(); - - log.debug("create SAML RedirectBinding response"); - - HTTPRedirectDeflateEncoder encoder = new HTTPRedirectDeflateEncoder(); - HttpServletResponseAdapter responseAdapter = new HttpServletResponseAdapter( - resp, true); - BasicSAMLMessageContext context = new BasicSAMLMessageContext(); - SingleSignOnService service = new SingleSignOnServiceBuilder() - .buildObject(); - service.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); - service.setLocation(targetLocation); - context.setOutboundSAMLMessageSigningCredential(credentials); - context.setPeerEntityEndpoint(service); - context.setOutboundSAMLMessage(response); - context.setOutboundMessageTransport(responseAdapter); - context.setRelayState(relayState); - - encoder.encode(context); - - } - - public InboundMessageInterface decode(HttpServletRequest req, - HttpServletResponse resp, MetadataProvider metadataProvider, boolean isSPEndPoint, URIComparator comparator) throws MessageDecodingException, - SecurityException { - - HTTPRedirectDeflateDecoder decode = new HTTPRedirectDeflateDecoder( - new BasicParserPool()); - - BasicSAMLMessageContext messageContext = new BasicSAMLMessageContext(); - messageContext - .setInboundMessageTransport(new HttpServletRequestAdapter(req)); - - //set metadata descriptor type - if (isSPEndPoint) { - messageContext.setPeerEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME); - decode.setURIComparator(comparator); - - } else { - messageContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME); - decode.setURIComparator(comparator); - } - - messageContext.setMetadataProvider(metadataProvider); - - SAML2HTTPRedirectDeflateSignatureRule signatureRule = new SAML2HTTPRedirectDeflateSignatureRule( - TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider)); - PVPAuthRequestSignedRole signedRole = new PVPAuthRequestSignedRole(); - BasicSecurityPolicy policy = new BasicSecurityPolicy(); - policy.getPolicyRules().add(signedRole); - policy.getPolicyRules().add(signatureRule); - SecurityPolicyResolver resolver = new StaticSecurityPolicyResolver( - policy); - messageContext.setSecurityPolicyResolver(resolver); - - //set metadata descriptor type - if (isSPEndPoint) - messageContext.setPeerEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME); - else - messageContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME); - - try { - decode.decode(messageContext); - - //check signature - signatureRule.evaluate(messageContext); - - } catch (SecurityException e) { - if (StringUtils.isEmpty(messageContext.getInboundMessageIssuer())) { - throw e; - - } - - if (metadataProvider instanceof IRefreshableMetadataProvider) { - log.debug("PVP2X message validation FAILED. Reload metadata for entityID: " + messageContext.getInboundMessageIssuer()); - if (!((IRefreshableMetadataProvider) metadataProvider).refreshMetadataProvider(messageContext.getInboundMessageIssuer())) - throw e; - - else { - log.trace("PVP2X metadata reload finished. Check validate message again."); - decode.decode(messageContext); - - //check signature - signatureRule.evaluate(messageContext); - - } - log.trace("Second PVP2X message validation finished"); - - } else { - throw e; - - } - } - - InboundMessage msg = null; - if (messageContext.getInboundMessage() instanceof RequestAbstractType) { - RequestAbstractType inboundMessage = (RequestAbstractType) messageContext - .getInboundMessage(); - msg = new PVPSProfileRequest(inboundMessage, getSAML2BindingName()); - - - } else if (messageContext.getInboundMessage() instanceof StatusResponseType){ - StatusResponseType inboundMessage = (StatusResponseType) messageContext.getInboundMessage(); - msg = new PVPSProfileResponse(inboundMessage); - - } else - //create empty container if request type is unknown - msg = new InboundMessage(); - - if (messageContext.getPeerEntityMetadata() != null) - msg.setEntityID(messageContext.getPeerEntityMetadata().getEntityID()); - - else - log.info("No Metadata found for OA with EntityID " + messageContext.getInboundMessageIssuer()); - - msg.setVerified(true); - msg.setRelayState(messageContext.getRelayState()); - - return msg; - } - - public boolean handleDecode(String action, HttpServletRequest req) { - return ((action.equals(PVPConstants.REDIRECT) || action.equals(PVPConstants.SINGLELOGOUT)) - && req.getMethod().equals("GET")); - } - - public String getSAML2BindingName() { - return SAMLConstants.SAML2_REDIRECT_BINDING_URI; - } + + private static final Logger log = LoggerFactory.getLogger(RedirectBinding.class); + + @Override + public void encodeRequest(final HttpServletRequest req, final HttpServletResponse resp, + final RequestAbstractType request, final String targetLocation, final String relayState, + final Credential credentials, final IRequest pendingReq) + throws MessageEncodingException, SecurityException { + + // load default PVP security configurations + EaafDefaultSaml2Bootstrap.initializeDefaultPvpConfiguration(); + + log.debug("create SAML RedirectBinding response"); + + final HTTPRedirectDeflateEncoder encoder = new HTTPRedirectDeflateEncoder(); + final HttpServletResponseAdapter responseAdapter = new HttpServletResponseAdapter(resp, true); + final BasicSAMLMessageContext context = + new BasicSAMLMessageContext<>(); + final SingleSignOnService service = new SingleSignOnServiceBuilder().buildObject(); + service.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); + service.setLocation(targetLocation); + context.setOutboundSAMLMessageSigningCredential(credentials); + context.setPeerEntityEndpoint(service); + context.setOutboundSAMLMessage(request); + context.setOutboundMessageTransport(responseAdapter); + context.setRelayState(relayState); + + encoder.encode(context); + } + + @Override + public void encodeRespone(final HttpServletRequest req, final HttpServletResponse resp, + final StatusResponseType response, final String targetLocation, final String relayState, + final Credential credentials, final IRequest pendingReq) + throws MessageEncodingException, SecurityException { + + // load default PVP security configurations + EaafDefaultSaml2Bootstrap.initializeDefaultPvpConfiguration(); + + log.debug("create SAML RedirectBinding response"); + + final HTTPRedirectDeflateEncoder encoder = new HTTPRedirectDeflateEncoder(); + final HttpServletResponseAdapter responseAdapter = new HttpServletResponseAdapter(resp, true); + final BasicSAMLMessageContext context = + new BasicSAMLMessageContext<>(); + final SingleSignOnService service = new SingleSignOnServiceBuilder().buildObject(); + service.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); + service.setLocation(targetLocation); + context.setOutboundSAMLMessageSigningCredential(credentials); + context.setPeerEntityEndpoint(service); + context.setOutboundSAMLMessage(response); + context.setOutboundMessageTransport(responseAdapter); + context.setRelayState(relayState); + + encoder.encode(context); + + } + + @Override + public InboundMessageInterface decode(final HttpServletRequest req, + final HttpServletResponse resp, final MetadataProvider metadataProvider, + final boolean isSpEndPoint, final URIComparator comparator) + throws MessageDecodingException, SecurityException { + + final HTTPRedirectDeflateDecoder decode = new HTTPRedirectDeflateDecoder(new BasicParserPool()); + + final BasicSAMLMessageContext messageContext = + new BasicSAMLMessageContext<>(); + messageContext.setInboundMessageTransport(new HttpServletRequestAdapter(req)); + + // set metadata descriptor type + if (isSpEndPoint) { + messageContext.setPeerEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME); + decode.setURIComparator(comparator); + + } else { + messageContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME); + decode.setURIComparator(comparator); + } + + messageContext.setMetadataProvider(metadataProvider); + + final SAML2HTTPRedirectDeflateSignatureRule signatureRule = + new SAML2HTTPRedirectDeflateSignatureRule( + TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider)); + final PvpAuthRequestSignedRole signedRole = new PvpAuthRequestSignedRole(); + final BasicSecurityPolicy policy = new BasicSecurityPolicy(); + policy.getPolicyRules().add(signedRole); + policy.getPolicyRules().add(signatureRule); + final SecurityPolicyResolver resolver = new StaticSecurityPolicyResolver(policy); + messageContext.setSecurityPolicyResolver(resolver); + + // set metadata descriptor type + if (isSpEndPoint) { + messageContext.setPeerEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME); + } else { + messageContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME); + } + + try { + decode.decode(messageContext); + + // check signature + signatureRule.evaluate(messageContext); + + } catch (final SecurityException e) { + if (StringUtils.isEmpty(messageContext.getInboundMessageIssuer())) { + throw e; + + } + + if (metadataProvider instanceof IRefreshableMetadataProvider) { + log.debug("PVP2X message validation FAILED. Reload metadata for entityID: " + + messageContext.getInboundMessageIssuer()); + if (!((IRefreshableMetadataProvider) metadataProvider) + .refreshMetadataProvider(messageContext.getInboundMessageIssuer())) { + throw e; + } else { + log.trace("PVP2X metadata reload finished. Check validate message again."); + decode.decode(messageContext); + + // check signature + signatureRule.evaluate(messageContext); + + } + log.trace("Second PVP2X message validation finished"); + + } else { + throw e; + + } + } + + InboundMessage msg = null; + if (messageContext.getInboundMessage() instanceof RequestAbstractType) { + final RequestAbstractType inboundMessage = + (RequestAbstractType) messageContext.getInboundMessage(); + msg = new PvpSProfileRequest(inboundMessage, getSaml2BindingName()); + + + } else if (messageContext.getInboundMessage() instanceof StatusResponseType) { + final StatusResponseType inboundMessage = + (StatusResponseType) messageContext.getInboundMessage(); + msg = new PvpSProfileResponse(inboundMessage); + + } else { + // create empty container if request type is unknown + msg = new InboundMessage(); + } + + if (messageContext.getPeerEntityMetadata() != null) { + msg.setEntityID(messageContext.getPeerEntityMetadata().getEntityID()); + } else { + log.info( + "No Metadata found for OA with EntityID " + messageContext.getInboundMessageIssuer()); + } + + msg.setVerified(true); + msg.setRelayState(messageContext.getRelayState()); + + return msg; + } + + @Override + public boolean handleDecode(final String action, final HttpServletRequest req) { + return ((action.equals(PvpConstants.REDIRECT) || action.equals(PvpConstants.SINGLELOGOUT)) + && req.getMethod().equals("GET")); + } + + @Override + public String getSaml2BindingName() { + return SAMLConstants.SAML2_REDIRECT_BINDING_URI; + } } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/binding/SoapBinding.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/binding/SoapBinding.java index c70060ad..79a88487 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/binding/SoapBinding.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/binding/SoapBinding.java @@ -1,36 +1,36 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.impl.binding; import java.util.List; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.modules.pvp2.PvpConstants; +import at.gv.egiz.eaaf.modules.pvp2.api.binding.IDecoder; +import at.gv.egiz.eaaf.modules.pvp2.api.binding.IEncoder; +import at.gv.egiz.eaaf.modules.pvp2.api.message.InboundMessageInterface; +import at.gv.egiz.eaaf.modules.pvp2.exception.AttributQueryException; +import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2Exception; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.PvpSProfileRequest; +import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafDefaultSaml2Bootstrap; import org.apache.commons.lang3.StringUtils; import org.opensaml.common.SAMLObject; import org.opensaml.common.binding.BasicSAMLMessageContext; @@ -56,117 +56,112 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; -import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.modules.pvp2.PVPConstants; -import at.gv.egiz.eaaf.modules.pvp2.api.binding.IDecoder; -import at.gv.egiz.eaaf.modules.pvp2.api.binding.IEncoder; -import at.gv.egiz.eaaf.modules.pvp2.api.message.InboundMessageInterface; -import at.gv.egiz.eaaf.modules.pvp2.exception.AttributQueryException; -import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; -import at.gv.egiz.eaaf.modules.pvp2.impl.message.PVPSProfileRequest; -import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EAAFDefaultSAML2Bootstrap; - @Service("PVPSOAPBinding") public class SoapBinding implements IDecoder, IEncoder { - private static final Logger log = LoggerFactory.getLogger(SoapBinding.class); - public InboundMessageInterface decode(HttpServletRequest req, - HttpServletResponse resp, MetadataProvider metadataProvider, boolean isSPEndPoint, URIComparator comparator) throws MessageDecodingException, - SecurityException, PVP2Exception { - HTTPSOAP11Decoder soapDecoder = new HTTPSOAP11Decoder(new BasicParserPool()); - BasicSAMLMessageContext messageContext = - new BasicSAMLMessageContext(); - messageContext - .setInboundMessageTransport(new HttpServletRequestAdapter( - req)); - messageContext.setMetadataProvider(metadataProvider); - - //TODO: update in a futher version: - // requires a special SignedSOAPRequestPolicyRole because - // messageContext.getInboundMessage() is not directly signed - - //set security context -// BasicSecurityPolicy policy = new BasicSecurityPolicy(); -// policy.getPolicyRules().add( -// new MOAPVPSignedRequestPolicyRule( -// TrustEngineFactory.getSignatureKnownKeysTrustEngine(), -// SPSSODescriptor.DEFAULT_ELEMENT_NAME)); -// SecurityPolicyResolver resolver = new StaticSecurityPolicyResolver( -// policy); -// messageContext.setSecurityPolicyResolver(resolver); - - //decode message - soapDecoder.decode(messageContext); - - Envelope inboundMessage = (Envelope) messageContext - .getInboundMessage(); - - if (inboundMessage.getBody() != null) { - List xmlElemList = inboundMessage.getBody().getUnknownXMLObjects(); - - if (!xmlElemList.isEmpty()) { - SignableXMLObject attrReq = (SignableXMLObject) xmlElemList.get(0); - PVPSProfileRequest request = new PVPSProfileRequest(attrReq, getSAML2BindingName()); - - if (messageContext.getPeerEntityMetadata() != null) - request.setEntityID(messageContext.getPeerEntityMetadata().getEntityID()); - - else if (attrReq instanceof RequestAbstractType) { - RequestAbstractType attributeRequest = (RequestAbstractType) attrReq; - try { - if (StringUtils.isNotEmpty(attributeRequest.getIssuer().getValue()) && - metadataProvider.getRole( - attributeRequest.getIssuer().getValue(), - SPSSODescriptor.DEFAULT_ELEMENT_NAME) != null) - request.setEntityID(attributeRequest.getIssuer().getValue()); - - } catch (Exception e) { - log.warn("No Metadata found with EntityID " + attributeRequest.getIssuer().getValue()); - } - } - - request.setVerified(false); - return request; - - } - } - - log.error("Receive empty PVP 2.1 attributequery request."); - throw new AttributQueryException("Receive empty PVP 2.1 attributequery request.", null); - } - - public boolean handleDecode(String action, HttpServletRequest req) { - return (req.getMethod().equals("POST") && - (action.equals(PVPConstants.SOAP) || action.equals(PVPConstants.ATTRIBUTEQUERY))); - } - - public void encodeRequest(HttpServletRequest req, HttpServletResponse resp, - RequestAbstractType request, String targetLocation, String relayState, Credential credentials, IRequest pendingReq) - throws MessageEncodingException, SecurityException, PVP2Exception { - - } - - public void encodeRespone(HttpServletRequest req, HttpServletResponse resp, - StatusResponseType response, String targetLocation, String relayState, Credential credentials, IRequest pendingReq) - throws MessageEncodingException, SecurityException, PVP2Exception { - - //load default PVP security configurations - EAAFDefaultSAML2Bootstrap.initializeDefaultPVPConfiguration(); - - HTTPSOAP11Encoder encoder = new HTTPSOAP11Encoder(); - HttpServletResponseAdapter responseAdapter = new HttpServletResponseAdapter( - resp, true); - BasicSAMLMessageContext context = new BasicSAMLMessageContext(); - context.setOutboundSAMLMessageSigningCredential(credentials); - context.setOutboundSAMLMessage(response); - context.setOutboundMessageTransport(responseAdapter); - - encoder.encode(context); - - } - - public String getSAML2BindingName() { - return SAMLConstants.SAML2_SOAP11_BINDING_URI; - } + private static final Logger log = LoggerFactory.getLogger(SoapBinding.class); + + @Override + public InboundMessageInterface decode(final HttpServletRequest req, + final HttpServletResponse resp, final MetadataProvider metadataProvider, + final boolean isSpEndPoint, final URIComparator comparator) + throws MessageDecodingException, SecurityException, Pvp2Exception { + final HTTPSOAP11Decoder soapDecoder = new HTTPSOAP11Decoder(new BasicParserPool()); + final BasicSAMLMessageContext messageContext = + new BasicSAMLMessageContext<>(); + messageContext.setInboundMessageTransport(new HttpServletRequestAdapter(req)); + messageContext.setMetadataProvider(metadataProvider); + + // TODO: update in a futher version: + // requires a special SignedSOAPRequestPolicyRole because + // messageContext.getInboundMessage() is not directly signed + + // set security context + // BasicSecurityPolicy policy = new BasicSecurityPolicy(); + // policy.getPolicyRules().add( + // new MOAPVPSignedRequestPolicyRule( + // TrustEngineFactory.getSignatureKnownKeysTrustEngine(), + // SPSSODescriptor.DEFAULT_ELEMENT_NAME)); + // SecurityPolicyResolver resolver = new StaticSecurityPolicyResolver( + // policy); + // messageContext.setSecurityPolicyResolver(resolver); + + // decode message + soapDecoder.decode(messageContext); + + final Envelope inboundMessage = (Envelope) messageContext.getInboundMessage(); + + if (inboundMessage.getBody() != null) { + final List xmlElemList = inboundMessage.getBody().getUnknownXMLObjects(); + + if (!xmlElemList.isEmpty()) { + final SignableXMLObject attrReq = (SignableXMLObject) xmlElemList.get(0); + final PvpSProfileRequest request = new PvpSProfileRequest(attrReq, getSaml2BindingName()); + + if (messageContext.getPeerEntityMetadata() != null) { + request.setEntityID(messageContext.getPeerEntityMetadata().getEntityID()); + } else if (attrReq instanceof RequestAbstractType) { + final RequestAbstractType attributeRequest = (RequestAbstractType) attrReq; + try { + if (StringUtils.isNotEmpty(attributeRequest.getIssuer().getValue()) + && metadataProvider.getRole(attributeRequest.getIssuer().getValue(), + SPSSODescriptor.DEFAULT_ELEMENT_NAME) != null) { + request.setEntityID(attributeRequest.getIssuer().getValue()); + } + + } catch (final Exception e) { + log.warn("No Metadata found with EntityID " + attributeRequest.getIssuer().getValue()); + } + } + + request.setVerified(false); + return request; + + } + } + + log.error("Receive empty PVP 2.1 attributequery request."); + throw new AttributQueryException("Receive empty PVP 2.1 attributequery request.", null); + } + + @Override + public boolean handleDecode(final String action, final HttpServletRequest req) { + return (req.getMethod().equals("POST") + && (action.equals(PvpConstants.SOAP) || action.equals(PvpConstants.ATTRIBUTEQUERY))); + } + + @Override + public void encodeRequest(final HttpServletRequest req, final HttpServletResponse resp, + final RequestAbstractType request, final String targetLocation, final String relayState, + final Credential credentials, final IRequest pendingReq) + throws MessageEncodingException, SecurityException, Pvp2Exception { + + } + + @Override + public void encodeRespone(final HttpServletRequest req, final HttpServletResponse resp, + final StatusResponseType response, final String targetLocation, final String relayState, + final Credential credentials, final IRequest pendingReq) + throws MessageEncodingException, SecurityException, Pvp2Exception { + + // load default PVP security configurations + EaafDefaultSaml2Bootstrap.initializeDefaultPvpConfiguration(); + + final HTTPSOAP11Encoder encoder = new HTTPSOAP11Encoder(); + final HttpServletResponseAdapter responseAdapter = new HttpServletResponseAdapter(resp, true); + final BasicSAMLMessageContext context = + new BasicSAMLMessageContext<>(); + context.setOutboundSAMLMessageSigningCredential(credentials); + context.setOutboundSAMLMessage(response); + context.setOutboundMessageTransport(responseAdapter); + + encoder.encode(context); + + } + + @Override + public String getSaml2BindingName() { + return SAMLConstants.SAML2_SOAP11_BINDING_URI; + } } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/CitizenTokenBuilder.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/CitizenTokenBuilder.java index c38b04bd..9765f520 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/CitizenTokenBuilder.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/CitizenTokenBuilder.java @@ -1,31 +1,25 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.impl.builder; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.Saml2Utils; import org.opensaml.saml2.core.Attribute; import org.opensaml.saml2.core.AttributeValue; import org.opensaml.xml.Configuration; @@ -35,87 +29,118 @@ import org.opensaml.xml.schema.XSString; import org.opensaml.xml.schema.impl.XSIntegerBuilder; import org.opensaml.xml.schema.impl.XSStringBuilder; -import at.gv.egiz.eaaf.modules.pvp2.impl.utils.SAML2Utils; - +/** + * Build all attributes from PVP2 citizen-token. + * + * @author tlenz + * + */ public class CitizenTokenBuilder { - public static XMLObject buildAttributeStringValue(String value) { - XSStringBuilder stringBuilder = (XSStringBuilder) Configuration.getBuilderFactory().getBuilder(XSString.TYPE_NAME); - XSString stringValue = stringBuilder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSString.TYPE_NAME); - stringValue.setValue(value); - return stringValue; - } - - public static XMLObject buildAttributeIntegerValue(int value) { - XSIntegerBuilder integerBuilder = (XSIntegerBuilder) Configuration.getBuilderFactory().getBuilder(XSInteger.TYPE_NAME); - XSInteger integerValue = integerBuilder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSInteger.TYPE_NAME); - integerValue.setValue(value); - return integerValue; - } - - public static Attribute buildStringAttribute(String friendlyName, - String name, String value) { - Attribute attribute = - SAML2Utils.createSAMLObject(Attribute.class); - attribute.setFriendlyName(friendlyName); - attribute.setName(name); - attribute.getAttributeValues().add(buildAttributeStringValue(value)); - return attribute; - } - - public static Attribute buildIntegerAttribute(String friendlyName, - String name, int value) { - Attribute attribute = - SAML2Utils.createSAMLObject(Attribute.class); - attribute.setFriendlyName(friendlyName); - attribute.setName(name); - attribute.getAttributeValues().add(buildAttributeIntegerValue(value)); - return attribute; - } - - public static Attribute buildPVPVersion(String value) { - return buildStringAttribute("PVP-VERSION", - "urn:oid:1.2.40.0.10.2.1.1.261.10", value); - } - - public static Attribute buildSecClass(int value) { - return buildIntegerAttribute("SECCLASS", - "", value); - } - - public static Attribute buildPrincipalName(String value) { - return buildStringAttribute("PRINCIPAL-NAME", - "urn:oid:1.2.40.0.10.2.1.1.261.20", value); - } - - public static Attribute buildGivenName(String value) { - return buildStringAttribute("GIVEN-NAME", - "urn:oid:2.5.4.42", value); - } - - public static Attribute buildBirthday(String value) { - return buildStringAttribute("BIRTHDATE", - "urn:oid:1.2.40.0.10.2.1.1.55", value); - } - - public static Attribute buildBPK(String value) { - return buildStringAttribute("BPK", - "urn:oid:1.2.40.0.10.2.1.1.149", value); - } - - public static Attribute buildEID_CITIZEN_QAALEVEL(int value) { - return buildIntegerAttribute("EID-CITIZEN-QAA-LEVEL", - "urn:oid:1.2.40.0.10.2.1.1.261.94", value); - } - - public static Attribute buildEID_ISSUING_NATION(String value) { - return buildStringAttribute("EID-ISSUING-NATION", - "urn:oid:1.2.40.0.10.2.1.1.261.32", value); - } - - public static Attribute buildEID_SECTOR_FOR_IDENTIFIER(String value) { - return buildStringAttribute("EID-SECTOR-FOR-IDENTIFIER", - "urn:oid:1.2.40.0.10.2.1.1.261.34", value); - } - + /** + * Build simple attribute. + * + * @param value Attributevalue + * @return XML attribute + */ + public static XMLObject buildAttributeStringValue(final String value) { + final XSStringBuilder stringBuilder = + (XSStringBuilder) Configuration.getBuilderFactory().getBuilder(XSString.TYPE_NAME); + final XSString stringValue = + stringBuilder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSString.TYPE_NAME); + stringValue.setValue(value); + return stringValue; + } + + /** + * Build simple attribute. + * + * @param value Attributevalue + * @return XML attribute + */ + public static XMLObject buildAttributeIntegerValue(final int value) { + final XSIntegerBuilder integerBuilder = + (XSIntegerBuilder) Configuration.getBuilderFactory().getBuilder(XSInteger.TYPE_NAME); + final XSInteger integerValue = + integerBuilder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSInteger.TYPE_NAME); + integerValue.setValue(value); + return integerValue; + } + + /** + * Build simple attribute. + * + * @param friendlyName attribute friendly-name + * @param value Attributevalue + * @return XML attribute + */ + public static Attribute buildStringAttribute(final String friendlyName, final String name, + final String value) { + final Attribute attribute = Saml2Utils.createSamlObject(Attribute.class); + attribute.setFriendlyName(friendlyName); + attribute.setName(name); + attribute.getAttributeValues().add(buildAttributeStringValue(value)); + return attribute; + } + + /** + * Build simple attribute. + * + * @param friendlyName attribute friendly-name + * @param value Attributevalue + * @return XML attribute + */ + public static Attribute buildIntegerAttribute(final String friendlyName, final String name, + final int value) { + final Attribute attribute = Saml2Utils.createSamlObject(Attribute.class); + attribute.setFriendlyName(friendlyName); + attribute.setName(name); + attribute.getAttributeValues().add(buildAttributeIntegerValue(value)); + return attribute; + } + + /** + * Build PVP version attribute. + * + * @param value PVP Version + * @return SAML2 Attribute + */ + public static Attribute buildPvpVersion(final String value) { + return buildStringAttribute("PVP-VERSION", "urn:oid:1.2.40.0.10.2.1.1.261.10", value); + } + + public static Attribute buildSecClass(final int value) { + return buildIntegerAttribute("SECCLASS", "", value); + } + + public static Attribute buildPrincipalName(final String value) { + return buildStringAttribute("PRINCIPAL-NAME", "urn:oid:1.2.40.0.10.2.1.1.261.20", value); + } + + public static Attribute buildGivenName(final String value) { + return buildStringAttribute("GIVEN-NAME", "urn:oid:2.5.4.42", value); + } + + public static Attribute buildBirthday(final String value) { + return buildStringAttribute("BIRTHDATE", "urn:oid:1.2.40.0.10.2.1.1.55", value); + } + + public static Attribute buildBpk(final String value) { + return buildStringAttribute("BPK", "urn:oid:1.2.40.0.10.2.1.1.149", value); + } + + public static Attribute buildEid_Citizen_QaaLevel(final int value) { + return buildIntegerAttribute("EID-CITIZEN-QAA-LEVEL", "urn:oid:1.2.40.0.10.2.1.1.261.94", + value); + } + + public static Attribute buildEid_Issuing_Nation(final String value) { + return buildStringAttribute("EID-ISSUING-NATION", "urn:oid:1.2.40.0.10.2.1.1.261.32", value); + } + + public static Attribute buildEid_Sector_For_Identifier(final String value) { + return buildStringAttribute("EID-SECTOR-FOR-IDENTIFIER", "urn:oid:1.2.40.0.10.2.1.1.261.34", + value); + } + } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/PVPAttributeBuilder.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/PVPAttributeBuilder.java deleted file mode 100644 index 0d9e38e0..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/PVPAttributeBuilder.java +++ /dev/null @@ -1,221 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.builder; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.ServiceLoader; - -import org.opensaml.saml2.core.Attribute; -import org.opensaml.saml2.metadata.RequestedAttribute; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder; -import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; -import at.gv.egiz.eaaf.core.exceptions.InvalidDateFormatAttributeException; -import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; -import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PVPMETADATA; -import at.gv.egiz.eaaf.modules.pvp2.exception.InvalidDateFormatException; -import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; -import at.gv.egiz.eaaf.modules.pvp2.impl.utils.SAML2Utils; - -public class PVPAttributeBuilder { - - private static final Logger log = LoggerFactory.getLogger(PVPAttributeBuilder.class); - - private static IAttributeGenerator generator = new SamlAttributeGenerator(); - private static HashMap builders; - - private static ServiceLoader attributBuilderLoader = - ServiceLoader.load(IAttributeBuilder.class); - - private static void addBuilder(IAttributeBuilder builder) { - builders.put(builder.getName(), builder); - } - - static { - builders = new HashMap(); - - log.info("Loading protocol attribut-builder modules:"); - if (attributBuilderLoader != null ) { - Iterator moduleLoaderInterator = attributBuilderLoader.iterator(); - while (moduleLoaderInterator.hasNext()) { - try { - IAttributeBuilder modul = moduleLoaderInterator.next(); - log.info("Loading attribut-builder Modul Information: " + modul.getName()); - addBuilder(modul); - - } catch(Throwable e) { - log.error("Check configuration! " + "Some attribute-builder modul" + - " is not a valid IAttributeBuilder", e); - } - } - } - - log.info("Loading attribute-builder modules done"); - - } - - - /** - * Get a specific attribute builder - * - * @param name Attribute-builder friendly name - * - * @return Attribute-builder with this name or null if builder does not exists - */ - public static IAttributeBuilder getAttributeBuilder(String name) { - return builders.get(name); - - } - - public static Attribute buildAttribute(String name, ISPConfiguration oaParam, - IAuthData authData) throws PVP2Exception, AttributeBuilderException { - if (builders.containsKey(name)) { - try { - return builders.get(name).build(oaParam, authData, generator); - } - catch (AttributeBuilderException e) { - if (e instanceof UnavailableAttributeException) { - throw e; - - } else if (e instanceof InvalidDateFormatAttributeException) { - throw new InvalidDateFormatException(); - - } else { - throw new UnavailableAttributeException(name); - - } - } - } - return null; - } - - public static Attribute buildEmptyAttribute(String name) { - if (builders.containsKey(name)) { - return builders.get(name).buildEmpty(generator); - } - return null; - } - - public static Attribute buildAttribute(String name, String value) { - if (builders.containsKey(name)) { - return builders.get(name).buildEmpty(generator); - } - return null; - } - - - /** - * Return all attributes that has a {@link PVPMETADATA} annotation - * - * @return - */ - public static List buildSupportedEmptyAttributes() { - List attributes = new ArrayList(); - Iterator builderIt = builders.values().iterator(); - while (builderIt.hasNext()) { - IAttributeBuilder builder = builderIt.next(); - if (builder.getClass().isAnnotationPresent(PVPMETADATA.class)) { - Attribute emptyAttribute = builder.buildEmpty(generator); - if (emptyAttribute != null) { - attributes.add(emptyAttribute); - } - - } else { - log.trace(builder.getName() + "is no PVP Metadata attribute"); - - } - } - return attributes; - } - - public static RequestedAttribute buildReqAttribute(String name, String friendlyName, boolean required) { - RequestedAttribute attribute = SAML2Utils.createSAMLObject(RequestedAttribute.class); - attribute.setIsRequired(required); - attribute.setName(name); - attribute.setFriendlyName(friendlyName); - attribute.setNameFormat(Attribute.URI_REFERENCE); - return attribute; - } - - /** - * Build a set of PVP Response-Attributes - *

    - * INFO: If a specific attribute can not be build, a info is logged, but no execpetion is thrown. - * Therefore, the return List must not include all requested attributes. - * - * @param authData AuthenticationData IAuthData which is used to build the attribute values, but never null - * @param reqAttributenName List of PVP attribute names which are requested, but never null - * @return List of PVP attributes, but never null - */ - public static List buildSetOfResponseAttributes(IAuthData authData, - Collection reqAttributenName) { - List attrList = new ArrayList(); - if (reqAttributenName != null) { - Iterator it = reqAttributenName.iterator(); - while (it.hasNext()) { - String reqAttributName = it.next(); - try { - Attribute attr = PVPAttributeBuilder.buildAttribute( - reqAttributName, null, authData); - if (attr == null) { - log.info( - "Attribute generation failed! for " - + reqAttributName); - - } else { - attrList.add(attr); - - } - - } catch (PVP2Exception e) { - log.info( - "Attribute generation failed! for " - + reqAttributName); - - } catch (Exception e) { - log.warn( - "General Attribute generation failed! for " - + reqAttributName, e); - - } - } - } - - return attrList; - } - - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/PVPMetadataBuilder.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/PVPMetadataBuilder.java deleted file mode 100644 index 61c6006b..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/PVPMetadataBuilder.java +++ /dev/null @@ -1,450 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.builder; - -import java.io.IOException; -import java.io.StringWriter; -import java.util.Collection; -import java.util.List; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.TransformerFactoryConfigurationError; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.apache.commons.httpclient.auth.CredentialsNotAvailableException; -import org.apache.commons.lang3.StringUtils; -import org.joda.time.DateTime; -import org.opensaml.Configuration; -import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.saml2.metadata.AssertionConsumerService; -import org.opensaml.saml2.metadata.AttributeConsumingService; -import org.opensaml.saml2.metadata.ContactPerson; -import org.opensaml.saml2.metadata.EntitiesDescriptor; -import org.opensaml.saml2.metadata.EntityDescriptor; -import org.opensaml.saml2.metadata.IDPSSODescriptor; -import org.opensaml.saml2.metadata.KeyDescriptor; -import org.opensaml.saml2.metadata.LocalizedString; -import org.opensaml.saml2.metadata.NameIDFormat; -import org.opensaml.saml2.metadata.Organization; -import org.opensaml.saml2.metadata.RequestedAttribute; -import org.opensaml.saml2.metadata.RoleDescriptor; -import org.opensaml.saml2.metadata.SPSSODescriptor; -import org.opensaml.saml2.metadata.ServiceName; -import org.opensaml.saml2.metadata.SingleLogoutService; -import org.opensaml.saml2.metadata.SingleSignOnService; -import org.opensaml.xml.io.Marshaller; -import org.opensaml.xml.io.MarshallingException; -import org.opensaml.xml.security.SecurityException; -import org.opensaml.xml.security.SecurityHelper; -import org.opensaml.xml.security.credential.Credential; -import org.opensaml.xml.security.credential.UsageType; -import org.opensaml.xml.security.keyinfo.KeyInfoGenerator; -import org.opensaml.xml.security.x509.X509KeyInfoGeneratorFactory; -import org.opensaml.xml.signature.Signature; -import org.opensaml.xml.signature.SignatureException; -import org.opensaml.xml.signature.Signer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; -import org.w3c.dom.Document; - -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPVPMetadataBuilderConfiguration; -import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EAAFDefaultSAML2Bootstrap; -import at.gv.egiz.eaaf.modules.pvp2.impl.utils.AbstractCredentialProvider; -import at.gv.egiz.eaaf.modules.pvp2.impl.utils.SAML2Utils; - -/** - * @author tlenz - * - */ - -@Service("PVPMetadataBuilder") -public class PVPMetadataBuilder { - - private static final Logger log = LoggerFactory.getLogger(PVPMetadataBuilder.class); - - X509KeyInfoGeneratorFactory keyInfoFactory = null; - - /** - * - */ - public PVPMetadataBuilder() { - keyInfoFactory = new X509KeyInfoGeneratorFactory(); - keyInfoFactory.setEmitEntityIDAsKeyName(true); - keyInfoFactory.setEmitEntityCertificate(true); - - } - - - /** - * - * Build PVP 2.1 conform SAML2 metadata - * - * @param config - * PVPMetadataBuilder configuration - * - * @return PVP metadata as XML String - * @throws SecurityException - * @throws ConfigurationException - * @throws CredentialsNotAvailableException - * @throws TransformerFactoryConfigurationError - * @throws MarshallingException - * @throws TransformerException - * @throws ParserConfigurationException - * @throws IOException - * @throws SignatureException - */ - public String buildPVPMetadata(IPVPMetadataBuilderConfiguration config) throws CredentialsNotAvailableException, EAAFException, SecurityException, TransformerFactoryConfigurationError, MarshallingException, TransformerException, ParserConfigurationException, IOException, SignatureException { - DateTime date = new DateTime(); - EntityDescriptor entityDescriptor = SAML2Utils - .createSAMLObject(EntityDescriptor.class); - - //set entityID - entityDescriptor.setEntityID(config.getEntityID()); - - //set contact and organisation information - List contactPersons = config.getContactPersonInformation(); - if (contactPersons != null) - entityDescriptor.getContactPersons().addAll(contactPersons); - - Organization organisation = config.getOrgansiationInformation(); - if (organisation != null) - entityDescriptor.setOrganization(organisation); - - //set IDP metadata - if (config.buildIDPSSODescriptor()) { - RoleDescriptor idpSSODesc = generateIDPMetadata(config); - if (idpSSODesc != null) - entityDescriptor.getRoleDescriptors().add(idpSSODesc); - - } - - //set SP metadata for interfederation - if (config.buildSPSSODescriptor()) { - RoleDescriptor spSSODesc = generateSPMetadata(config); - if (spSSODesc != null) - entityDescriptor.getRoleDescriptors().add(spSSODesc); - - } - - //set metadata signature parameters - Credential metadataSignCred = config.getMetadataSigningCredentials(); - Signature signature = AbstractCredentialProvider.getIDPSignature(metadataSignCred); - SecurityHelper.prepareSignatureParams(signature, metadataSignCred, null, null); - - //initialize XML document builder - DocumentBuilder builder; - DocumentBuilderFactory factory = DocumentBuilderFactory - .newInstance(); - - builder = factory.newDocumentBuilder(); - Document document = builder.newDocument(); - - - //build entities descriptor - if (config.buildEntitiesDescriptorAsRootElement()) { - EntitiesDescriptor entitiesDescriptor = - SAML2Utils.createSAMLObject(EntitiesDescriptor.class); - entitiesDescriptor.setName(config.getEntityFriendlyName()); - entitiesDescriptor.setID(SAML2Utils.getSecureIdentifier()); - entitiesDescriptor.setValidUntil(date.plusHours(config.getMetadataValidUntil())); - entitiesDescriptor.getEntityDescriptors().add(entityDescriptor); - - //load default PVP security configurations - EAAFDefaultSAML2Bootstrap.initializeDefaultPVPConfiguration(); - entitiesDescriptor.setSignature(signature); - - - //marshall document - Marshaller out = Configuration.getMarshallerFactory() - .getMarshaller(entitiesDescriptor); - out.marshall(entitiesDescriptor, document); - - } else { - entityDescriptor.setValidUntil(date.plusHours(config.getMetadataValidUntil())); - entityDescriptor.setID(SAML2Utils.getSecureIdentifier()); - - entityDescriptor.setSignature(signature); - - - - //marshall document - Marshaller out = Configuration.getMarshallerFactory() - .getMarshaller(entityDescriptor); - out.marshall(entityDescriptor, document); - - } - - //sign metadata - Signer.signObject(signature); - - //transform metadata object to XML string - Transformer transformer = TransformerFactory.newInstance() - .newTransformer(); - - StringWriter sw = new StringWriter(); - StreamResult sr = new StreamResult(sw); - DOMSource source = new DOMSource(document); - transformer.transform(source, sr); - sw.close(); - - return sw.toString(); - } - - - private RoleDescriptor generateSPMetadata(IPVPMetadataBuilderConfiguration config) throws CredentialsNotAvailableException, SecurityException, EAAFException { - SPSSODescriptor spSSODescriptor = SAML2Utils.createSAMLObject(SPSSODescriptor.class); - spSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); - spSSODescriptor.setAuthnRequestsSigned(config.wantAuthnRequestSigned()); - spSSODescriptor.setWantAssertionsSigned(config.wantAssertionSigned()); - - KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance(); - - //Set AuthRequest Signing certificate - Credential authcredential = config.getRequestorResponseSigningCredentials(); - if (authcredential == null) { - log.warn("SP Metadata generation FAILED! --> Builder has NO request signing-credential. "); - return null; - - } else { - KeyDescriptor signKeyDescriptor = SAML2Utils - .createSAMLObject(KeyDescriptor.class); - signKeyDescriptor.setUse(UsageType.SIGNING); - signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authcredential)); - spSSODescriptor.getKeyDescriptors().add(signKeyDescriptor); - - } - - //Set assertion encryption credentials - Credential authEncCredential = config.getEncryptionCredentials(); - - if (authEncCredential != null) { - KeyDescriptor encryKeyDescriptor = SAML2Utils - .createSAMLObject(KeyDescriptor.class); - encryKeyDescriptor.setUse(UsageType.ENCRYPTION); - encryKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authEncCredential)); - spSSODescriptor.getKeyDescriptors().add(encryKeyDescriptor); - - } else { - log.warn("No Assertion Encryption-Key defined. This setting is not recommended!"); - - } - - //check nameID formates - if (config.getSPAllowedNameITTypes() == null || config.getSPAllowedNameITTypes().size() == 0) { - log.warn("SP Metadata generation FAILED! --> Builder has NO provideable SAML2 nameIDFormats. "); - return null; - - } else { - for (String format : config.getSPAllowedNameITTypes()) { - NameIDFormat nameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); - nameIDFormat.setFormat(format); - spSSODescriptor.getNameIDFormats().add(nameIDFormat); - - } - } - - - //add POST-Binding assertion consumer services - if (StringUtils.isNotEmpty(config.getSPAssertionConsumerServicePostBindingURL())) { - AssertionConsumerService postassertionConsumerService = SAML2Utils.createSAMLObject(AssertionConsumerService.class); - postassertionConsumerService.setIndex(0); - postassertionConsumerService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); - postassertionConsumerService.setLocation(config.getSPAssertionConsumerServicePostBindingURL()); - postassertionConsumerService.setIsDefault(true); - spSSODescriptor.getAssertionConsumerServices().add(postassertionConsumerService); - - } - - //add POST-Binding assertion consumer services - if (StringUtils.isNotEmpty(config.getSPAssertionConsumerServiceRedirectBindingURL())) { - AssertionConsumerService redirectassertionConsumerService = SAML2Utils.createSAMLObject(AssertionConsumerService.class); - redirectassertionConsumerService.setIndex(1); - redirectassertionConsumerService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); - redirectassertionConsumerService.setLocation(config.getSPAssertionConsumerServiceRedirectBindingURL()); - spSSODescriptor.getAssertionConsumerServices().add(redirectassertionConsumerService); - - } - - //validate WebSSO endpoints - if (spSSODescriptor.getAssertionConsumerServices().size() == 0) { - log.warn("SP Metadata generation FAILED! --> NO SAML2 AssertionConsumerService endpoint found. "); - return null; - - } - - //add POST-Binding SLO descriptor - if (StringUtils.isNotEmpty(config.getSPSLOPostBindingURL())) { - SingleLogoutService postSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); - postSLOService.setLocation(config.getSPSLOPostBindingURL()); - postSLOService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); - spSSODescriptor.getSingleLogoutServices().add(postSLOService); - - } - - //add POST-Binding SLO descriptor - if (StringUtils.isNotEmpty(config.getSPSLORedirectBindingURL())) { - SingleLogoutService redirectSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); - redirectSLOService.setLocation(config.getSPSLORedirectBindingURL()); - redirectSLOService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); - spSSODescriptor.getSingleLogoutServices().add(redirectSLOService); - - } - - //add POST-Binding SLO descriptor - if (StringUtils.isNotEmpty(config.getSPSLOSOAPBindingURL())) { - SingleLogoutService soapSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); - soapSLOService.setLocation(config.getSPSLOSOAPBindingURL()); - soapSLOService.setBinding(SAMLConstants.SAML2_SOAP11_BINDING_URI); - spSSODescriptor.getSingleLogoutServices().add(soapSLOService); - - } - - - //add required attributes - Collection reqSPAttr = config.getSPRequiredAttributes(); - AttributeConsumingService attributeService = SAML2Utils.createSAMLObject(AttributeConsumingService.class); - - attributeService.setIndex(0); - attributeService.setIsDefault(true); - ServiceName serviceName = SAML2Utils.createSAMLObject(ServiceName.class); - serviceName.setName(new LocalizedString("Default Service", "en")); - attributeService.getNames().add(serviceName); - - if (reqSPAttr != null && reqSPAttr.size() > 0) { - log.debug("Add " + reqSPAttr.size() + " attributes to SP metadata"); - attributeService.getRequestAttributes().addAll(reqSPAttr); - - } else { - log.debug("SP metadata contains NO requested attributes."); - - } - - spSSODescriptor.getAttributeConsumingServices().add(attributeService); - - return spSSODescriptor; - } - - private IDPSSODescriptor generateIDPMetadata(IPVPMetadataBuilderConfiguration config) throws EAAFException, CredentialsNotAvailableException, SecurityException { - //check response signing credential - Credential responseSignCred = config.getRequestorResponseSigningCredentials(); - if (responseSignCred == null) { - log.warn("IDP Metadata generation FAILED! --> Builder has NO Response signing credential. "); - return null; - - } - - //check nameID formates - if (config.getIDPPossibleNameITTypes() == null || config.getIDPPossibleNameITTypes().size() == 0) { - log.warn("IDP Metadata generation FAILED! --> Builder has NO provideable SAML2 nameIDFormats. "); - return null; - - } - - // build SAML2 IDP-SSO descriptor element - IDPSSODescriptor idpSSODescriptor = SAML2Utils - .createSAMLObject(IDPSSODescriptor.class); - - idpSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); - - //set ass default value, because PVP 2.x specification defines this feature as MUST - idpSSODescriptor.setWantAuthnRequestsSigned(config.wantAuthnRequestSigned()); - - // add WebSSO descriptor for POST-Binding - if (StringUtils.isNotEmpty(config.getIDPWebSSOPostBindingURL())) { - SingleSignOnService postSingleSignOnService = SAML2Utils.createSAMLObject(SingleSignOnService.class); - postSingleSignOnService.setLocation(config.getIDPWebSSOPostBindingURL()); - postSingleSignOnService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); - idpSSODescriptor.getSingleSignOnServices().add(postSingleSignOnService); - - } - - // add WebSSO descriptor for Redirect-Binding - if (StringUtils.isNotEmpty(config.getIDPWebSSORedirectBindingURL())) { - SingleSignOnService postSingleSignOnService = SAML2Utils.createSAMLObject(SingleSignOnService.class); - postSingleSignOnService.setLocation(config.getIDPWebSSORedirectBindingURL()); - postSingleSignOnService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); - idpSSODescriptor.getSingleSignOnServices().add(postSingleSignOnService); - - } - - //add Single LogOut POST-Binding endpoing - if (StringUtils.isNotEmpty(config.getIDPSLOPostBindingURL())) { - SingleLogoutService postSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); - postSLOService.setLocation(config.getIDPSLOPostBindingURL()); - postSLOService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); - idpSSODescriptor.getSingleLogoutServices().add(postSLOService); - - } - - //add Single LogOut Redirect-Binding endpoing - if (StringUtils.isNotEmpty(config.getIDPSLORedirectBindingURL())) { - SingleLogoutService redirectSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); - redirectSLOService.setLocation(config.getIDPSLORedirectBindingURL()); - redirectSLOService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); - idpSSODescriptor.getSingleLogoutServices().add(redirectSLOService); - - } - - //validate WebSSO endpoints - if (idpSSODescriptor.getSingleSignOnServices().size() == 0) { - log.warn("IDP Metadata generation FAILED! --> NO SAML2 SingleSignOnService endpoint found. "); - return null; - - } - - //set assertion signing key - KeyDescriptor signKeyDescriptor = SAML2Utils - .createSAMLObject(KeyDescriptor.class); - signKeyDescriptor.setUse(UsageType.SIGNING); - KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance(); - signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(config.getRequestorResponseSigningCredentials())); - idpSSODescriptor.getKeyDescriptors().add(signKeyDescriptor); - - //set IDP attribute set - idpSSODescriptor.getAttributes().addAll(config.getIDPPossibleAttributes()); - - //set providable nameID formats - for (String format : config.getIDPPossibleNameITTypes()) { - NameIDFormat nameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); - nameIDFormat.setFormat(format); - idpSSODescriptor.getNameIDFormats().add(nameIDFormat); - - } - - return idpSSODescriptor; - - } - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/PvpAttributeBuilder.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/PvpAttributeBuilder.java new file mode 100644 index 00000000..73ba73c7 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/PvpAttributeBuilder.java @@ -0,0 +1,244 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.impl.builder; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.ServiceLoader; +import at.gv.egiz.eaaf.core.api.idp.IAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.exceptions.InvalidDateFormatAttributeException; +import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; +import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PvpMetadata; +import at.gv.egiz.eaaf.modules.pvp2.exception.InvalidDateFormatException; +import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2Exception; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.Saml2Utils; +import org.opensaml.saml2.core.Attribute; +import org.opensaml.saml2.metadata.RequestedAttribute; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class PvpAttributeBuilder { + + private static final Logger log = LoggerFactory.getLogger(PvpAttributeBuilder.class); + + private static IAttributeGenerator generator = new SamlAttributeGenerator(); + private static HashMap builders; + + private static ServiceLoader attributBuilderLoader = + ServiceLoader.load(IAttributeBuilder.class); + + private static void addBuilder(final IAttributeBuilder builder) { + builders.put(builder.getName(), builder); + } + + static { + builders = new HashMap<>(); + + log.info("Loading protocol attribut-builder modules:"); + if (attributBuilderLoader != null) { + final Iterator moduleLoaderInterator = attributBuilderLoader.iterator(); + while (moduleLoaderInterator.hasNext()) { + try { + final IAttributeBuilder modul = moduleLoaderInterator.next(); + log.info("Loading attribut-builder Modul Information: " + modul.getName()); + addBuilder(modul); + + } catch (final Throwable e) { + log.error("Check configuration! " + "Some attribute-builder modul" + + " is not a valid IAttributeBuilder", e); + } + } + } + + log.info("Loading attribute-builder modules done"); + + } + + + /** + * Get a specific attribute builder. + * + * @param name Attribute-builder friendly name + * + * @return Attribute-builder with this name or null if builder does not exists + */ + public static IAttributeBuilder getAttributeBuilder(final String name) { + return builders.get(name); + + } + + /** + * Build an SAML2 attribute. + * + * @param name attribute name + * @param value attribute value + * @return SAML2 attribute + */ + public static Attribute buildAttribute(final String name, final String value) { + log.warn("Attribute value: {} is NOT injected", value); + + if (builders.containsKey(name)) { + return builders.get(name).buildEmpty(generator); + } + return null; + } + + /** + * Build a SAML2 attribute. + * + * @param name attribute name + * @param oaParam Service-Provider configuration + * @param authData serice-provider specific authentication data + * @return SAML2 attribute + * @throws Pvp2Exception In case of a general error + * @throws AttributeBuilderException In case of an attribute builder error + */ + public static Attribute buildAttribute(final String name, final IspConfiguration oaParam, + final IAuthData authData) throws Pvp2Exception, AttributeBuilderException { + if (builders.containsKey(name)) { + try { + return builders.get(name).build(oaParam, authData, generator); + } catch (final AttributeBuilderException e) { + if (e instanceof UnavailableAttributeException) { + throw e; + + } else if (e instanceof InvalidDateFormatAttributeException) { + throw new InvalidDateFormatException(); + + } else { + throw new UnavailableAttributeException(name); + + } + } + } + return null; + } + + /** + * Build an empty attribute. + * + * @param name attributename + * @return SAML2 attribute + */ + public static Attribute buildEmptyAttribute(final String name) { + if (builders.containsKey(name)) { + return builders.get(name).buildEmpty(generator); + } + return null; + } + + + + + + /** + * Return all attributes that has a {@link PvpMetadata} annotation. + * + * @return + */ + public static List buildSupportedEmptyAttributes() { + final List attributes = new ArrayList<>(); + final Iterator builderIt = builders.values().iterator(); + while (builderIt.hasNext()) { + final IAttributeBuilder builder = builderIt.next(); + if (builder.getClass().isAnnotationPresent(PvpMetadata.class)) { + final Attribute emptyAttribute = builder.buildEmpty(generator); + if (emptyAttribute != null) { + attributes.add(emptyAttribute); + } + + } else { + log.trace(builder.getName() + "is no PVP Metadata attribute"); + + } + } + return attributes; + } + + /** + * Build a requested attribute. + * + * @param name attribute name + * @param friendlyName attribute friendlyname + * @param required is attribute mandatory + * @return SAML2 requested attribute + */ + public static RequestedAttribute buildReqAttribute(final String name, final String friendlyName, + final boolean required) { + final RequestedAttribute attribute = Saml2Utils.createSamlObject(RequestedAttribute.class); + attribute.setIsRequired(required); + attribute.setName(name); + attribute.setFriendlyName(friendlyName); + attribute.setNameFormat(Attribute.URI_REFERENCE); + return attribute; + } + + /** + * Build a set of PVP Response-Attributes
    + *
    + * INFO: If a specific attribute can not be build, a info is logged, but no execpetion is + * thrown. Therefore, the return List must not include all requested attributes. + * + * @param authData AuthenticationData IAuthData which is used to build the attribute + * values, but never null + * @param reqAttributenName List of PVP attribute names which are requested, but never + * null + * @return List of PVP attributes, but never null + */ + public static List buildSetOfResponseAttributes(final IAuthData authData, + final Collection reqAttributenName) { + final List attrList = new ArrayList<>(); + if (reqAttributenName != null) { + final Iterator it = reqAttributenName.iterator(); + while (it.hasNext()) { + final String reqAttributName = it.next(); + try { + final Attribute attr = + PvpAttributeBuilder.buildAttribute(reqAttributName, null, authData); + if (attr == null) { + log.info("Attribute generation failed! for " + reqAttributName); + + } else { + attrList.add(attr); + + } + + } catch (final Pvp2Exception e) { + log.info("Attribute generation failed! for " + reqAttributName); + + } catch (final Exception e) { + log.warn("General Attribute generation failed! for " + reqAttributName, e); + + } + } + } + + return attrList; + } + + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/PvpMetadataBuilder.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/PvpMetadataBuilder.java new file mode 100644 index 00000000..1efa8745 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/PvpMetadataBuilder.java @@ -0,0 +1,458 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.impl.builder; + +import java.io.IOException; +import java.io.StringWriter; +import java.util.Collection; +import java.util.List; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.TransformerFactoryConfigurationError; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPvpMetadataBuilderConfiguration; +import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafDefaultSaml2Bootstrap; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.AbstractCredentialProvider; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.Saml2Utils; +import org.apache.commons.httpclient.auth.CredentialsNotAvailableException; +import org.apache.commons.lang3.StringUtils; +import org.joda.time.DateTime; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.AssertionConsumerService; +import org.opensaml.saml2.metadata.AttributeConsumingService; +import org.opensaml.saml2.metadata.ContactPerson; +import org.opensaml.saml2.metadata.EntitiesDescriptor; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.IDPSSODescriptor; +import org.opensaml.saml2.metadata.KeyDescriptor; +import org.opensaml.saml2.metadata.LocalizedString; +import org.opensaml.saml2.metadata.NameIDFormat; +import org.opensaml.saml2.metadata.Organization; +import org.opensaml.saml2.metadata.RequestedAttribute; +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.saml2.metadata.SPSSODescriptor; +import org.opensaml.saml2.metadata.ServiceName; +import org.opensaml.saml2.metadata.SingleLogoutService; +import org.opensaml.saml2.metadata.SingleSignOnService; +import org.opensaml.xml.io.Marshaller; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.security.SecurityException; +import org.opensaml.xml.security.SecurityHelper; +import org.opensaml.xml.security.credential.Credential; +import org.opensaml.xml.security.credential.UsageType; +import org.opensaml.xml.security.keyinfo.KeyInfoGenerator; +import org.opensaml.xml.security.x509.X509KeyInfoGeneratorFactory; +import org.opensaml.xml.signature.Signature; +import org.opensaml.xml.signature.SignatureException; +import org.opensaml.xml.signature.Signer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.w3c.dom.Document; + +/** + * PVP metadata builder implementation. + * + * @author tlenz + * + */ + +@Service("PVPMetadataBuilder") +public class PvpMetadataBuilder { + + private static final Logger log = LoggerFactory.getLogger(PvpMetadataBuilder.class); + + X509KeyInfoGeneratorFactory keyInfoFactory = null; + + /** + * PVP metadata builder. + * + */ + public PvpMetadataBuilder() { + keyInfoFactory = new X509KeyInfoGeneratorFactory(); + keyInfoFactory.setEmitEntityIDAsKeyName(true); + keyInfoFactory.setEmitEntityCertificate(true); + + } + + + /** + * Build PVP 2.1 conform SAML2 metadata. + * + * @param config PVPMetadataBuilder configuration* + * @return PVP metadata as XML String + * @throws SecurityException In case of an error + * @throws ConfigurationException In case of an error + * @throws CredentialsNotAvailableException In case of an error + * @throws TransformerFactoryConfigurationError In case of an error + * @throws MarshallingException In case of an error + * @throws TransformerException In case of an error + * @throws ParserConfigurationException In case of an error + * @throws IOException In case of an error + * @throws SignatureException In case of an error + */ + public String buildPvpMetadata(final IPvpMetadataBuilderConfiguration config) + throws CredentialsNotAvailableException, EaafException, SecurityException, + TransformerFactoryConfigurationError, MarshallingException, TransformerException, + ParserConfigurationException, IOException, SignatureException { + final DateTime date = new DateTime(); + final EntityDescriptor entityDescriptor = Saml2Utils.createSamlObject(EntityDescriptor.class); + + // set entityID + entityDescriptor.setEntityID(config.getEntityID()); + + // set contact and organisation information + final List contactPersons = config.getContactPersonInformation(); + if (contactPersons != null) { + entityDescriptor.getContactPersons().addAll(contactPersons); + } + + final Organization organisation = config.getOrgansiationInformation(); + if (organisation != null) { + entityDescriptor.setOrganization(organisation); + } + + // set IDP metadata + if (config.buildIdpSsoDescriptor()) { + final RoleDescriptor idpSsoDesc = generateIdpMetadata(config); + if (idpSsoDesc != null) { + entityDescriptor.getRoleDescriptors().add(idpSsoDesc); + } + + } + + // set SP metadata for interfederation + if (config.buildSpSsoDescriptor()) { + final RoleDescriptor spSsoDesc = generateSpMetadata(config); + if (spSsoDesc != null) { + entityDescriptor.getRoleDescriptors().add(spSsoDesc); + } + + } + + // set metadata signature parameters + final Credential metadataSignCred = config.getMetadataSigningCredentials(); + final Signature signature = AbstractCredentialProvider.getIdpSignature(metadataSignCred); + SecurityHelper.prepareSignatureParams(signature, metadataSignCred, null, null); + + // initialize XML document builder + DocumentBuilder builder; + final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + + builder = factory.newDocumentBuilder(); + final Document document = builder.newDocument(); + + + // build entities descriptor + if (config.buildEntitiesDescriptorAsRootElement()) { + final EntitiesDescriptor entitiesDescriptor = + Saml2Utils.createSamlObject(EntitiesDescriptor.class); + entitiesDescriptor.setName(config.getEntityFriendlyName()); + entitiesDescriptor.setID(Saml2Utils.getSecureIdentifier()); + entitiesDescriptor.setValidUntil(date.plusHours(config.getMetadataValidUntil())); + entitiesDescriptor.getEntityDescriptors().add(entityDescriptor); + + // load default PVP security configurations + EaafDefaultSaml2Bootstrap.initializeDefaultPvpConfiguration(); + entitiesDescriptor.setSignature(signature); + + + // marshall document + final Marshaller out = + org.opensaml.xml.Configuration.getMarshallerFactory().getMarshaller(entitiesDescriptor); + out.marshall(entitiesDescriptor, document); + + } else { + entityDescriptor.setValidUntil(date.plusHours(config.getMetadataValidUntil())); + entityDescriptor.setID(Saml2Utils.getSecureIdentifier()); + + entityDescriptor.setSignature(signature); + + + + // marshall document + final Marshaller out = + org.opensaml.xml.Configuration.getMarshallerFactory().getMarshaller(entityDescriptor); + out.marshall(entityDescriptor, document); + + } + + // sign metadata + Signer.signObject(signature); + + // transform metadata object to XML string + final Transformer transformer = TransformerFactory.newInstance().newTransformer(); + + final StringWriter sw = new StringWriter(); + final StreamResult sr = new StreamResult(sw); + final DOMSource source = new DOMSource(document); + transformer.transform(source, sr); + sw.close(); + + return sw.toString(); + } + + + private RoleDescriptor generateSpMetadata(final IPvpMetadataBuilderConfiguration config) + throws CredentialsNotAvailableException, SecurityException, EaafException { + final SPSSODescriptor spSsoDescriptor = Saml2Utils.createSamlObject(SPSSODescriptor.class); + spSsoDescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); + spSsoDescriptor.setAuthnRequestsSigned(config.wantAuthnRequestSigned()); + spSsoDescriptor.setWantAssertionsSigned(config.wantAssertionSigned()); + + final KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance(); + + // Set AuthRequest Signing certificate + final Credential authcredential = config.getRequestorResponseSigningCredentials(); + if (authcredential == null) { + log.warn("SP Metadata generation FAILED! --> Builder has NO request signing-credential. "); + return null; + + } else { + final KeyDescriptor signKeyDescriptor = Saml2Utils.createSamlObject(KeyDescriptor.class); + signKeyDescriptor.setUse(UsageType.SIGNING); + signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authcredential)); + spSsoDescriptor.getKeyDescriptors().add(signKeyDescriptor); + + } + + // Set assertion encryption credentials + final Credential authEncCredential = config.getEncryptionCredentials(); + + if (authEncCredential != null) { + final KeyDescriptor encryKeyDescriptor = Saml2Utils.createSamlObject(KeyDescriptor.class); + encryKeyDescriptor.setUse(UsageType.ENCRYPTION); + encryKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authEncCredential)); + spSsoDescriptor.getKeyDescriptors().add(encryKeyDescriptor); + + } else { + log.warn("No Assertion Encryption-Key defined. This setting is not recommended!"); + + } + + // check nameID formates + if (config.getSpAllowedNameIdTypes() == null || config.getSpAllowedNameIdTypes().size() == 0) { + log.warn( + "SP Metadata generation FAILED! --> Builder has NO provideable SAML2 nameIDFormats. "); + return null; + + } else { + for (final String format : config.getSpAllowedNameIdTypes()) { + final NameIDFormat nameIdFormat = Saml2Utils.createSamlObject(NameIDFormat.class); + nameIdFormat.setFormat(format); + spSsoDescriptor.getNameIDFormats().add(nameIdFormat); + + } + } + + + // add POST-Binding assertion consumer services + if (StringUtils.isNotEmpty(config.getSpAssertionConsumerServicePostBindingUrl())) { + final AssertionConsumerService postassertionConsumerService = + Saml2Utils.createSamlObject(AssertionConsumerService.class); + postassertionConsumerService.setIndex(0); + postassertionConsumerService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); + postassertionConsumerService + .setLocation(config.getSpAssertionConsumerServicePostBindingUrl()); + postassertionConsumerService.setIsDefault(true); + spSsoDescriptor.getAssertionConsumerServices().add(postassertionConsumerService); + + } + + // add POST-Binding assertion consumer services + if (StringUtils.isNotEmpty(config.getSpAssertionConsumerServiceRedirectBindingUrl())) { + final AssertionConsumerService redirectassertionConsumerService = + Saml2Utils.createSamlObject(AssertionConsumerService.class); + redirectassertionConsumerService.setIndex(1); + redirectassertionConsumerService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); + redirectassertionConsumerService + .setLocation(config.getSpAssertionConsumerServiceRedirectBindingUrl()); + spSsoDescriptor.getAssertionConsumerServices().add(redirectassertionConsumerService); + + } + + // validate WebSSO endpoints + if (spSsoDescriptor.getAssertionConsumerServices().size() == 0) { + log.warn( + "SP Metadata generation FAILED! --> NO SAML2 AssertionConsumerService endpoint found. "); + return null; + + } + + // add POST-Binding SLO descriptor + if (StringUtils.isNotEmpty(config.getSpSloPostBindingUrl())) { + final SingleLogoutService postSloService = + Saml2Utils.createSamlObject(SingleLogoutService.class); + postSloService.setLocation(config.getSpSloPostBindingUrl()); + postSloService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); + spSsoDescriptor.getSingleLogoutServices().add(postSloService); + + } + + // add POST-Binding SLO descriptor + if (StringUtils.isNotEmpty(config.getSpSloRedirectBindingUrl())) { + final SingleLogoutService redirectSloService = + Saml2Utils.createSamlObject(SingleLogoutService.class); + redirectSloService.setLocation(config.getSpSloRedirectBindingUrl()); + redirectSloService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); + spSsoDescriptor.getSingleLogoutServices().add(redirectSloService); + + } + + // add POST-Binding SLO descriptor + if (StringUtils.isNotEmpty(config.getSpSloSoapBindingUrl())) { + final SingleLogoutService soapSloService = + Saml2Utils.createSamlObject(SingleLogoutService.class); + soapSloService.setLocation(config.getSpSloSoapBindingUrl()); + soapSloService.setBinding(SAMLConstants.SAML2_SOAP11_BINDING_URI); + spSsoDescriptor.getSingleLogoutServices().add(soapSloService); + + } + + + // add required attributes + final Collection reqSpAttr = config.getSpRequiredAttributes(); + final AttributeConsumingService attributeService = + Saml2Utils.createSamlObject(AttributeConsumingService.class); + + attributeService.setIndex(0); + attributeService.setIsDefault(true); + final ServiceName serviceName = Saml2Utils.createSamlObject(ServiceName.class); + serviceName.setName(new LocalizedString("Default Service", "en")); + attributeService.getNames().add(serviceName); + + if (reqSpAttr != null && reqSpAttr.size() > 0) { + log.debug("Add " + reqSpAttr.size() + " attributes to SP metadata"); + attributeService.getRequestAttributes().addAll(reqSpAttr); + + } else { + log.debug("SP metadata contains NO requested attributes."); + + } + + spSsoDescriptor.getAttributeConsumingServices().add(attributeService); + + return spSsoDescriptor; + } + + private IDPSSODescriptor generateIdpMetadata(final IPvpMetadataBuilderConfiguration config) + throws EaafException, CredentialsNotAvailableException, SecurityException { + // check response signing credential + final Credential responseSignCred = config.getRequestorResponseSigningCredentials(); + if (responseSignCred == null) { + log.warn("IDP Metadata generation FAILED! --> Builder has NO Response signing credential. "); + return null; + + } + + // check nameID formates + if (config.getIdpPossibleNameIdTypes() == null + || config.getIdpPossibleNameIdTypes().size() == 0) { + log.warn( + "IDP Metadata generation FAILED! --> Builder has NO provideable SAML2 nameIDFormats. "); + return null; + + } + + // build SAML2 IDP-SSO descriptor element + final IDPSSODescriptor idpSsoDescriptor = Saml2Utils.createSamlObject(IDPSSODescriptor.class); + + idpSsoDescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); + + // set ass default value, because PVP 2.x specification defines this feature as MUST + idpSsoDescriptor.setWantAuthnRequestsSigned(config.wantAuthnRequestSigned()); + + // add WebSSO descriptor for POST-Binding + if (StringUtils.isNotEmpty(config.getIdpWebSsoPostBindingUrl())) { + final SingleSignOnService postSingleSignOnService = + Saml2Utils.createSamlObject(SingleSignOnService.class); + postSingleSignOnService.setLocation(config.getIdpWebSsoPostBindingUrl()); + postSingleSignOnService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); + idpSsoDescriptor.getSingleSignOnServices().add(postSingleSignOnService); + + } + + // add WebSSO descriptor for Redirect-Binding + if (StringUtils.isNotEmpty(config.getIdpWebSsoRedirectBindingUrl())) { + final SingleSignOnService postSingleSignOnService = + Saml2Utils.createSamlObject(SingleSignOnService.class); + postSingleSignOnService.setLocation(config.getIdpWebSsoRedirectBindingUrl()); + postSingleSignOnService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); + idpSsoDescriptor.getSingleSignOnServices().add(postSingleSignOnService); + + } + + // add Single LogOut POST-Binding endpoing + if (StringUtils.isNotEmpty(config.getIdpSloPostBindingUrl())) { + final SingleLogoutService postSloService = + Saml2Utils.createSamlObject(SingleLogoutService.class); + postSloService.setLocation(config.getIdpSloPostBindingUrl()); + postSloService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); + idpSsoDescriptor.getSingleLogoutServices().add(postSloService); + + } + + // add Single LogOut Redirect-Binding endpoing + if (StringUtils.isNotEmpty(config.getIdpSloRedirectBindingUrl())) { + final SingleLogoutService redirectSloService = + Saml2Utils.createSamlObject(SingleLogoutService.class); + redirectSloService.setLocation(config.getIdpSloRedirectBindingUrl()); + redirectSloService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); + idpSsoDescriptor.getSingleLogoutServices().add(redirectSloService); + + } + + // validate WebSSO endpoints + if (idpSsoDescriptor.getSingleSignOnServices().size() == 0) { + log.warn("IDP Metadata generation FAILED! --> NO SAML2 SingleSignOnService endpoint found. "); + return null; + + } + + // set assertion signing key + final KeyDescriptor signKeyDescriptor = Saml2Utils.createSamlObject(KeyDescriptor.class); + signKeyDescriptor.setUse(UsageType.SIGNING); + final KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance(); + signKeyDescriptor + .setKeyInfo(keyInfoGenerator.generate(config.getRequestorResponseSigningCredentials())); + idpSsoDescriptor.getKeyDescriptors().add(signKeyDescriptor); + + // set IDP attribute set + idpSsoDescriptor.getAttributes().addAll(config.getIdpPossibleAttributes()); + + // set providable nameID formats + for (final String format : config.getIdpPossibleNameIdTypes()) { + final NameIDFormat nameIdFormat = Saml2Utils.createSamlObject(NameIDFormat.class); + nameIdFormat.setFormat(format); + idpSsoDescriptor.getNameIDFormats().add(nameIdFormat); + + } + + return idpSsoDescriptor; + + } + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/SamlAttributeGenerator.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/SamlAttributeGenerator.java index cb4a4608..559a3959 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/SamlAttributeGenerator.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/SamlAttributeGenerator.java @@ -1,31 +1,26 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.impl.builder; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.Saml2Utils; import org.opensaml.saml2.core.Attribute; import org.opensaml.saml2.core.AttributeValue; import org.opensaml.xml.Configuration; @@ -35,58 +30,66 @@ import org.opensaml.xml.schema.XSString; import org.opensaml.xml.schema.impl.XSIntegerBuilder; import org.opensaml.xml.schema.impl.XSStringBuilder; -import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; -import at.gv.egiz.eaaf.modules.pvp2.impl.utils.SAML2Utils; - public class SamlAttributeGenerator implements IAttributeGenerator { - - private XMLObject buildAttributeStringValue(String value) { - XSStringBuilder stringBuilder = (XSStringBuilder) Configuration.getBuilderFactory().getBuilder(XSString.TYPE_NAME); - XSString stringValue = stringBuilder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSString.TYPE_NAME); - stringValue.setValue(value); - return stringValue; - } - - private XMLObject buildAttributeIntegerValue(int value) { - XSIntegerBuilder integerBuilder = (XSIntegerBuilder) Configuration.getBuilderFactory().getBuilder(XSInteger.TYPE_NAME); - XSInteger integerValue = integerBuilder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSInteger.TYPE_NAME); - integerValue.setValue(value); - return integerValue; - } - - public Attribute buildStringAttribute(final String friendlyName, final String name, final String value) { - Attribute attribute = SAML2Utils.createSAMLObject(Attribute.class); - attribute.setFriendlyName(friendlyName); - attribute.setName(name); - attribute.setNameFormat(Attribute.URI_REFERENCE); - attribute.getAttributeValues().add(buildAttributeStringValue(value)); - return attribute; - } - - public Attribute buildIntegerAttribute(final String friendlyName, final String name, final int value) { - Attribute attribute = SAML2Utils.createSAMLObject(Attribute.class); - attribute.setFriendlyName(friendlyName); - attribute.setName(name); - attribute.setNameFormat(Attribute.URI_REFERENCE); - attribute.getAttributeValues().add(buildAttributeIntegerValue(value)); - return attribute; - } - - public Attribute buildEmptyAttribute(final String friendlyName, final String name) { - Attribute attribute = SAML2Utils.createSAMLObject(Attribute.class); - attribute.setFriendlyName(friendlyName); - attribute.setName(name); - attribute.setNameFormat(Attribute.URI_REFERENCE); - return attribute; - } - public Attribute buildLongAttribute(String friendlyName, String name, long value) { - Attribute attribute = SAML2Utils.createSAMLObject(Attribute.class); - attribute.setFriendlyName(friendlyName); - attribute.setName(name); - attribute.setNameFormat(Attribute.URI_REFERENCE); - attribute.getAttributeValues().add(buildAttributeIntegerValue((int) value)); - return attribute; - } - + private XMLObject buildAttributeStringValue(final String value) { + final XSStringBuilder stringBuilder = + (XSStringBuilder) Configuration.getBuilderFactory().getBuilder(XSString.TYPE_NAME); + final XSString stringValue = + stringBuilder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSString.TYPE_NAME); + stringValue.setValue(value); + return stringValue; + } + + private XMLObject buildAttributeIntegerValue(final int value) { + final XSIntegerBuilder integerBuilder = + (XSIntegerBuilder) Configuration.getBuilderFactory().getBuilder(XSInteger.TYPE_NAME); + final XSInteger integerValue = + integerBuilder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSInteger.TYPE_NAME); + integerValue.setValue(value); + return integerValue; + } + + @Override + public Attribute buildStringAttribute(final String friendlyName, final String name, + final String value) { + final Attribute attribute = Saml2Utils.createSamlObject(Attribute.class); + attribute.setFriendlyName(friendlyName); + attribute.setName(name); + attribute.setNameFormat(Attribute.URI_REFERENCE); + attribute.getAttributeValues().add(buildAttributeStringValue(value)); + return attribute; + } + + @Override + public Attribute buildIntegerAttribute(final String friendlyName, final String name, + final int value) { + final Attribute attribute = Saml2Utils.createSamlObject(Attribute.class); + attribute.setFriendlyName(friendlyName); + attribute.setName(name); + attribute.setNameFormat(Attribute.URI_REFERENCE); + attribute.getAttributeValues().add(buildAttributeIntegerValue(value)); + return attribute; + } + + @Override + public Attribute buildEmptyAttribute(final String friendlyName, final String name) { + final Attribute attribute = Saml2Utils.createSamlObject(Attribute.class); + attribute.setFriendlyName(friendlyName); + attribute.setName(name); + attribute.setNameFormat(Attribute.URI_REFERENCE); + return attribute; + } + + @Override + public Attribute buildLongAttribute(final String friendlyName, final String name, + final long value) { + final Attribute attribute = Saml2Utils.createSamlObject(Attribute.class); + attribute.setFriendlyName(friendlyName); + attribute.setName(name); + attribute.setNameFormat(Attribute.URI_REFERENCE); + attribute.getAttributeValues().add(buildAttributeIntegerValue((int) value)); + return attribute; + } + } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFExtensionImplementation.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFExtensionImplementation.java deleted file mode 100644 index 817ca2f6..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFExtensionImplementation.java +++ /dev/null @@ -1,36 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr; - -import org.opensaml.saml2.common.impl.ExtensionsImpl; - -public class EAAFExtensionImplementation extends ExtensionsImpl { - - protected EAAFExtensionImplementation(String namespaceURI, String elementLocalName, String namespacePrefix) { - super(namespaceURI, elementLocalName, namespacePrefix); - - } - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestExtensionBuilder.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestExtensionBuilder.java deleted file mode 100644 index 431784cf..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestExtensionBuilder.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr; - -import org.opensaml.common.impl.AbstractSAMLObjectBuilder; -import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.saml2.common.Extensions; - -public class EAAFRequestExtensionBuilder extends AbstractSAMLObjectBuilder { - - @Override - public Extensions buildObject() { - return buildObject(SAMLConstants.SAML20P_NS, Extensions.LOCAL_NAME, SAMLConstants.SAML20P_PREFIX); - - } - - @Override - public Extensions buildObject(String namespaceURI, String localName, String namespacePrefix) { - return new EAAFExtensionImplementation(namespaceURI, localName, namespacePrefix); - - } - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestedAttributeBuilder.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestedAttributeBuilder.java deleted file mode 100644 index 33868544..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestedAttributeBuilder.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr; - -import org.opensaml.common.impl.AbstractSAMLObjectBuilder; - -import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EAAFRequestedAttribute; -import at.gv.egiz.eaaf.modules.pvp2.impl.reqattr.EAAFRequestedAttributeImpl; - -public class EAAFRequestedAttributeBuilder extends AbstractSAMLObjectBuilder { - - @Override - public EAAFRequestedAttribute buildObject() { - return buildObject(EAAFRequestedAttribute.DEFAULT_ELEMENT_NAME); - } - - @Override - public EAAFRequestedAttribute buildObject(String namespaceURI, String localName, String namespacePrefix) { - return new EAAFRequestedAttributeImpl(namespaceURI, localName, - namespacePrefix); - } - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestedAttributeMarshaller.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestedAttributeMarshaller.java deleted file mode 100644 index d95adc8f..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestedAttributeMarshaller.java +++ /dev/null @@ -1,76 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr; - -import java.util.Map.Entry; - -import javax.xml.namespace.QName; - -import org.opensaml.Configuration; -import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; -import org.opensaml.xml.XMLObject; -import org.opensaml.xml.io.MarshallingException; -import org.opensaml.xml.util.XMLHelper; -import org.w3c.dom.Attr; -import org.w3c.dom.Element; - -import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EAAFRequestedAttribute; - -public class EAAFRequestedAttributeMarshaller extends AbstractSAMLObjectMarshaller { - protected final void marshallAttributes(final XMLObject samlElement, - final Element domElement) throws MarshallingException { - final EAAFRequestedAttribute requestedAttr = (EAAFRequestedAttribute) samlElement; - - if (requestedAttr.getName() != null) { - domElement.setAttributeNS(null, EAAFRequestedAttribute.NAME_ATTRIB_NAME, requestedAttr.getName()); - } - - if (requestedAttr.getNameFormat() != null) { - domElement.setAttributeNS(null, EAAFRequestedAttribute.NAME_FORMAT_ATTR, requestedAttr.getNameFormat()); - } - - if (requestedAttr.getFriendlyName() != null) { - domElement.setAttributeNS(null, EAAFRequestedAttribute.FRIENDLY_NAME_ATT, requestedAttr.getFriendlyName()); - } - - if (requestedAttr.getIsRequiredXSBoolean() != null) { - domElement.setAttributeNS(null, EAAFRequestedAttribute.IS_REQUIRED_ATTR, requestedAttr.getIsRequiredXSBoolean()); - } - - Attr attr; - for (Entry entry : requestedAttr.getUnknownAttributes() - .entrySet()) { - attr = XMLHelper.constructAttribute(domElement.getOwnerDocument(), - entry.getKey()); - attr.setValue(entry.getValue()); - domElement.setAttributeNodeNS(attr); - if (Configuration.isIDAttribute(entry.getKey()) - || requestedAttr.getUnknownAttributes().isIDAttribute( - entry.getKey())) { - attr.getOwnerElement().setIdAttributeNode(attr, true); - } - } - } -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestedAttributeUnmarshaller.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestedAttributeUnmarshaller.java deleted file mode 100644 index a4515707..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestedAttributeUnmarshaller.java +++ /dev/null @@ -1,75 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr; - -import javax.xml.namespace.QName; - -import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; -import org.opensaml.xml.XMLObject; -import org.opensaml.xml.io.UnmarshallingException; -import org.opensaml.xml.util.XMLHelper; -import org.w3c.dom.Attr; - -import at.gv.egiz.eaaf.modules.pvp2.PVPConstants; -import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EAAFRequestedAttribute; - -public class EAAFRequestedAttributeUnmarshaller extends AbstractSAMLObjectUnmarshaller { - protected final void processChildElement(final XMLObject parentSAMLObject, final XMLObject childSAMLObject) throws UnmarshallingException { - final EAAFRequestedAttribute requestedAttr = (EAAFRequestedAttribute) parentSAMLObject; - final QName childQName = childSAMLObject.getElementQName(); - - if ("AttributeValue".equals(childQName.getLocalPart()) - && childQName.getNamespaceURI().equals(PVPConstants.EIDAT10_SAML_NS)) { - requestedAttr.getAttributeValues().add(childSAMLObject); - - } else - super.processChildElement(parentSAMLObject, childSAMLObject); - - } - - protected final void processAttribute(final XMLObject samlObject, final Attr attribute) throws UnmarshallingException { - final EAAFRequestedAttribute requestedAttr = (EAAFRequestedAttribute) samlObject; - if (attribute.getLocalName().equals(EAAFRequestedAttribute.NAME_ATTRIB_NAME)) { - requestedAttr.setName(attribute.getValue()); - - } else if (attribute.getLocalName().equals(EAAFRequestedAttribute.NAME_FORMAT_ATTR)) { - requestedAttr.setNameFormat(attribute.getValue()); - - } else if (attribute.getLocalName().equals(EAAFRequestedAttribute.FRIENDLY_NAME_ATT)) { - requestedAttr.setFriendlyName(attribute.getValue()); - - } else if (attribute.getLocalName().equals(EAAFRequestedAttribute.IS_REQUIRED_ATTR)) { - requestedAttr.setIsRequired(attribute.getValue()); - - } else { - final QName attribQName = XMLHelper.getNodeQName(attribute); - if (attribute.isId()) { - requestedAttr.getUnknownAttributes().registerID(attribQName); - } - requestedAttr.getUnknownAttributes().put(attribQName, - attribute.getValue()); - } - } -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestedAttributesBuilder.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestedAttributesBuilder.java deleted file mode 100644 index 6e432b25..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestedAttributesBuilder.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr; - -import org.opensaml.common.impl.AbstractSAMLObjectBuilder; - -import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EAAFRequestedAttributes; -import at.gv.egiz.eaaf.modules.pvp2.impl.reqattr.EAAFRequestedAttributesImpl; - -public class EAAFRequestedAttributesBuilder extends AbstractSAMLObjectBuilder { - - @Override - public EAAFRequestedAttributes buildObject() { - return buildObject(EAAFRequestedAttributes.DEFAULT_ELEMENT_NAME); - } - - @Override - public EAAFRequestedAttributes buildObject(String namespaceURI, String localName, String namespacePrefix) { - return new EAAFRequestedAttributesImpl(namespaceURI, localName, - namespacePrefix); - } - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestedAttributesMarshaller.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestedAttributesMarshaller.java deleted file mode 100644 index 28d50422..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestedAttributesMarshaller.java +++ /dev/null @@ -1,31 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr; - -import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; - -public class EAAFRequestedAttributesMarshaller extends AbstractSAMLObjectMarshaller { - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestedAttributesUnmarshaller.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestedAttributesUnmarshaller.java deleted file mode 100644 index b2758326..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EAAFRequestedAttributesUnmarshaller.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr; - -import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; -import org.opensaml.xml.XMLObject; -import org.opensaml.xml.io.UnmarshallingException; - -import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EAAFRequestedAttribute; -import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EAAFRequestedAttributes; - -public class EAAFRequestedAttributesUnmarshaller extends AbstractSAMLObjectUnmarshaller { - protected final void processChildElement(final XMLObject parentObject, - final XMLObject childObject) throws UnmarshallingException { - final EAAFRequestedAttributes attrStatement = (EAAFRequestedAttributes) parentObject; - if (childObject instanceof EAAFRequestedAttribute) { - attrStatement.getAttributes().add((EAAFRequestedAttribute) childObject); - - } else - super.processChildElement(parentObject, childObject); - - } -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafExtensionImplementation.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafExtensionImplementation.java new file mode 100644 index 00000000..e61f5e6e --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafExtensionImplementation.java @@ -0,0 +1,32 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr; + +import org.opensaml.saml2.common.impl.ExtensionsImpl; + +public class EaafExtensionImplementation extends ExtensionsImpl { + + protected EaafExtensionImplementation(final String namespaceUri, final String elementLocalName, + final String namespacePrefix) { + super(namespaceUri, elementLocalName, namespacePrefix); + + } + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestExtensionBuilder.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestExtensionBuilder.java new file mode 100644 index 00000000..d8ea35a0 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestExtensionBuilder.java @@ -0,0 +1,41 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.common.Extensions; + +public class EaafRequestExtensionBuilder extends AbstractSAMLObjectBuilder { + + @Override + public Extensions buildObject() { + return buildObject(SAMLConstants.SAML20P_NS, Extensions.LOCAL_NAME, + SAMLConstants.SAML20P_PREFIX); + + } + + @Override + public Extensions buildObject(final String namespaceUri, final String localName, final String namespacePrefix) { + return new EaafExtensionImplementation(namespaceUri, localName, namespacePrefix); + + } + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestedAttributeBuilder.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestedAttributeBuilder.java new file mode 100644 index 00000000..4f91f267 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestedAttributeBuilder.java @@ -0,0 +1,40 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr; + +import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EaafRequestedAttribute; +import at.gv.egiz.eaaf.modules.pvp2.impl.reqattr.EaafRequestedAttributeImpl; +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; + +public class EaafRequestedAttributeBuilder + extends AbstractSAMLObjectBuilder { + + @Override + public EaafRequestedAttribute buildObject() { + return buildObject(EaafRequestedAttribute.DEFAULT_ELEMENT_NAME); + } + + @Override + public EaafRequestedAttribute buildObject(final String namespaceUri, final String localName, + final String namespacePrefix) { + return new EaafRequestedAttributeImpl(namespaceUri, localName, namespacePrefix); + } + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestedAttributeMarshaller.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestedAttributeMarshaller.java new file mode 100644 index 00000000..a370818e --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestedAttributeMarshaller.java @@ -0,0 +1,69 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr; + +import java.util.Map.Entry; +import javax.xml.namespace.QName; +import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EaafRequestedAttribute; +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; + +public class EaafRequestedAttributeMarshaller extends AbstractSAMLObjectMarshaller { + @Override + protected final void marshallAttributes(final XMLObject samlElement, final Element domElement) + throws MarshallingException { + final EaafRequestedAttribute requestedAttr = (EaafRequestedAttribute) samlElement; + + if (requestedAttr.getName() != null) { + domElement.setAttributeNS(null, EaafRequestedAttribute.NAME_ATTRIB_NAME, + requestedAttr.getName()); + } + + if (requestedAttr.getNameFormat() != null) { + domElement.setAttributeNS(null, EaafRequestedAttribute.NAME_FORMAT_ATTR, + requestedAttr.getNameFormat()); + } + + if (requestedAttr.getFriendlyName() != null) { + domElement.setAttributeNS(null, EaafRequestedAttribute.FRIENDLY_NAME_ATT, + requestedAttr.getFriendlyName()); + } + + if (requestedAttr.getIsRequiredXsBoolean() != null) { + domElement.setAttributeNS(null, EaafRequestedAttribute.IS_REQUIRED_ATTR, + requestedAttr.getIsRequiredXsBoolean()); + } + + Attr attr; + for (final Entry entry : requestedAttr.getUnknownAttributes().entrySet()) { + attr = XMLHelper.constructAttribute(domElement.getOwnerDocument(), entry.getKey()); + attr.setValue(entry.getValue()); + domElement.setAttributeNodeNS(attr); + if (org.opensaml.xml.Configuration.isIDAttribute(entry.getKey()) + || requestedAttr.getUnknownAttributes().isIDAttribute(entry.getKey())) { + attr.getOwnerElement().setIdAttributeNode(attr, true); + } + } + } +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestedAttributeUnmarshaller.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestedAttributeUnmarshaller.java new file mode 100644 index 00000000..25baed16 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestedAttributeUnmarshaller.java @@ -0,0 +1,74 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr; + +import javax.xml.namespace.QName; + +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Attr; + +import at.gv.egiz.eaaf.modules.pvp2.PvpConstants; +import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EaafRequestedAttribute; + +public class EaafRequestedAttributeUnmarshaller extends AbstractSAMLObjectUnmarshaller { + @Override + protected final void processChildElement(final XMLObject parentSamlObject, + final XMLObject childSamlObject) throws UnmarshallingException { + final EaafRequestedAttribute requestedAttr = (EaafRequestedAttribute) parentSamlObject; + final QName childQName = childSamlObject.getElementQName(); + + if ("AttributeValue".equals(childQName.getLocalPart()) + && childQName.getNamespaceURI().equals(PvpConstants.EIDAT10_SAML_NS)) { + requestedAttr.getAttributeValues().add(childSamlObject); + + } else { + super.processChildElement(parentSamlObject, childSamlObject); + } + + } + + @Override + protected final void processAttribute(final XMLObject samlObject, final Attr attribute) + throws UnmarshallingException { + final EaafRequestedAttribute requestedAttr = (EaafRequestedAttribute) samlObject; + if (attribute.getLocalName().equals(EaafRequestedAttribute.NAME_ATTRIB_NAME)) { + requestedAttr.setName(attribute.getValue()); + + } else if (attribute.getLocalName().equals(EaafRequestedAttribute.NAME_FORMAT_ATTR)) { + requestedAttr.setNameFormat(attribute.getValue()); + + } else if (attribute.getLocalName().equals(EaafRequestedAttribute.FRIENDLY_NAME_ATT)) { + requestedAttr.setFriendlyName(attribute.getValue()); + + } else if (attribute.getLocalName().equals(EaafRequestedAttribute.IS_REQUIRED_ATTR)) { + requestedAttr.setIsRequired(attribute.getValue()); + + } else { + final QName attribQName = XMLHelper.getNodeQName(attribute); + if (attribute.isId()) { + requestedAttr.getUnknownAttributes().registerID(attribQName); + } + requestedAttr.getUnknownAttributes().put(attribQName, attribute.getValue()); + } + } +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestedAttributesBuilder.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestedAttributesBuilder.java new file mode 100644 index 00000000..1f68747f --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestedAttributesBuilder.java @@ -0,0 +1,41 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr; + +import org.opensaml.common.impl.AbstractSAMLObjectBuilder; + +import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EaafRequestedAttributes; +import at.gv.egiz.eaaf.modules.pvp2.impl.reqattr.EaafRequestedAttributesImpl; + +public class EaafRequestedAttributesBuilder + extends AbstractSAMLObjectBuilder { + + @Override + public EaafRequestedAttributes buildObject() { + return buildObject(EaafRequestedAttributes.DEFAULT_ELEMENT_NAME); + } + + @Override + public EaafRequestedAttributes buildObject(final String namespaceUri, final String localName, + final String namespacePrefix) { + return new EaafRequestedAttributesImpl(namespaceUri, localName, namespacePrefix); + } + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestedAttributesMarshaller.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestedAttributesMarshaller.java new file mode 100644 index 00000000..2fff64b3 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestedAttributesMarshaller.java @@ -0,0 +1,26 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr; + +import org.opensaml.common.impl.AbstractSAMLObjectMarshaller; + +public class EaafRequestedAttributesMarshaller extends AbstractSAMLObjectMarshaller { + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestedAttributesUnmarshaller.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestedAttributesUnmarshaller.java new file mode 100644 index 00000000..b2cf7a82 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/builder/reqattr/EaafRequestedAttributesUnmarshaller.java @@ -0,0 +1,41 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr; + +import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EaafRequestedAttribute; +import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EaafRequestedAttributes; +import org.opensaml.common.impl.AbstractSAMLObjectUnmarshaller; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.UnmarshallingException; + +public class EaafRequestedAttributesUnmarshaller extends AbstractSAMLObjectUnmarshaller { + @Override + protected final void processChildElement(final XMLObject parentObject, + final XMLObject childObject) throws UnmarshallingException { + final EaafRequestedAttributes attrStatement = (EaafRequestedAttributes) parentObject; + if (childObject instanceof EaafRequestedAttribute) { + attrStatement.getAttributes().add((EaafRequestedAttribute) childObject); + + } else { + super.processChildElement(parentObject, childObject); + } + + } +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/message/InboundMessage.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/message/InboundMessage.java index 452fa553..107a856e 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/message/InboundMessage.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/message/InboundMessage.java @@ -1,123 +1,135 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.impl.message; import java.io.Serializable; - +import at.gv.egiz.eaaf.modules.pvp2.api.message.InboundMessageInterface; +import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPvpMetadataProvider; +import at.gv.egiz.eaaf.modules.pvp2.exception.NoMetadataInformationException; import org.opensaml.saml2.metadata.EntityDescriptor; import org.opensaml.saml2.metadata.provider.MetadataProviderException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Element; -import at.gv.egiz.eaaf.modules.pvp2.api.message.InboundMessageInterface; -import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPVPMetadataProvider; -import at.gv.egiz.eaaf.modules.pvp2.exception.NoMetadataInformationException; - -/** - * @author tlenz - * - */ -public class InboundMessage implements InboundMessageInterface, Serializable{ - private static final Logger log = LoggerFactory.getLogger(InboundMessage.class); - - private static final long serialVersionUID = 2395131650841669663L; - - private Element samlMessage = null; - private boolean verified = false; - private String entityID = null; - private String relayState = null; - - - public EntityDescriptor getEntityMetadata(IPVPMetadataProvider metadataProvider) throws NoMetadataInformationException { - try { - if (metadataProvider == null) - throw new NullPointerException("No PVP MetadataProvider found."); - - return metadataProvider.getEntityDescriptor(this.entityID); - - } catch (MetadataProviderException e) { - log.warn("No Metadata for EntitiyID " + entityID); - throw new NoMetadataInformationException(); - } - } - - /** - * @param entitiyID the entitiyID to set - */ - public void setEntityID(String entitiyID) { - this.entityID = entitiyID; - } - - public void setVerified(boolean verified) { - this.verified = verified; - } - - /** - * @param relayState the relayState to set - */ - public void setRelayState(String relayState) { - this.relayState = relayState; - } - - public void setSAMLMessage(Element msg) { - this.samlMessage = msg; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.messages.PVP21InboundMessage#getRelayState() - */ - @Override - public String getRelayState() { - return relayState; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.messages.PVP21InboundMessage#getEntityID() - */ - @Override - public String getEntityID() { - return entityID; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.messages.PVP21InboundMessage#isVerified() - */ - @Override - public boolean isVerified() { - return verified; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.messages.PVP21InboundMessage#getInboundMessage() - */ - @Override - public Element getInboundMessage() { - return samlMessage; - } +public class InboundMessage implements InboundMessageInterface, Serializable { + private static final Logger log = LoggerFactory.getLogger(InboundMessage.class); + + private static final long serialVersionUID = 2395131650841669663L; + + private Element samlMessage = null; + private boolean verified = false; + private String entityID = null; + private String relayState = null; + + /** + * Get SAML2 metadata for Entity that sends this request. + * + * @param metadataProvider Metadataprovider + * @return EntityDescriptor from metadata + * @throws NoMetadataInformationException In case of an error + */ + public EntityDescriptor getEntityMetadata(final IPvpMetadataProvider metadataProvider) + throws NoMetadataInformationException { + try { + if (metadataProvider == null) { + throw new NullPointerException("No PVP MetadataProvider found."); + } + + return metadataProvider.getEntityDescriptor(this.entityID); + + } catch (final MetadataProviderException e) { + log.warn("No Metadata for EntitiyID " + entityID); + throw new NoMetadataInformationException(); + } + } + + /** + * Set EntitId of requester. + * + * @param entitiyID the entitiyID to set + */ + public void setEntityID(final String entitiyID) { + this.entityID = entitiyID; + } + + public void setVerified(final boolean verified) { + this.verified = verified; + } + + /** + * Set relayState from requester. + * + * @param relayState the relayState to set + */ + public void setRelayState(final String relayState) { + this.relayState = relayState; + } + + /** + * Set full SAML2 message. + * + * @param msg message + */ + public void setSamlMessage(final Element msg) { + this.samlMessage = msg; + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.protocols.pvp2x.messages.PVP21InboundMessage#getRelayState() + */ + @Override + public String getRelayState() { + return relayState; + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.protocols.pvp2x.messages.PVP21InboundMessage#getEntityID() + */ + @Override + public String getEntityID() { + return entityID; + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.protocols.pvp2x.messages.PVP21InboundMessage#isVerified() + */ + @Override + public boolean isVerified() { + return verified; + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.protocols.pvp2x.messages.PVP21InboundMessage#getInboundMessage() + */ + @Override + public Element getInboundMessage() { + return samlMessage; + } } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/message/PVPSProfileRequest.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/message/PVPSProfileRequest.java deleted file mode 100644 index 9c9c913d..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/message/PVPSProfileRequest.java +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.message; - - -import org.opensaml.Configuration; -import org.opensaml.xml.io.Unmarshaller; -import org.opensaml.xml.io.UnmarshallerFactory; -import org.opensaml.xml.io.UnmarshallingException; -import org.opensaml.xml.signature.SignableXMLObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class PVPSProfileRequest extends InboundMessage{ - private static final Logger log = LoggerFactory.getLogger(PVPSProfileRequest.class); - - private static final long serialVersionUID = 8613921176727607896L; - - private String binding = null; - - public PVPSProfileRequest(SignableXMLObject inboundMessage, String binding) { - setSAMLMessage(inboundMessage.getDOM()); - this.binding = binding; - - } - - public String getRequestBinding() { - return binding; - } - - public SignableXMLObject getSamlRequest() { - UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory(); - Unmarshaller unmashaller = unmarshallerFactory.getUnmarshaller(getInboundMessage()); - - try { - return (SignableXMLObject) unmashaller.unmarshall(getInboundMessage()); - - } catch (UnmarshallingException e) { - log.warn("AuthnRequest Unmarshaller error", e); - return null; - } - - } - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/message/PVPSProfileResponse.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/message/PVPSProfileResponse.java deleted file mode 100644 index 107aa731..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/message/PVPSProfileResponse.java +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.message; - -import org.opensaml.Configuration; -import org.opensaml.saml2.core.StatusResponseType; -import org.opensaml.xml.io.Unmarshaller; -import org.opensaml.xml.io.UnmarshallerFactory; -import org.opensaml.xml.io.UnmarshallingException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class PVPSProfileResponse extends InboundMessage { - - private static final Logger log = LoggerFactory.getLogger(PVPSProfileResponse.class); - - private static final long serialVersionUID = -1133012928130138501L; - - public PVPSProfileResponse(StatusResponseType response) { - setSAMLMessage(response.getDOM()); - } - - public StatusResponseType getResponse() { - UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory(); - Unmarshaller unmashaller = unmarshallerFactory.getUnmarshaller(getInboundMessage()); - - try { - return (StatusResponseType) unmashaller.unmarshall(getInboundMessage()); - - } catch (UnmarshallingException e) { - log.warn("AuthnResponse Unmarshaller error", e); - return null; - } - - } - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/message/PvpSProfileRequest.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/message/PvpSProfileRequest.java new file mode 100644 index 00000000..dce2dd04 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/message/PvpSProfileRequest.java @@ -0,0 +1,73 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.impl.message; + + +import org.opensaml.xml.io.Unmarshaller; +import org.opensaml.xml.io.UnmarshallerFactory; +import org.opensaml.xml.io.UnmarshallingException; +import org.opensaml.xml.signature.SignableXMLObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class PvpSProfileRequest extends InboundMessage { + private static final Logger log = LoggerFactory.getLogger(PvpSProfileRequest.class); + + private static final long serialVersionUID = 8613921176727607896L; + + private String binding = null; + + /** + * PVP2 S-Profil request DAO. + * + * @param inboundMessage SAML2 request object + * @param binding Used SAML2 binding + */ + public PvpSProfileRequest(final SignableXMLObject inboundMessage, final String binding) { + setSamlMessage(inboundMessage.getDOM()); + this.binding = binding; + + } + + public String getRequestBinding() { + return binding; + } + + /** + * Get SAML2 request object. + * + * @return + */ + public SignableXMLObject getSamlRequest() { + final UnmarshallerFactory unmarshallerFactory = + org.opensaml.xml.Configuration.getUnmarshallerFactory(); + final Unmarshaller unmashaller = unmarshallerFactory.getUnmarshaller(getInboundMessage()); + + try { + return (SignableXMLObject) unmashaller.unmarshall(getInboundMessage()); + + } catch (final UnmarshallingException e) { + log.warn("AuthnRequest Unmarshaller error", e); + return null; + } + + } + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/message/PvpSProfileResponse.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/message/PvpSProfileResponse.java new file mode 100644 index 00000000..8d1cbe8c --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/message/PvpSProfileResponse.java @@ -0,0 +1,59 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.impl.message; + +import org.opensaml.saml2.core.StatusResponseType; +import org.opensaml.xml.io.Unmarshaller; +import org.opensaml.xml.io.UnmarshallerFactory; +import org.opensaml.xml.io.UnmarshallingException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class PvpSProfileResponse extends InboundMessage { + + private static final Logger log = LoggerFactory.getLogger(PvpSProfileResponse.class); + + private static final long serialVersionUID = -1133012928130138501L; + + public PvpSProfileResponse(final StatusResponseType response) { + setSamlMessage(response.getDOM()); + } + + /** + * Get SAML2 Response object. + * + * @return + */ + public StatusResponseType getResponse() { + final UnmarshallerFactory unmarshallerFactory = + org.opensaml.xml.Configuration.getUnmarshallerFactory(); + final Unmarshaller unmashaller = unmarshallerFactory.getUnmarshaller(getInboundMessage()); + + try { + return (StatusResponseType) unmashaller.unmarshall(getInboundMessage()); + + } catch (final UnmarshallingException e) { + log.warn("AuthnResponse Unmarshaller error", e); + return null; + } + + } + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/metadata/AbstractChainingMetadataProvider.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/metadata/AbstractChainingMetadataProvider.java index 08ef26ab..ec81353a 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/metadata/AbstractChainingMetadataProvider.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/metadata/AbstractChainingMetadataProvider.java @@ -1,29 +1,22 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.impl.metadata; import java.io.IOException; @@ -35,9 +28,12 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Timer; - import javax.xml.namespace.QName; - +import at.gv.egiz.components.spring.api.IDestroyableObject; +import at.gv.egiz.eaaf.core.api.IGarbageCollectorProcessing; +import at.gv.egiz.eaaf.core.exceptions.EaafConfigurationException; +import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPvpMetadataProvider; +import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IRefreshableMetadataProvider; import org.apache.commons.lang3.StringUtils; import org.opensaml.saml2.metadata.EntitiesDescriptor; import org.opensaml.saml2.metadata.EntityDescriptor; @@ -52,419 +48,474 @@ import org.opensaml.xml.XMLObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import at.gv.egiz.components.spring.api.IDestroyableObject; -import at.gv.egiz.eaaf.core.api.IGarbageCollectorProcessing; -import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; -import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPVPMetadataProvider; -import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IRefreshableMetadataProvider; - public abstract class AbstractChainingMetadataProvider extends SimpleMetadataProvider - implements ObservableMetadataProvider, IGarbageCollectorProcessing, - IRefreshableMetadataProvider, IDestroyableObject, IPVPMetadataProvider { - - private static final Logger log = LoggerFactory.getLogger(AbstractChainingMetadataProvider.class); - - private MetadataProvider internalProvider = null; - private static Object mutex = new Object(); - private Timer timer = null; - - - public AbstractChainingMetadataProvider() { - internalProvider = new ChainingMetadataProvider(); - - } - - public final Timer getTimer() { - return this.timer; - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.config.auth.IGarbageCollectorProcessing#runGarbageCollector() - */ - @Override - public void runGarbageCollector() { - synchronized (mutex) { - /**add new Metadataprovider or remove Metadataprovider which are not in use any more.**/ - try { - log.trace("Check consistence of PVP2X metadata"); - addAndRemoveMetadataProvider(); - - } catch (EAAFConfigurationException e) { - log.error("Access to MOA-ID configuration FAILED.", e); - - } - } - - } - - public void fullyDestroy() { - internalDestroy(); - - } - - @Override - public synchronized boolean refreshMetadataProvider(String entityID) { - try { - //check if metadata provider is already loaded - try { - if (internalProvider.getEntityDescriptor(entityID) != null) - return true; - - } catch (MetadataProviderException e) {} - - - //reload metadata provider - String metadataURL = getMetadataURL(entityID); - if (StringUtils.isNotEmpty(metadataURL)) { - Map actuallyLoadedProviders = getAllActuallyLoadedProviders(); - - // check if MetadataProvider is actually loaded - if (actuallyLoadedProviders.containsKey(metadataURL)) { - actuallyLoadedProviders.get(metadataURL).refresh(); - log.info("SAML2 metadata for service provider: " - + entityID + " is refreshed."); - return true; - - } else { - //load new Metadata Provider - if (timer == null) - timer = new Timer(true); - - ChainingMetadataProvider chainProvider = (ChainingMetadataProvider) internalProvider; - chainProvider.addMetadataProvider(createNewMetadataProvider(entityID)); - - emitChangeEvent(); - log.info("SAML2 metadata for service provider: " - + entityID + " is added."); - return true; - - } - - } else - log.debug("Can not refresh SAML2 metadata: NO SAML2 metadata URL for SP with Id: " + entityID); - - } catch (MetadataProviderException e) { - log.warn("Refresh SAML2 metadata for service provider: " - + entityID + " FAILED.", e); - - } catch (IOException e) { - log.warn("Refresh SAML2 metadata for service provider: " - + entityID + " FAILED.", e); - - } catch (EAAFConfigurationException e) { - log.warn("Refresh SAML2 metadata for service provider: " - + entityID + " FAILED.", e); - - } catch (CertificateException e) { - log.warn("Refresh SAML2 metadata for service provider: " - + entityID + " FAILED.", e); - - } - - return false; - - } - - public void internalDestroy() { - if (internalProvider != null && internalProvider instanceof ChainingMetadataProvider) { - log.info("Destrorying PVP-Authentication MetaDataProvider."); - ChainingMetadataProvider chainProvider = (ChainingMetadataProvider) internalProvider; - - List providers = chainProvider.getProviders(); - for (MetadataProvider provider : providers) { - if (provider instanceof HTTPMetadataProvider) { - HTTPMetadataProvider httpprovider = (HTTPMetadataProvider) provider; - log.debug("Destroy HTTPMetadataProvider +" + httpprovider.getMetadataURI()); - httpprovider.destroy(); - - } else { - log.warn("MetadataProvider can not be destroyed."); - } - } - - internalProvider = new ChainingMetadataProvider(); - - if (timer != null) - timer.cancel(); - - } else { - log.warn("ReInitalize MOAMetaDataProvider is not possible! MOA-ID Instance has to be restarted manualy"); - } - } - - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.metadata.IEAAFMetadataProvider#requireValidMetadata() - */ - @Override - public boolean requireValidMetadata() { - return internalProvider.requireValidMetadata(); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.metadata.IEAAFMetadataProvider#setRequireValidMetadata(boolean) - */ - @Override - public void setRequireValidMetadata(boolean requireValidMetadata) { - internalProvider.setRequireValidMetadata(requireValidMetadata); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.metadata.IEAAFMetadataProvider#getMetadataFilter() - */ - @Override - public MetadataFilter getMetadataFilter() { - return internalProvider.getMetadataFilter(); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.metadata.IEAAFMetadataProvider#setMetadataFilter(org.opensaml.saml2.metadata.provider.MetadataFilter) - */ - @Override - public void setMetadataFilter(MetadataFilter newFilter) - throws MetadataProviderException { - internalProvider.setMetadataFilter(newFilter); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.metadata.IEAAFMetadataProvider#getMetadata() - */ - @Override - public XMLObject getMetadata() throws MetadataProviderException { - return internalProvider.getMetadata(); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.metadata.IEAAFMetadataProvider#getEntitiesDescriptor(java.lang.String) - */ - @Override - public EntitiesDescriptor getEntitiesDescriptor(String entitiesID) - throws MetadataProviderException { - EntitiesDescriptor entitiesDesc = null; - try { - entitiesDesc = internalProvider.getEntitiesDescriptor(entitiesID); - - if (entitiesDesc == null) { - log.debug("Can not find PVP metadata for entityID: " + entitiesID - + " Start refreshing process ..."); - if (refreshMetadataProvider(entitiesID)) - return internalProvider.getEntitiesDescriptor(entitiesID); - - } - - } catch (MetadataProviderException e) { - log.debug("Can not find PVP metadata for entityID: " + entitiesID - + " Start refreshing process ..."); - if (refreshMetadataProvider(entitiesID)) - return internalProvider.getEntitiesDescriptor(entitiesID); - - } - - return entitiesDesc; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.metadata.IEAAFMetadataProvider#getEntityDescriptor(java.lang.String) - */ - @Override - public EntityDescriptor getEntityDescriptor(String entityID) - throws MetadataProviderException { - EntityDescriptor entityDesc = null; - try { - entityDesc = internalProvider.getEntityDescriptor(entityID); - if (entityDesc == null) { - log.debug("Can not find PVP metadata for entityID: " + entityID - + " Start refreshing process ..."); - if (refreshMetadataProvider(entityID)) - return internalProvider.getEntityDescriptor(entityID); - - } - - } catch (MetadataProviderException e) { - log.debug("Can not find PVP metadata for entityID: " + entityID - + " Start refreshing process ..."); - if (refreshMetadataProvider(entityID)) - return internalProvider.getEntityDescriptor(entityID); - - } - -// if (entityDesc != null) -// lastAccess.put(entityID, new Date()); - - return entityDesc; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.metadata.IEAAFMetadataProvider#getRole(java.lang.String, javax.xml.namespace.QName) - */ - @Override - public List getRole(String entityID, QName roleName) - throws MetadataProviderException { - List result = internalProvider.getRole(entityID, roleName); - -// if (result != null) -// lastAccess.put(entityID, new Date()); - - return result; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.metadata.IEAAFMetadataProvider#getRole(java.lang.String, javax.xml.namespace.QName, java.lang.String) - */ - @Override - public RoleDescriptor getRole(String entityID, QName roleName, - String supportedProtocol) throws MetadataProviderException { - RoleDescriptor result = internalProvider.getRole(entityID, roleName, supportedProtocol); - -// if (result != null) -// lastAccess.put(entityID, new Date()); - - return result; - } - - /* (non-Javadoc) - * @see org.opensaml.saml2.metadata.provider.ObservableMetadataProvider#getObservers() - */ - @Override - public List getObservers() { - return ((ChainingMetadataProvider) internalProvider).getObservers(); - } - - - /** - * Get the URL to metadata for a specific entityID - * - * @param entityId - * @return - * @throws EAAFConfigurationException - */ - protected abstract String getMetadataURL(String entityId) throws EAAFConfigurationException; - - /** - * Creates a new implementation specific SAML2 metadata provider - * - * @param entityId - * @return - * @throws EAAFConfigurationException - * @throws IOException - * @throws CertificateException - * @throws ConfigurationException - */ - protected abstract MetadataProvider createNewMetadataProvider(String entityId) throws EAAFConfigurationException, IOException, CertificateException; - - /** - * Get a List of metadata URLs for all SAML2 SPs from configuration - * - * @throws EAAFConfigurationException - */ - protected abstract List getAllMetadataURLsFromConfiguration() throws EAAFConfigurationException; - - - protected void emitChangeEvent() { - if ((getObservers() == null) || (getObservers().size() == 0)) { - return; - } - - List tempObserverList = new ArrayList(getObservers()); - for (ObservableMetadataProvider.Observer observer : tempObserverList) - if (observer != null) - observer.onEvent(this); - } - - private Map getAllActuallyLoadedProviders() { - Map loadedproviders = new HashMap(); - ChainingMetadataProvider chainProvider = (ChainingMetadataProvider) internalProvider; - - //make a Map of all actually loaded HTTPMetadataProvider - List providers = chainProvider.getProviders(); - for (MetadataProvider provider : providers) { - if (provider instanceof HTTPMetadataProvider) { - HTTPMetadataProvider httpprovider = (HTTPMetadataProvider) provider; - loadedproviders.put(httpprovider.getMetadataURI(), httpprovider); - - } - } - - return loadedproviders; - } - - private void addAndRemoveMetadataProvider() throws EAAFConfigurationException { - if (internalProvider != null && internalProvider instanceof ChainingMetadataProvider) { - log.info("Reload MOAMetaDataProvider."); - - /*OpenSAML ChainingMetadataProvider can not remove a MetadataProvider (UnsupportedOperationException) - *The ChainingMetadataProvider use internal a unmodifiableList to hold all registrated MetadataProviders.*/ - Map providersinuse = new HashMap(); - ChainingMetadataProvider chainProvider = (ChainingMetadataProvider) internalProvider; - - //get all actually loaded metadata providers - Map loadedproviders = getAllActuallyLoadedProviders(); - - /* TODO: maybe add metadata provider destroy after timeout. - * But could be a problem if one Metadataprovider load an EntitiesDescriptor - * with more the multiple EntityDescriptors. If one of this EntityDesciptors - * are expired the full EntitiesDescriptor is removed. - * - * Timeout requires a better solution in this case! - */ - - //load all SAML2 SPs form configuration and - //compare actually loaded Providers with configured SAML2 SPs - List allMetadataURLs = getAllMetadataURLsFromConfiguration(); - - if (allMetadataURLs != null) { - Iterator metadataURLInterator = allMetadataURLs.iterator(); - while (metadataURLInterator.hasNext()) { - String metadataurl = metadataURLInterator.next(); - try { - if (StringUtils.isNotEmpty(metadataurl)) { - if (loadedproviders.containsKey(metadataurl)) { - // SAML2 SP is actually loaded, to nothing - providersinuse.put(metadataurl, loadedproviders.get(metadataurl)); - loadedproviders.remove(metadataurl); - - } - } - } catch (Throwable e) { - log.error( - "Failed to add Metadata (unhandled reason: " + e.getMessage(), e); - - } - } - } - - //remove all actually loaded MetadataProviders with are not in ConfigurationDB any more - Collection notusedproviders = loadedproviders.values(); - for (HTTPMetadataProvider provider : notusedproviders) { - String metadataurl = provider.getMetadataURI(); - try { - provider.destroy(); - - /*OpenSAML ChainingMetadataProvider can not remove a MetadataProvider (UnsupportedOperationException) - *The ChainingMetadataProvider use internal a unmodifiableList to hold all registrated MetadataProviders.*/ - //chainProvider.removeMetadataProvider(provider); - log.info("Remove not used MetadataProvider with MetadataURL " + metadataurl); - - } catch (Throwable e) { - log.error("HTTPMetadataProvider with URL " + metadataurl - + " can not be removed from the list of actually loaded Providers.", e); - - } - - } - - try { - chainProvider.setProviders(new ArrayList(providersinuse.values())); - emitChangeEvent(); - - } catch (MetadataProviderException e) { - log.warn("ReInitalize AbstractMetaDataProvider is not possible! Service has to be restarted manualy", e); - - } - - } else - log.warn("ReInitalize AbstractMetaDataProvider is not possible! Service has to be restarted manualy"); - - } + implements ObservableMetadataProvider, IGarbageCollectorProcessing, + IRefreshableMetadataProvider, IDestroyableObject, IPvpMetadataProvider { + + private static final Logger log = LoggerFactory.getLogger(AbstractChainingMetadataProvider.class); + + private MetadataProvider internalProvider = null; + private static Object mutex = new Object(); + private Timer timer = null; + + + public AbstractChainingMetadataProvider() { + internalProvider = new ChainingMetadataProvider(); + + } + + public final Timer getTimer() { + return this.timer; + + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.config.auth.IGarbageCollectorProcessing#runGarbageCollector() + */ + @Override + public void runGarbageCollector() { + synchronized (mutex) { + /* add new Metadataprovider or remove Metadataprovider which are not in use any more. */ + try { + log.trace("Check consistence of PVP2X metadata"); + addAndRemoveMetadataProvider(); + + } catch (final EaafConfigurationException e) { + log.error("Access to MOA-ID configuration FAILED.", e); + + } + } + + } + + @Override + public void fullyDestroy() { + internalDestroy(); + + } + + @Override + public synchronized boolean refreshMetadataProvider(final String entityID) { + try { + // check if metadata provider is already loaded + try { + if (internalProvider.getEntityDescriptor(entityID) != null) { + return true; + } + + } catch (final MetadataProviderException e) { + log.debug("Metadata for EntityId: {} is not valid. Starting refresh ... ", entityID); + + } + + + // reload metadata provider + final String metadataUrl = getMetadataUrl(entityID); + if (StringUtils.isNotEmpty(metadataUrl)) { + final Map actuallyLoadedProviders = + getAllActuallyLoadedProviders(); + + // check if MetadataProvider is actually loaded + if (actuallyLoadedProviders.containsKey(metadataUrl)) { + actuallyLoadedProviders.get(metadataUrl).refresh(); + log.info("SAML2 metadata for service provider: " + entityID + " is refreshed."); + return true; + + } else { + // load new Metadata Provider + if (timer == null) { + timer = new Timer(true); + } + + final ChainingMetadataProvider chainProvider = + (ChainingMetadataProvider) internalProvider; + chainProvider.addMetadataProvider(createNewMetadataProvider(entityID)); + + emitChangeEvent(); + log.info("SAML2 metadata for service provider: " + entityID + " is added."); + return true; + + } + + } else { + log.debug( + "Can not refresh SAML2 metadata: NO SAML2 metadata URL for SP with Id: " + entityID); + } + + } catch (final MetadataProviderException e) { + log.warn("Refresh SAML2 metadata for service provider: " + entityID + " FAILED.", e); + + } catch (final IOException e) { + log.warn("Refresh SAML2 metadata for service provider: " + entityID + " FAILED.", e); + + } catch (final EaafConfigurationException e) { + log.warn("Refresh SAML2 metadata for service provider: " + entityID + " FAILED.", e); + + } catch (final CertificateException e) { + log.warn("Refresh SAML2 metadata for service provider: " + entityID + " FAILED.", e); + + } + + return false; + + } + + /** + * Close metadata provider and remove all loaded metadata. + * + */ + public void internalDestroy() { + if (internalProvider != null && internalProvider instanceof ChainingMetadataProvider) { + log.info("Destrorying PVP-Authentication MetaDataProvider."); + final ChainingMetadataProvider chainProvider = (ChainingMetadataProvider) internalProvider; + + final List providers = chainProvider.getProviders(); + for (final MetadataProvider provider : providers) { + if (provider instanceof HTTPMetadataProvider) { + final HTTPMetadataProvider httpprovider = (HTTPMetadataProvider) provider; + log.debug("Destroy HTTPMetadataProvider +" + httpprovider.getMetadataURI()); + httpprovider.destroy(); + + } else { + log.warn("MetadataProvider can not be destroyed."); + } + } + + internalProvider = new ChainingMetadataProvider(); + + if (timer != null) { + timer.cancel(); + } + + } else { + log.warn( + "ReInitalize MOAMetaDataProvider is not possible! MOA-ID Instance has to be restarted manualy"); + } + } + + + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.protocols.pvp2x.metadata.IEAAFMetadataProvider#requireValidMetadata() + */ + @Override + public boolean requireValidMetadata() { + return internalProvider.requireValidMetadata(); + } + + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.protocols.pvp2x.metadata.IEAAFMetadataProvider#setRequireValidMetadata + * (boolean) + */ + @Override + public void setRequireValidMetadata(final boolean requireValidMetadata) { + internalProvider.setRequireValidMetadata(requireValidMetadata); + } + + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.protocols.pvp2x.metadata.IEAAFMetadataProvider#getMetadataFilter() + */ + @Override + public MetadataFilter getMetadataFilter() { + return internalProvider.getMetadataFilter(); + } + + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.protocols.pvp2x.metadata.IEAAFMetadataProvider#setMetadataFilter(org. + * opensaml.saml2.metadata.provider.MetadataFilter) + */ + @Override + public void setMetadataFilter(final MetadataFilter newFilter) throws MetadataProviderException { + internalProvider.setMetadataFilter(newFilter); + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.protocols.pvp2x.metadata.IEAAFMetadataProvider#getMetadata() + */ + @Override + public XMLObject getMetadata() throws MetadataProviderException { + return internalProvider.getMetadata(); + } + + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.protocols.pvp2x.metadata.IEAAFMetadataProvider#getEntitiesDescriptor( + * java.lang.String) + */ + @Override + public EntitiesDescriptor getEntitiesDescriptor(final String entitiesID) + throws MetadataProviderException { + EntitiesDescriptor entitiesDesc = null; + try { + entitiesDesc = internalProvider.getEntitiesDescriptor(entitiesID); + + if (entitiesDesc == null) { + log.debug("Can not find PVP metadata for entityID: " + entitiesID + + " Start refreshing process ..."); + if (refreshMetadataProvider(entitiesID)) { + return internalProvider.getEntitiesDescriptor(entitiesID); + } + + } + + } catch (final MetadataProviderException e) { + log.debug("Can not find PVP metadata for entityID: " + entitiesID + + " Start refreshing process ..."); + if (refreshMetadataProvider(entitiesID)) { + return internalProvider.getEntitiesDescriptor(entitiesID); + } + + } + + return entitiesDesc; + } + + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.protocols.pvp2x.metadata.IEAAFMetadataProvider#getEntityDescriptor( + * java.lang.String) + */ + @Override + public EntityDescriptor getEntityDescriptor(final String entityID) + throws MetadataProviderException { + EntityDescriptor entityDesc = null; + try { + entityDesc = internalProvider.getEntityDescriptor(entityID); + if (entityDesc == null) { + log.debug("Can not find PVP metadata for entityID: " + entityID + + " Start refreshing process ..."); + if (refreshMetadataProvider(entityID)) { + return internalProvider.getEntityDescriptor(entityID); + } + + } + + } catch (final MetadataProviderException e) { + log.debug( + "Can not find PVP metadata for entityID: " + entityID + " Start refreshing process ..."); + if (refreshMetadataProvider(entityID)) { + return internalProvider.getEntityDescriptor(entityID); + } + + } + + // if (entityDesc != null) + // lastAccess.put(entityID, new Date()); + + return entityDesc; + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.protocols.pvp2x.metadata.IEAAFMetadataProvider#getRole(java.lang. + * String, javax.xml.namespace.QName) + */ + @Override + public List getRole(final String entityID, final QName roleName) + throws MetadataProviderException { + final List result = internalProvider.getRole(entityID, roleName); + + // if (result != null) + // lastAccess.put(entityID, new Date()); + + return result; + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.protocols.pvp2x.metadata.IEAAFMetadataProvider#getRole(java.lang. + * String, javax.xml.namespace.QName, java.lang.String) + */ + @Override + public RoleDescriptor getRole(final String entityID, final QName roleName, + final String supportedProtocol) throws MetadataProviderException { + final RoleDescriptor result = internalProvider.getRole(entityID, roleName, supportedProtocol); + + // if (result != null) + // lastAccess.put(entityID, new Date()); + + return result; + } + + /* + * (non-Javadoc) + * + * @see org.opensaml.saml2.metadata.provider.ObservableMetadataProvider#getObservers() + */ + @Override + public List getObservers() { + return ((ChainingMetadataProvider) internalProvider).getObservers(); + } + + + /** + * Get the URL to metadata for a specific entityID. + * + * @param entityId EntityId + * @return URL to metadata + * @throws EaafConfigurationException In case of an error + */ + protected abstract String getMetadataUrl(String entityId) throws EaafConfigurationException; + + /** + * Creates a new implementation specific SAML2 metadata provider. + * + * @param entityId EntityId + * @return MetadataProvider + * @throws EaafConfigurationException In case of an error + * @throws IOException In case of an error + * @throws CertificateException In case of an error + * @throws ConfigurationException In case of an error + */ + protected abstract MetadataProvider createNewMetadataProvider(String entityId) + throws EaafConfigurationException, IOException, CertificateException; + + /** + * Get a List of metadata URLs for all SAML2 SPs from configuration. + * + * @throws EaafConfigurationException In case of an error + */ + protected abstract List getAllMetadataUrlsFromConfiguration() + throws EaafConfigurationException; + + + protected void emitChangeEvent() { + if ((getObservers() == null) || (getObservers().size() == 0)) { + return; + } + + final List tempObserverList = new ArrayList<>(getObservers()); + for (final ObservableMetadataProvider.Observer observer : tempObserverList) { + if (observer != null) { + observer.onEvent(this); + } + } + } + + private Map getAllActuallyLoadedProviders() { + final Map loadedproviders = + new HashMap<>(); + final ChainingMetadataProvider chainProvider = (ChainingMetadataProvider) internalProvider; + + // make a Map of all actually loaded HTTPMetadataProvider + final List providers = chainProvider.getProviders(); + for (final MetadataProvider provider : providers) { + if (provider instanceof HTTPMetadataProvider) { + final HTTPMetadataProvider httpprovider = (HTTPMetadataProvider) provider; + loadedproviders.put(httpprovider.getMetadataURI(), httpprovider); + + } + } + + return loadedproviders; + } + + private void addAndRemoveMetadataProvider() throws EaafConfigurationException { + if (internalProvider != null && internalProvider instanceof ChainingMetadataProvider) { + log.info("Reload MOAMetaDataProvider."); + + /* + * OpenSAML ChainingMetadataProvider can not remove a MetadataProvider + * (UnsupportedOperationException) The ChainingMetadataProvider use internal a + * unmodifiableList to hold all registrated MetadataProviders. + */ + final Map providersinuse = new HashMap<>(); + final ChainingMetadataProvider chainProvider = (ChainingMetadataProvider) internalProvider; + + // get all actually loaded metadata providers + final Map loadedproviders = getAllActuallyLoadedProviders(); + + /* + * TODO: maybe add metadata provider destroy after timeout. But could be a problem if one + * Metadataprovider load an EntitiesDescriptor with more the multiple EntityDescriptors. If + * one of this EntityDesciptors are expired the full EntitiesDescriptor is removed. + * + * Timeout requires a better solution in this case! + */ + + // load all SAML2 SPs form configuration and + // compare actually loaded Providers with configured SAML2 SPs + final List allMetadataUrls = getAllMetadataUrlsFromConfiguration(); + + if (allMetadataUrls != null) { + final Iterator metadataUrlInterator = allMetadataUrls.iterator(); + while (metadataUrlInterator.hasNext()) { + final String metadataurl = metadataUrlInterator.next(); + try { + if (StringUtils.isNotEmpty(metadataurl)) { + if (loadedproviders.containsKey(metadataurl)) { + // SAML2 SP is actually loaded, to nothing + providersinuse.put(metadataurl, loadedproviders.get(metadataurl)); + loadedproviders.remove(metadataurl); + + } + } + } catch (final Throwable e) { + log.error("Failed to add Metadata (unhandled reason: " + e.getMessage(), e); + + } + } + } + + // remove all actually loaded MetadataProviders with are not in ConfigurationDB any more + final Collection notusedproviders = loadedproviders.values(); + for (final HTTPMetadataProvider provider : notusedproviders) { + final String metadataurl = provider.getMetadataURI(); + try { + provider.destroy(); + + /* + * OpenSAML ChainingMetadataProvider can not remove a MetadataProvider + * (UnsupportedOperationException) The ChainingMetadataProvider use internal a + * unmodifiableList to hold all registrated MetadataProviders. + */ + // chainProvider.removeMetadataProvider(provider); + log.info("Remove not used MetadataProvider with MetadataURL " + metadataurl); + + } catch (final Throwable e) { + log.error("HTTPMetadataProvider with URL " + metadataurl + + " can not be removed from the list of actually loaded Providers.", e); + + } + + } + + try { + chainProvider.setProviders(new ArrayList<>(providersinuse.values())); + emitChangeEvent(); + + } catch (final MetadataProviderException e) { + log.warn( + "ReInitalize AbstractMetaDataProvider is not possible! Service has to be restarted manualy", + e); + + } + + } else { + log.warn( + "ReInitalize AbstractMetaDataProvider is not possible! Service has to be restarted manualy"); + } + + } } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/metadata/MetadataFilterChain.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/metadata/MetadataFilterChain.java index 06065a82..04c1dcb8 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/metadata/MetadataFilterChain.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/metadata/MetadataFilterChain.java @@ -1,34 +1,26 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.impl.metadata; import java.util.ArrayList; import java.util.List; - import org.opensaml.saml2.metadata.provider.FilterException; import org.opensaml.saml2.metadata.provider.MetadataFilter; import org.opensaml.xml.XMLObject; @@ -37,44 +29,48 @@ import org.slf4j.LoggerFactory; /** + * Metadata filter-chain implementation. + * * @author tlenz * */ public class MetadataFilterChain implements MetadataFilter { - private static final Logger log = LoggerFactory.getLogger(MetadataFilterChain.class); - - - private List filters = new ArrayList(); - - /** - * Return all actually used Metadata filters - * - * @return List of Metadata filters - */ - public List getFilters() { - return filters; - } - - /** - * Add a new Metadata filter to filterchain - * - * @param filter - */ - public void addFilter(MetadataFilter filter) { - filters.add(filter); - } - - - /* (non-Javadoc) - * @see org.opensaml.saml2.metadata.provider.MetadataFilter#doFilter(org.opensaml.xml.XMLObject) - */ - @Override - public void doFilter(XMLObject arg0) throws FilterException { - for (MetadataFilter filter : filters) { - log.trace("Use EAAFMetadataFilter " + filter.getClass().getName()); - filter.doFilter(arg0); - } + private static final Logger log = LoggerFactory.getLogger(MetadataFilterChain.class); + + + private final List filters = new ArrayList<>(); + + /** + * Return all actually used Metadata filters. + * + * @return List of Metadata filters + */ + public List getFilters() { + return filters; + } + + /** + * Add a new Metadata filter to filterchain. + * + * @param filter add a metadata filter + */ + public void addFilter(final MetadataFilter filter) { + filters.add(filter); + } + + + /* + * (non-Javadoc) + * + * @see org.opensaml.saml2.metadata.provider.MetadataFilter#doFilter(org.opensaml.xml.XMLObject) + */ + @Override + public void doFilter(final XMLObject arg0) throws FilterException { + for (final MetadataFilter filter : filters) { + log.trace("Use EAAFMetadataFilter " + filter.getClass().getName()); + filter.doFilter(arg0); + } - } + } } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/metadata/SimpleMetadataProvider.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/metadata/SimpleMetadataProvider.java index c16ca5fd..67dd1d35 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/metadata/SimpleMetadataProvider.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/metadata/SimpleMetadataProvider.java @@ -1,37 +1,32 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.impl.metadata; import java.io.File; import java.net.MalformedURLException; import java.util.Timer; - import javax.net.ssl.SSLHandshakeException; - +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.impl.utils.FileUtils; +import at.gv.egiz.eaaf.modules.pvp2.exception.SchemaValidationException; +import at.gv.egiz.eaaf.modules.pvp2.exception.SignatureValidationException; import org.apache.commons.httpclient.HttpClient; import org.opensaml.saml2.metadata.provider.FilesystemMetadataProvider; import org.opensaml.saml2.metadata.provider.HTTPMetadataProvider; @@ -42,195 +37,193 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.impl.utils.FileUtils; -import at.gv.egiz.eaaf.modules.pvp2.exception.SchemaValidationException; -import at.gv.egiz.eaaf.modules.pvp2.exception.SignatureValidationException; - /** + * Simple SAML2 metadata provider. + * * @author tlenz * */ -public abstract class SimpleMetadataProvider implements MetadataProvider{ - private static final Logger log = LoggerFactory.getLogger(SimpleMetadataProvider.class); - - private static final String URI_PREFIX_HTTP = "http:"; - private static final String URI_PREFIX_HTTPS = "https:"; - private static final String URI_PREFIX_FILE = "file:"; - - - @Autowired - protected IConfiguration authConfig; - - - /** - * Create a single SAML2 metadata provider - * - * @param metadataLocation where the metadata should be loaded, but never null. If the location starts with http(s):, than a http - * based metadata provider is used. If the location starts with file:, than a filesystem based metadata provider is used - * @param filter Filters, which should be used to validate the metadata - * @param IdForLogging Id, which is used for Logging - * @param timer {@link Timer} which is used to schedule metadata refresh operations - * @param httpClient Apache commons 3.x http client - * - * @return SAML2 Metadata Provider, or null if the metadata provider can not initialized - */ - protected MetadataProvider createNewSimpleMetadataProvider(String metadataLocation, MetadataFilter filter, - String IdForLogging, Timer timer, ParserPool pool, HttpClient httpClient) { - if (metadataLocation.startsWith(URI_PREFIX_HTTP) || metadataLocation.startsWith(URI_PREFIX_HTTPS)) { - if (httpClient != null) - return createNewHTTPMetaDataProvider(metadataLocation, filter, IdForLogging, timer, pool, httpClient); - - else { - log.warn("Can not load http(s) based SAML2 metadata without a HTTP client"); - return null; - } - - } else { - String absoluteMetadataLocation; - try { - absoluteMetadataLocation = FileUtils.makeAbsoluteURL( - metadataLocation, - authConfig.getConfigurationRootDirectory()); - - if (absoluteMetadataLocation.startsWith(URI_PREFIX_FILE)) { - File metadataFile = new File(absoluteMetadataLocation); - if (metadataFile.exists()) - return createNewFileSystemMetaDataProvider(metadataFile, filter, IdForLogging, timer, pool); - - else { - log.warn("SAML2 metadata file: " + absoluteMetadataLocation + " not found or not exist"); - return null; - } - - } - - - } catch (MalformedURLException e) { - log.warn("SAML2 metadata URL is invalid: " + metadataLocation, e); - - } - - } - - log.warn("SAML2 metadata has an unsupported metadata location prefix: " + metadataLocation); - return null; - - } - - - /** - * Create a single SAML2 filesystem based metadata provider - * - * @param metadataFile File, where the metadata should be loaded - * @param filter Filters, which should be used to validate the metadata - * @param IdForLogging Id, which is used for Logging - * @param timer {@link Timer} which is used to schedule metadata refresh operations - * @param pool - * - * @return SAML2 Metadata Provider - */ - private MetadataProvider createNewFileSystemMetaDataProvider(File metadataFile, MetadataFilter filter, String IdForLogging, Timer timer, ParserPool pool) { - FilesystemMetadataProvider fileSystemProvider = null; - try { - fileSystemProvider = new FilesystemMetadataProvider(timer, metadataFile); - fileSystemProvider.setParserPool(pool); - fileSystemProvider.setRequireValidMetadata(true); - fileSystemProvider.setMinRefreshDelay(1000*60*15); //15 minutes - fileSystemProvider.setMaxRefreshDelay(1000*60*60*24); //24 hours - //httpProvider.setRefreshDelayFactor(0.1F); - - fileSystemProvider.setMetadataFilter(filter); - fileSystemProvider.initialize(); - - fileSystemProvider.setRequireValidMetadata(true); - - return fileSystemProvider; - - } catch (Exception e) { - log.warn( - "Failed to load Metadata file for " - + IdForLogging + "[ " - + "File: " + metadataFile.getAbsolutePath() - + " Msg: " + e.getMessage() + " ]", e); - - - log.warn("Can not initialize SAML2 metadata provider from filesystem: " + metadataFile.getAbsolutePath() - + " Reason: " + e.getMessage(), e); - - if (fileSystemProvider != null) - fileSystemProvider.destroy(); - - } - - return null; - - } - - - - /** - * Create a single SAML2 HTTP metadata provider - * - * @param metadataURL URL, where the metadata should be loaded - * @param filter Filters, which should be used to validate the metadata - * @param IdForLogging Id, which is used for Logging - * @param timer {@link Timer} which is used to schedule metadata refresh operations - * @param pool - * - * @return SAML2 Metadata Provider - */ - private MetadataProvider createNewHTTPMetaDataProvider(String metadataURL, MetadataFilter filter, String IdForLogging, Timer timer, ParserPool pool, HttpClient httpClient) { - HTTPMetadataProvider httpProvider = null; - try { - httpProvider = new HTTPMetadataProvider(timer, httpClient, - metadataURL); - httpProvider.setParserPool(pool); - httpProvider.setRequireValidMetadata(true); - httpProvider.setMinRefreshDelay(1000*60*15); //15 minutes - httpProvider.setMaxRefreshDelay(1000*60*60*24); //24 hours - //httpProvider.setRefreshDelayFactor(0.1F); - - httpProvider.setMetadataFilter(filter); - httpProvider.initialize(); - - httpProvider.setRequireValidMetadata(true); - - return httpProvider; - - } catch (Throwable e) { - if (e.getCause() != null && e.getCause().getCause() instanceof SSLHandshakeException) { - log.warn("SSL-Server certificate for metadata " - + metadataURL + " not trusted.", e); - - } if (e.getCause() != null && e.getCause().getCause() instanceof SignatureValidationException) { - log.warn("Signature verification for metadata" - + metadataURL + " FAILED.", e); - - } if (e.getCause() != null && e.getCause().getCause() instanceof SchemaValidationException) { - log.warn("Schema validation for metadata " - + metadataURL + " FAILED.", e); - } - - log.warn( - "Failed to load Metadata file for " - + IdForLogging + "[ " - + e.getMessage() + " ]", e); - - if (httpProvider != null) { - log.debug("Destroy failed Metadata provider"); - httpProvider.destroy(); - } - -// if (timer != null) { -// log.debug("Destroy Timer."); -// timer.cancel(); -// } - - - } - - return null; - } +public abstract class SimpleMetadataProvider implements MetadataProvider { + private static final Logger log = LoggerFactory.getLogger(SimpleMetadataProvider.class); + + private static final String URI_PREFIX_HTTP = "http:"; + private static final String URI_PREFIX_HTTPS = "https:"; + private static final String URI_PREFIX_FILE = "file:"; + + + @Autowired + protected IConfiguration authConfig; + + + /** + * Create a single SAML2 metadata provider. + * + * @param metadataLocation where the metadata should be loaded, but never null. If the location + * starts with http(s):, than a http based metadata provider is used. If the location + * starts with file:, than a filesystem based metadata provider is used + * @param filter Filters, which should be used to validate the metadata + * @param idForLogging Id, which is used for Logging + * @param timer {@link Timer} which is used to schedule metadata refresh operations + * @param httpClient Apache commons 3.x http client + * + * @return SAML2 Metadata Provider, or null if the metadata provider can not initialized + */ + protected MetadataProvider createNewSimpleMetadataProvider(final String metadataLocation, + final MetadataFilter filter, final String idForLogging, final Timer timer, + final ParserPool pool, final HttpClient httpClient) { + if (metadataLocation.startsWith(URI_PREFIX_HTTP) + || metadataLocation.startsWith(URI_PREFIX_HTTPS)) { + if (httpClient != null) { + return createNewHttpMetaDataProvider(metadataLocation, filter, idForLogging, timer, pool, + httpClient); + } else { + log.warn("Can not load http(s) based SAML2 metadata without a HTTP client"); + return null; + } + + } else { + String absoluteMetadataLocation; + try { + absoluteMetadataLocation = + FileUtils.makeAbsoluteUrl(metadataLocation, authConfig.getConfigurationRootDirectory()); + + if (absoluteMetadataLocation.startsWith(URI_PREFIX_FILE)) { + final File metadataFile = new File(absoluteMetadataLocation); + if (metadataFile.exists()) { + return createNewFileSystemMetaDataProvider(metadataFile, filter, idForLogging, timer, + pool); + } else { + log.warn( + "SAML2 metadata file: " + absoluteMetadataLocation + " not found or not exist"); + return null; + } + + } + + + } catch (final MalformedURLException e) { + log.warn("SAML2 metadata URL is invalid: " + metadataLocation, e); + + } + + } + + log.warn("SAML2 metadata has an unsupported metadata location prefix: " + metadataLocation); + return null; + + } + + + /** + * Create a single SAML2 filesystem based metadata provider. + * + * @param metadataFile File, where the metadata should be loaded + * @param filter Filters, which should be used to validate the metadata + * @param idForLogging Id, which is used for Logging + * @param timer {@link Timer} which is used to schedule metadata refresh operations + * @param pool + * + * @return SAML2 Metadata Provider + */ + private MetadataProvider createNewFileSystemMetaDataProvider(final File metadataFile, + final MetadataFilter filter, final String idForLogging, final Timer timer, + final ParserPool pool) { + FilesystemMetadataProvider fileSystemProvider = null; + try { + fileSystemProvider = new FilesystemMetadataProvider(timer, metadataFile); + fileSystemProvider.setParserPool(pool); + fileSystemProvider.setRequireValidMetadata(true); + fileSystemProvider.setMinRefreshDelay(1000 * 60 * 15); // 15 minutes + fileSystemProvider.setMaxRefreshDelay(1000 * 60 * 60 * 24); // 24 hours + // httpProvider.setRefreshDelayFactor(0.1F); + + fileSystemProvider.setMetadataFilter(filter); + fileSystemProvider.initialize(); + + fileSystemProvider.setRequireValidMetadata(true); + + return fileSystemProvider; + + } catch (final Exception e) { + log.warn("Failed to load Metadata file for " + idForLogging + "[ " + "File: " + + metadataFile.getAbsolutePath() + " Msg: " + e.getMessage() + " ]", e); + + + log.warn("Can not initialize SAML2 metadata provider from filesystem: " + + metadataFile.getAbsolutePath() + " Reason: " + e.getMessage(), e); + + if (fileSystemProvider != null) { + fileSystemProvider.destroy(); + } + + } + + return null; + + } + + + + /** + * Create a single SAML2 HTTP metadata provider. + * + * @param metadataUrl URL, where the metadata should be loaded + * @param filter Filters, which should be used to validate the metadata + * @param idForLogging Id, which is used for Logging + * @param timer {@link Timer} which is used to schedule metadata refresh operations + * @param pool + * + * @return SAML2 Metadata Provider + */ + private MetadataProvider createNewHttpMetaDataProvider(final String metadataUrl, + final MetadataFilter filter, final String idForLogging, final Timer timer, + final ParserPool pool, final HttpClient httpClient) { + HTTPMetadataProvider httpProvider = null; + try { + httpProvider = new HTTPMetadataProvider(timer, httpClient, metadataUrl); + httpProvider.setParserPool(pool); + httpProvider.setRequireValidMetadata(true); + httpProvider.setMinRefreshDelay(1000 * 60 * 15); // 15 minutes + httpProvider.setMaxRefreshDelay(1000 * 60 * 60 * 24); // 24 hours + // httpProvider.setRefreshDelayFactor(0.1F); + + httpProvider.setMetadataFilter(filter); + httpProvider.initialize(); + + httpProvider.setRequireValidMetadata(true); + + return httpProvider; + + } catch (final Throwable e) { + if (e.getCause() != null && e.getCause().getCause() instanceof SSLHandshakeException) { + log.warn("SSL-Server certificate for metadata " + metadataUrl + " not trusted.", e); + + } + if (e.getCause() != null && e.getCause().getCause() instanceof SignatureValidationException) { + log.warn("Signature verification for metadata" + metadataUrl + " FAILED.", e); + + } + if (e.getCause() != null && e.getCause().getCause() instanceof SchemaValidationException) { + log.warn("Schema validation for metadata " + metadataUrl + " FAILED.", e); + } + + log.warn("Failed to load Metadata file for " + idForLogging + "[ " + e.getMessage() + " ]", + e); + + if (httpProvider != null) { + log.debug("Destroy failed Metadata provider"); + httpProvider.destroy(); + } + + // if (timer != null) { + // log.debug("Destroy Timer."); + // timer.cancel(); + // } + + + } + + return null; + } } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/HTTPPostEncoderWithOwnTemplate.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/HTTPPostEncoderWithOwnTemplate.java deleted file mode 100644 index 8af12acc..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/HTTPPostEncoderWithOwnTemplate.java +++ /dev/null @@ -1,122 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.opensaml; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.Writer; - -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.VelocityEngine; -import org.opensaml.common.binding.SAMLMessageContext; -import org.opensaml.saml2.binding.encoding.HTTPPostEncoder; -import org.opensaml.ws.message.encoder.MessageEncodingException; -import org.opensaml.ws.transport.http.HTTPOutTransport; -import org.opensaml.ws.transport.http.HTTPTransportUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import at.gv.egiz.eaaf.core.api.gui.IVelocityGUIBuilderConfiguration; -import at.gv.egiz.eaaf.core.api.gui.IVelocityGuiFormBuilder; - -/** - * @author tlenz - * - */ -public class HTTPPostEncoderWithOwnTemplate extends HTTPPostEncoder { - private static final Logger log = LoggerFactory.getLogger(HTTPPostEncoderWithOwnTemplate.class); - - - private final VelocityEngine velocityEngine; - private final IVelocityGUIBuilderConfiguration guiConfig; - private final IVelocityGuiFormBuilder guiBuilder; - - /** - * @param engine - * @param templateId - */ - public HTTPPostEncoderWithOwnTemplate(IVelocityGUIBuilderConfiguration guiConfig, IVelocityGuiFormBuilder guiBuilder, VelocityEngine engine) { - super(engine, null); - this.velocityEngine = engine; - this.guiConfig = guiConfig; - this.guiBuilder = guiBuilder; - - } - - /** - * Base64 and POST encodes the outbound message and writes it to the outbound transport. - * - * @param messageContext current message context - * @param endpointURL endpoint URL to which to encode message - * - * @throws MessageEncodingException thrown if there is a problem encoding the message - */ - @Override - protected void postEncode(SAMLMessageContext messageContext, String endpointURL) throws MessageEncodingException { - log.debug("Invoking Velocity template to create POST body"); - InputStream is = null; - try { - //build Velocity Context from GUI input paramters - final VelocityContext context = guiBuilder.generateVelocityContextFromConfiguration(guiConfig); - - //load template - is = guiBuilder.getTemplateInputStream(guiConfig); - - //populate velocity context with SAML2 parameters - populateVelocityContext(context, messageContext, endpointURL); - - //populate transport parameter - final HTTPOutTransport outTransport = (HTTPOutTransport) messageContext.getOutboundMessageTransport(); - HTTPTransportUtils.addNoCacheHeaders(outTransport); - HTTPTransportUtils.setUTF8Encoding(outTransport); - HTTPTransportUtils.setContentType(outTransport, "text/html"); - - //evaluate template and write content to response - final Writer out = new OutputStreamWriter(outTransport.getOutgoingStream(), "UTF-8"); - velocityEngine.evaluate(context, out, "SAML2_POST_BINDING", new BufferedReader(new InputStreamReader(is))); - out.flush(); - - } catch (final Exception e) { - log.error("Error invoking Velocity template", e); - throw new MessageEncodingException("Error creating output document", e); - - } finally { - if (is != null) { - try { - is.close(); - - } catch (final IOException e) { - log.error("Can NOT close GUI-Template InputStream.", e); - } - } - - } - } -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/HttpPostEncoderWithOwnTemplate.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/HttpPostEncoderWithOwnTemplate.java new file mode 100644 index 00000000..860eec64 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/HttpPostEncoderWithOwnTemplate.java @@ -0,0 +1,123 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.impl.opensaml; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.Writer; +import at.gv.egiz.eaaf.core.api.gui.IVelocityGuiBuilderConfiguration; +import at.gv.egiz.eaaf.core.api.gui.IVelocityGuiFormBuilder; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.saml2.binding.encoding.HTTPPostEncoder; +import org.opensaml.ws.message.encoder.MessageEncodingException; +import org.opensaml.ws.transport.http.HTTPOutTransport; +import org.opensaml.ws.transport.http.HTTPTransportUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * OpenSAML2 Post-Binding encoder that uses dynamic loaded templates. + * + * @author tlenz + * + */ +public class HttpPostEncoderWithOwnTemplate extends HTTPPostEncoder { + private static final Logger log = LoggerFactory.getLogger(HttpPostEncoderWithOwnTemplate.class); + + + private final VelocityEngine velocityEngine; + private final IVelocityGuiBuilderConfiguration guiConfig; + private final IVelocityGuiFormBuilder guiBuilder; + + /** + * Own Post-Binding encoder. + * + * @param guiConfig GUI configuration + * @param guiBuilder GUI builder implementation + * @param engine velocity engine + */ + public HttpPostEncoderWithOwnTemplate(final IVelocityGuiBuilderConfiguration guiConfig, + final IVelocityGuiFormBuilder guiBuilder, final VelocityEngine engine) { + super(engine, null); + this.velocityEngine = engine; + this.guiConfig = guiConfig; + this.guiBuilder = guiBuilder; + + } + + /** + * Base64 and POST encodes the outbound message and writes it to the outbound transport. + * + * @param messageContext current message context + * @param endpointUrl endpoint URL to which to encode message + * + * @throws MessageEncodingException thrown if there is a problem encoding the message + */ + @Override + protected void postEncode(final SAMLMessageContext messageContext, final String endpointUrl) + throws MessageEncodingException { + log.debug("Invoking Velocity template to create POST body"); + InputStream is = null; + try { + // build Velocity Context from GUI input paramters + final VelocityContext context = + guiBuilder.generateVelocityContextFromConfiguration(guiConfig); + + // load template + is = guiBuilder.getTemplateInputStream(guiConfig); + + // populate velocity context with SAML2 parameters + populateVelocityContext(context, messageContext, endpointUrl); + + // populate transport parameter + final HTTPOutTransport outTransport = + (HTTPOutTransport) messageContext.getOutboundMessageTransport(); + HTTPTransportUtils.addNoCacheHeaders(outTransport); + HTTPTransportUtils.setUTF8Encoding(outTransport); + HTTPTransportUtils.setContentType(outTransport, "text/html"); + + // evaluate template and write content to response + final Writer out = new OutputStreamWriter(outTransport.getOutgoingStream(), "UTF-8"); + velocityEngine.evaluate(context, out, "SAML2_POST_BINDING", + new BufferedReader(new InputStreamReader(is))); + out.flush(); + + } catch (final Exception e) { + log.error("Error invoking Velocity template", e); + throw new MessageEncodingException("Error creating output document", e); + + } finally { + if (is != null) { + try { + is.close(); + + } catch (final IOException e) { + log.error("Can NOT close GUI-Template InputStream.", e); + } + } + + } + } +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/KeyStoreX509CredentialAdapter.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/KeyStoreX509CredentialAdapter.java index 2f3912ca..d84b407f 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/KeyStoreX509CredentialAdapter.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/KeyStoreX509CredentialAdapter.java @@ -1,56 +1,53 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.impl.opensaml; import java.security.KeyStore; - import org.opensaml.xml.security.x509.X509Credential; /** + * OpenSAML2 KeyStore adapter. + * * @author tlenz * */ -public class KeyStoreX509CredentialAdapter extends - org.opensaml.xml.security.x509.KeyStoreX509CredentialAdapter { - - /** - * @param store - * @param alias - * @param password - */ - public KeyStoreX509CredentialAdapter(KeyStore store, String alias, - char[] password) { - super(store, alias, password); - } - - public Class getCredentialType() { - return X509Credential.class; - } - +public class KeyStoreX509CredentialAdapter + extends org.opensaml.xml.security.x509.KeyStoreX509CredentialAdapter { + + /** + * Get an OpenSAML2 keystore. + * + * @param store Java KeyStore + * @param alias Key alias + * @param password key Password + */ + public KeyStoreX509CredentialAdapter(final KeyStore store, final String alias, + final char[] password) { + super(store, alias, password); + } + + @Override + public Class getCredentialType() { + return X509Credential.class; + } + } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/StringRedirectDeflateEncoder.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/StringRedirectDeflateEncoder.java index 544dc9f5..2def1446 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/StringRedirectDeflateEncoder.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/StringRedirectDeflateEncoder.java @@ -1,31 +1,25 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.impl.opensaml; +import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EaafDefaultSaml2Bootstrap; import org.opensaml.common.binding.SAMLMessageContext; import org.opensaml.saml2.binding.encoding.HTTPRedirectDeflateEncoder; import org.opensaml.ws.message.MessageContext; @@ -33,49 +27,49 @@ import org.opensaml.ws.message.encoder.MessageEncodingException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EAAFDefaultSAML2Bootstrap; - /** + * Create deflate encoded SAML2 redirect-binding informations. + * * @author tlenz * */ public class StringRedirectDeflateEncoder extends HTTPRedirectDeflateEncoder { - private static final Logger log = LoggerFactory.getLogger(StringRedirectDeflateEncoder.class); - - private String redirectURL = null; - - public void encode(MessageContext messageContext) - throws MessageEncodingException { - if (!(messageContext instanceof SAMLMessageContext)) { - log.error("Invalid message context type, this encoder only support SAMLMessageContext"); - throw new MessageEncodingException( - "Invalid message context type, this encoder only support SAMLMessageContext"); - } + private static final Logger log = LoggerFactory.getLogger(StringRedirectDeflateEncoder.class); + + private String redirectUrl = null; + + @Override + public void encode(final MessageContext messageContext) throws MessageEncodingException { + if (!(messageContext instanceof SAMLMessageContext)) { + log.error("Invalid message context type, this encoder only support SAMLMessageContext"); + throw new MessageEncodingException( + "Invalid message context type, this encoder only support SAMLMessageContext"); + } + + // load default PVP security configurations + EaafDefaultSaml2Bootstrap.initializeDefaultPvpConfiguration(); + + final SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; + + final String endpointUrl = getEndpointURL(samlMsgCtx).buildURL(); - //load default PVP security configurations - EAAFDefaultSAML2Bootstrap.initializeDefaultPVPConfiguration(); - - SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; + setResponseDestination(samlMsgCtx.getOutboundSAMLMessage(), endpointUrl); - String endpointURL = getEndpointURL(samlMsgCtx).buildURL(); + removeSignature(samlMsgCtx); - setResponseDestination(samlMsgCtx.getOutboundSAMLMessage(), endpointURL); + final String encodedMessage = deflateAndBase64Encode(samlMsgCtx.getOutboundSAMLMessage()); - removeSignature(samlMsgCtx); + redirectUrl = buildRedirectURL(samlMsgCtx, endpointUrl, encodedMessage); + } - String encodedMessage = deflateAndBase64Encode(samlMsgCtx - .getOutboundSAMLMessage()); + /** + * Get generated redirect URL. + * + * @return the redirectURL + */ + public String getRedirectUrl() { + return redirectUrl; + } - redirectURL = buildRedirectURL(samlMsgCtx, endpointURL, - encodedMessage); - } - /** - * @return the redirectURL - */ - public String getRedirectURL() { - return redirectURL; - } - - } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/initialize/EAAFDefaultSAML2Bootstrap.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/initialize/EAAFDefaultSAML2Bootstrap.java deleted file mode 100644 index 266b6e5f..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/initialize/EAAFDefaultSAML2Bootstrap.java +++ /dev/null @@ -1,94 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize; - -import org.opensaml.Configuration; -import org.opensaml.DefaultBootstrap; -import org.opensaml.xml.ConfigurationException; - -import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EAAFRequestedAttribute; -import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EAAFRequestedAttributes; -import at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr.EAAFRequestedAttributeBuilder; -import at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr.EAAFRequestedAttributeMarshaller; -import at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr.EAAFRequestedAttributeUnmarshaller; -import at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr.EAAFRequestedAttributesBuilder; -import at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr.EAAFRequestedAttributesMarshaller; -import at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr.EAAFRequestedAttributesUnmarshaller; - -/** - * @author tlenz - * - */ -public class EAAFDefaultSAML2Bootstrap extends DefaultBootstrap { - - public static synchronized void bootstrap() throws ConfigurationException { - - initializeXMLSecurity(); - - initializeXMLTooling(); - - initializeArtifactBuilderFactories(); - - initializeGlobalSecurityConfiguration(); - - initializeParserPool(); - - initializeESAPI(); - - initializeExtenstions(); - - } - - private static void initializeExtenstions() { - Configuration.registerObjectProvider( - EAAFRequestedAttribute.DEFAULT_ELEMENT_NAME, - new EAAFRequestedAttributeBuilder(), - new EAAFRequestedAttributeMarshaller(), - new EAAFRequestedAttributeUnmarshaller() - ); - - Configuration.registerObjectProvider( - EAAFRequestedAttributes.DEFAULT_ELEMENT_NAME, - new EAAFRequestedAttributesBuilder(), - new EAAFRequestedAttributesMarshaller(), - new EAAFRequestedAttributesUnmarshaller() - ); - - } - - public static void initializeDefaultPVPConfiguration() { - initializeGlobalSecurityConfiguration(); - - } - - /** - * Initializes the default global security configuration. - */ - protected static void initializeGlobalSecurityConfiguration() { - Configuration.setGlobalSecurityConfiguration(EAAFDefaultSecurityConfigurationBootstrap.buildDefaultConfig()); - } -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/initialize/EAAFDefaultSecurityConfigurationBootstrap.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/initialize/EAAFDefaultSecurityConfigurationBootstrap.java deleted file mode 100644 index ddd5b13e..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/initialize/EAAFDefaultSecurityConfigurationBootstrap.java +++ /dev/null @@ -1,156 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize; - -import org.opensaml.xml.encryption.EncryptionConstants; -import org.opensaml.xml.security.BasicSecurityConfiguration; -import org.opensaml.xml.security.DefaultSecurityConfigurationBootstrap; -import org.opensaml.xml.security.credential.BasicKeyInfoGeneratorFactory; -import org.opensaml.xml.security.keyinfo.KeyInfoGeneratorManager; -import org.opensaml.xml.security.keyinfo.NamedKeyInfoGeneratorManager; -import org.opensaml.xml.security.x509.X509KeyInfoGeneratorFactory; -import org.opensaml.xml.signature.SignatureConstants; - -/** - * @author tlenz - * - */ -public class EAAFDefaultSecurityConfigurationBootstrap extends - DefaultSecurityConfigurationBootstrap { - - public static BasicSecurityConfiguration buildDefaultConfig() { - BasicSecurityConfiguration config = new BasicSecurityConfiguration(); - - populateSignatureParams(config); - populateEncryptionParams(config); - populateKeyInfoCredentialResolverParams(config); - populateKeyInfoGeneratorManager(config); - populateKeyParams(config); - - return config; - } - - protected static void populateKeyInfoGeneratorManager( - BasicSecurityConfiguration config) { - NamedKeyInfoGeneratorManager namedManager = new NamedKeyInfoGeneratorManager(); - config.setKeyInfoGeneratorManager(namedManager); - - namedManager.setUseDefaultManager(true); - KeyInfoGeneratorManager defaultManager = namedManager - .getDefaultManager(); - - BasicKeyInfoGeneratorFactory basicFactory = new BasicKeyInfoGeneratorFactory(); - basicFactory.setEmitPublicKeyValue(true); - - X509KeyInfoGeneratorFactory x509Factory = new X509KeyInfoGeneratorFactory(); - x509Factory.setEmitEntityCertificate(true); - - defaultManager.registerFactory(basicFactory); - defaultManager.registerFactory(x509Factory); - } - - protected static void populateSignatureParams( - BasicSecurityConfiguration config) { - - //use SHA256 instead of SHA1 - config.registerSignatureAlgorithmURI("RSA", - SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); - - config.registerSignatureAlgorithmURI("DSA", - "http://www.w3.org/2000/09/xmldsig#dsa-sha1"); - - //use SHA256 instead of SHA1 - config.registerSignatureAlgorithmURI("EC", - SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA256); - - //use SHA256 instead of SHA1 - config.registerSignatureAlgorithmURI("AES", - SignatureConstants.ALGO_ID_MAC_HMAC_SHA256); - - - config.registerSignatureAlgorithmURI("DESede", - SignatureConstants.ALGO_ID_MAC_HMAC_SHA256); - - config.setSignatureCanonicalizationAlgorithm("http://www.w3.org/2001/10/xml-exc-c14n#"); - config.setSignatureHMACOutputLength(null); - - //use SHA256 instead of SHA1 - config.setSignatureReferenceDigestMethod(SignatureConstants.ALGO_ID_DIGEST_SHA256); - } - - protected static void populateEncryptionParams( - BasicSecurityConfiguration config) { - config.registerDataEncryptionAlgorithmURI("AES", Integer.valueOf(128), - "http://www.w3.org/2001/04/xmlenc#aes128-cbc"); - config.registerDataEncryptionAlgorithmURI("AES", Integer.valueOf(192), - "http://www.w3.org/2001/04/xmlenc#aes192-cbc"); - config.registerDataEncryptionAlgorithmURI("AES", Integer.valueOf(256), - "http://www.w3.org/2001/04/xmlenc#aes256-cbc"); - - //support GCM mode - config.registerDataEncryptionAlgorithmURI("AES", Integer.valueOf(128), - EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128_GCM); - - config.registerDataEncryptionAlgorithmURI("AES", Integer.valueOf(192), - EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES192_GCM); - - config.registerDataEncryptionAlgorithmURI("AES", Integer.valueOf(256), - EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256_GCM); - - - config.registerDataEncryptionAlgorithmURI("DESede", - Integer.valueOf(168), - "http://www.w3.org/2001/04/xmlenc#tripledes-cbc"); - config.registerDataEncryptionAlgorithmURI("DESede", - Integer.valueOf(192), - "http://www.w3.org/2001/04/xmlenc#tripledes-cbc"); - - config.registerKeyTransportEncryptionAlgorithmURI("RSA", null, "AES", - "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"); - - config.registerKeyTransportEncryptionAlgorithmURI("RSA", null, - "DESede", "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"); - - config.registerKeyTransportEncryptionAlgorithmURI("AES", - Integer.valueOf(128), null, - "http://www.w3.org/2001/04/xmlenc#kw-aes128"); - config.registerKeyTransportEncryptionAlgorithmURI("AES", - Integer.valueOf(192), null, - "http://www.w3.org/2001/04/xmlenc#kw-aes192"); - config.registerKeyTransportEncryptionAlgorithmURI("AES", - Integer.valueOf(256), null, - "http://www.w3.org/2001/04/xmlenc#kw-aes256"); - config.registerKeyTransportEncryptionAlgorithmURI("DESede", - Integer.valueOf(168), null, - "http://www.w3.org/2001/04/xmlenc#kw-tripledes"); - config.registerKeyTransportEncryptionAlgorithmURI("DESede", - Integer.valueOf(192), null, - "http://www.w3.org/2001/04/xmlenc#kw-tripledes"); - - config.setAutoGeneratedDataEncryptionKeyAlgorithmURI("http://www.w3.org/2001/04/xmlenc#aes128-cbc"); - } -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/initialize/EaafDefaultSaml2Bootstrap.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/initialize/EaafDefaultSaml2Bootstrap.java new file mode 100644 index 00000000..9db8e5e7 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/initialize/EaafDefaultSaml2Bootstrap.java @@ -0,0 +1,87 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize; + +import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EaafRequestedAttribute; +import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EaafRequestedAttributes; +import at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr.EaafRequestedAttributeBuilder; +import at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr.EaafRequestedAttributeMarshaller; +import at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr.EaafRequestedAttributeUnmarshaller; +import at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr.EaafRequestedAttributesBuilder; +import at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr.EaafRequestedAttributesMarshaller; +import at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr.EaafRequestedAttributesUnmarshaller; +import org.opensaml.DefaultBootstrap; +import org.opensaml.xml.ConfigurationException; + +/** + * EAAF specific OpenSAML Initializer. + * + * @author tlenz + * + */ +public class EaafDefaultSaml2Bootstrap extends DefaultBootstrap { + + /** + * OpenSAML2 bootstrap. + * + * @throws ConfigurationException In case of an error + */ + public static synchronized void bootstrap() throws ConfigurationException { + + initializeXMLSecurity(); + + initializeXMLTooling(); + + initializeArtifactBuilderFactories(); + + initializeGlobalSecurityConfiguration(); + + initializeParserPool(); + + initializeESAPI(); + + initializeExtenstions(); + + } + + private static void initializeExtenstions() { + org.opensaml.xml.Configuration.registerObjectProvider( + EaafRequestedAttribute.DEFAULT_ELEMENT_NAME, new EaafRequestedAttributeBuilder(), + new EaafRequestedAttributeMarshaller(), new EaafRequestedAttributeUnmarshaller()); + + org.opensaml.xml.Configuration.registerObjectProvider( + EaafRequestedAttributes.DEFAULT_ELEMENT_NAME, new EaafRequestedAttributesBuilder(), + new EaafRequestedAttributesMarshaller(), new EaafRequestedAttributesUnmarshaller()); + + } + + public static void initializeDefaultPvpConfiguration() { + initializeGlobalSecurityConfiguration(); + + } + + /** + * Initializes the default global security configuration. + */ + protected static void initializeGlobalSecurityConfiguration() { + org.opensaml.xml.Configuration.setGlobalSecurityConfiguration( + EaafDefaultSecurityConfigurationBootstrap.buildDefaultConfig()); + } +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/initialize/EaafDefaultSecurityConfigurationBootstrap.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/initialize/EaafDefaultSecurityConfigurationBootstrap.java new file mode 100644 index 00000000..a1a7e9d2 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/opensaml/initialize/EaafDefaultSecurityConfigurationBootstrap.java @@ -0,0 +1,141 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize; + +import org.opensaml.xml.encryption.EncryptionConstants; +import org.opensaml.xml.security.BasicSecurityConfiguration; +import org.opensaml.xml.security.DefaultSecurityConfigurationBootstrap; +import org.opensaml.xml.security.credential.BasicKeyInfoGeneratorFactory; +import org.opensaml.xml.security.keyinfo.KeyInfoGeneratorManager; +import org.opensaml.xml.security.keyinfo.NamedKeyInfoGeneratorManager; +import org.opensaml.xml.security.x509.X509KeyInfoGeneratorFactory; +import org.opensaml.xml.signature.SignatureConstants; + +/** + * EAAF specific OpenSAML2 security configuration. + * + * @author tlenz + * + */ +public class EaafDefaultSecurityConfigurationBootstrap + extends DefaultSecurityConfigurationBootstrap { + + /** + * Build EAAF security configuration for OpenSAML2. + * + * @return + */ + public static BasicSecurityConfiguration buildDefaultConfig() { + final BasicSecurityConfiguration config = new BasicSecurityConfiguration(); + + populateSignatureParams(config); + populateEncryptionParams(config); + populateKeyInfoCredentialResolverParams(config); + populateKeyInfoGeneratorManager(config); + populateKeyParams(config); + + return config; + } + + protected static void populateKeyInfoGeneratorManager(final BasicSecurityConfiguration config) { + final NamedKeyInfoGeneratorManager namedManager = new NamedKeyInfoGeneratorManager(); + config.setKeyInfoGeneratorManager(namedManager); + + namedManager.setUseDefaultManager(true); + final KeyInfoGeneratorManager defaultManager = namedManager.getDefaultManager(); + + final BasicKeyInfoGeneratorFactory basicFactory = new BasicKeyInfoGeneratorFactory(); + basicFactory.setEmitPublicKeyValue(true); + + final X509KeyInfoGeneratorFactory x509Factory = new X509KeyInfoGeneratorFactory(); + x509Factory.setEmitEntityCertificate(true); + + defaultManager.registerFactory(basicFactory); + defaultManager.registerFactory(x509Factory); + } + + protected static void populateSignatureParams(final BasicSecurityConfiguration config) { + + // use SHA256 instead of SHA1 + config.registerSignatureAlgorithmURI("RSA", SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); + + config.registerSignatureAlgorithmURI("DSA", "http://www.w3.org/2000/09/xmldsig#dsa-sha1"); + + // use SHA256 instead of SHA1 + config.registerSignatureAlgorithmURI("EC", SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA256); + + // use SHA256 instead of SHA1 + config.registerSignatureAlgorithmURI("AES", SignatureConstants.ALGO_ID_MAC_HMAC_SHA256); + + + config.registerSignatureAlgorithmURI("DESede", SignatureConstants.ALGO_ID_MAC_HMAC_SHA256); + + config.setSignatureCanonicalizationAlgorithm("http://www.w3.org/2001/10/xml-exc-c14n#"); + config.setSignatureHMACOutputLength(null); + + // use SHA256 instead of SHA1 + config.setSignatureReferenceDigestMethod(SignatureConstants.ALGO_ID_DIGEST_SHA256); + } + + protected static void populateEncryptionParams(final BasicSecurityConfiguration config) { + config.registerDataEncryptionAlgorithmURI("AES", Integer.valueOf(128), + "http://www.w3.org/2001/04/xmlenc#aes128-cbc"); + config.registerDataEncryptionAlgorithmURI("AES", Integer.valueOf(192), + "http://www.w3.org/2001/04/xmlenc#aes192-cbc"); + config.registerDataEncryptionAlgorithmURI("AES", Integer.valueOf(256), + "http://www.w3.org/2001/04/xmlenc#aes256-cbc"); + + // support GCM mode + config.registerDataEncryptionAlgorithmURI("AES", Integer.valueOf(128), + EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128_GCM); + + config.registerDataEncryptionAlgorithmURI("AES", Integer.valueOf(192), + EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES192_GCM); + + config.registerDataEncryptionAlgorithmURI("AES", Integer.valueOf(256), + EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256_GCM); + + + config.registerDataEncryptionAlgorithmURI("DESede", Integer.valueOf(168), + "http://www.w3.org/2001/04/xmlenc#tripledes-cbc"); + config.registerDataEncryptionAlgorithmURI("DESede", Integer.valueOf(192), + "http://www.w3.org/2001/04/xmlenc#tripledes-cbc"); + + config.registerKeyTransportEncryptionAlgorithmURI("RSA", null, "AES", + "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"); + + config.registerKeyTransportEncryptionAlgorithmURI("RSA", null, "DESede", + "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"); + + config.registerKeyTransportEncryptionAlgorithmURI("AES", Integer.valueOf(128), null, + "http://www.w3.org/2001/04/xmlenc#kw-aes128"); + config.registerKeyTransportEncryptionAlgorithmURI("AES", Integer.valueOf(192), null, + "http://www.w3.org/2001/04/xmlenc#kw-aes192"); + config.registerKeyTransportEncryptionAlgorithmURI("AES", Integer.valueOf(256), null, + "http://www.w3.org/2001/04/xmlenc#kw-aes256"); + config.registerKeyTransportEncryptionAlgorithmURI("DESede", Integer.valueOf(168), null, + "http://www.w3.org/2001/04/xmlenc#kw-tripledes"); + config.registerKeyTransportEncryptionAlgorithmURI("DESede", Integer.valueOf(192), null, + "http://www.w3.org/2001/04/xmlenc#kw-tripledes"); + + config.setAutoGeneratedDataEncryptionKeyAlgorithmURI( + "http://www.w3.org/2001/04/xmlenc#aes128-cbc"); + } +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/reqattr/EAAFRequestedAttributeImpl.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/reqattr/EAAFRequestedAttributeImpl.java deleted file mode 100644 index ed169d8c..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/reqattr/EAAFRequestedAttributeImpl.java +++ /dev/null @@ -1,133 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.reqattr; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.opensaml.common.impl.AbstractSAMLObject; -import org.opensaml.xml.XMLObject; -import org.opensaml.xml.schema.XSBooleanValue; -import org.opensaml.xml.util.AttributeMap; -import org.opensaml.xml.util.XMLObjectChildrenList; - -import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EAAFRequestedAttribute; - -public class EAAFRequestedAttributeImpl extends AbstractSAMLObject implements EAAFRequestedAttribute { - - private final XMLObjectChildrenList attributeValues; - private String friendlyName; - private String isRequired; - private String name; - private String nameFormat; - private AttributeMap unknownAttributes; - - public EAAFRequestedAttributeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { - super(namespaceURI, elementLocalName, namespacePrefix); - unknownAttributes = new AttributeMap(this); - attributeValues = new XMLObjectChildrenList(this); - - } - - public final List getAttributeValues() { - return attributeValues; - } - - public final String getFriendlyName() { - return friendlyName; - } - - public final String getIsRequiredXSBoolean() { - return isRequired; - } - - public final String getName() { - return name; - } - - public final String getNameFormat() { - return nameFormat; - } - - public final List getOrderedChildren() { - final List children = new ArrayList(); - children.addAll(attributeValues); - return Collections.unmodifiableList(children); - } - - - public final AttributeMap getUnknownAttributes() { - return unknownAttributes; - } - - - public final void setFriendlyName(final String newFriendlyName) { - this.friendlyName = prepareForAssignment(this.friendlyName, - newFriendlyName); - } - - - public final void setIsRequired(final String newIsRequired) { - isRequired = prepareForAssignment(this.isRequired, newIsRequired); - - } - - - public final void setName(final String newName) { - this.name = prepareForAssignment(this.name, newName); - } - - - public final void setNameFormat(final String newNameFormat) { - this.nameFormat = prepareForAssignment(this.nameFormat, newNameFormat); - } - - - public final void setUnknownAttributes(final AttributeMap newUnknownAttr) { - this.unknownAttributes = newUnknownAttr; - } - - @Override - public XSBooleanValue isRequiredXSBoolean() { - return XSBooleanValue.valueOf(isRequired); - } - - @Override - public void setIsRequired(Boolean aBoolean) { - this.isRequired = String.valueOf(aBoolean); - } - - @Override - public void setIsRequired(XSBooleanValue xsBooleanValue) { - this.isRequired = String.valueOf(xsBooleanValue); - } - - @Override - public Boolean isRequired() { - return Boolean.parseBoolean(isRequired); - } - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/reqattr/EAAFRequestedAttributesImpl.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/reqattr/EAAFRequestedAttributesImpl.java deleted file mode 100644 index b85d4791..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/reqattr/EAAFRequestedAttributesImpl.java +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.reqattr; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.opensaml.common.impl.AbstractSAMLObject; -import org.opensaml.xml.XMLObject; -import org.opensaml.xml.util.IndexedXMLObjectChildrenList; - -import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EAAFRequestedAttribute; -import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EAAFRequestedAttributes; - -public class EAAFRequestedAttributesImpl extends AbstractSAMLObject implements EAAFRequestedAttributes { - - private final IndexedXMLObjectChildrenList indexedChildren; - - public EAAFRequestedAttributesImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { - super(namespaceURI, elementLocalName, namespacePrefix); - indexedChildren = new IndexedXMLObjectChildrenList(this); - } - - @Override - public List getOrderedChildren() { - final List children = new ArrayList(); - children.addAll(indexedChildren); - return Collections.unmodifiableList(children); - - } - - @Override - public List getAttributes() { - return (List) indexedChildren - .subList(EAAFRequestedAttribute.DEFAULT_ELEMENT_NAME); - } - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/reqattr/EaafRequestedAttributeImpl.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/reqattr/EaafRequestedAttributeImpl.java new file mode 100644 index 00000000..1ceb5adc --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/reqattr/EaafRequestedAttributeImpl.java @@ -0,0 +1,149 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.impl.reqattr; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EaafRequestedAttribute; +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.schema.XSBooleanValue; +import org.opensaml.xml.util.AttributeMap; +import org.opensaml.xml.util.XMLObjectChildrenList; + +public class EaafRequestedAttributeImpl extends AbstractSAMLObject + implements EaafRequestedAttribute { + + private final XMLObjectChildrenList attributeValues; + private String friendlyName; + private String isRequired; + private String name; + private String nameFormat; + private AttributeMap unknownAttributes; + + /** + * Build an EAAF specific requested attribute. + * + * @param namespaceUri Attribute namespace + * @param elementLocalName Attribute name + * @param namespacePrefix Attribute namespace prefix + */ + public EaafRequestedAttributeImpl(final String namespaceUri, final String elementLocalName, + final String namespacePrefix) { + super(namespaceUri, elementLocalName, namespacePrefix); + unknownAttributes = new AttributeMap(this); + attributeValues = new XMLObjectChildrenList<>(this); + + } + + @Override + public final List getAttributeValues() { + return attributeValues; + } + + @Override + public final String getFriendlyName() { + return friendlyName; + } + + @Override + public final String getIsRequiredXsBoolean() { + return isRequired; + } + + @Override + public final String getName() { + return name; + } + + @Override + public final String getNameFormat() { + return nameFormat; + } + + @Override + public final List getOrderedChildren() { + final List children = new ArrayList<>(); + children.addAll(attributeValues); + return Collections.unmodifiableList(children); + } + + + @Override + public final AttributeMap getUnknownAttributes() { + return unknownAttributes; + } + + + @Override + public final void setFriendlyName(final String newFriendlyName) { + this.friendlyName = prepareForAssignment(this.friendlyName, newFriendlyName); + } + + + @Override + public void setIsRequired(final Boolean aboolean) { + this.isRequired = String.valueOf(aboolean); + } + + @Override + public void setIsRequired(final XSBooleanValue xsBooleanValue) { + this.isRequired = String.valueOf(xsBooleanValue); + } + + @Override + public final void setIsRequired(final String newIsRequired) { + isRequired = prepareForAssignment(this.isRequired, newIsRequired); + + } + + + @Override + public final void setName(final String newName) { + this.name = prepareForAssignment(this.name, newName); + } + + + @Override + public final void setNameFormat(final String newNameFormat) { + this.nameFormat = prepareForAssignment(this.nameFormat, newNameFormat); + } + + + public final void setUnknownAttributes(final AttributeMap newUnknownAttr) { + this.unknownAttributes = newUnknownAttr; + } + + @Override + public XSBooleanValue isRequiredXSBoolean() { + return XSBooleanValue.valueOf(isRequired); + } + + + + + + @Override + public Boolean isRequired() { + return Boolean.parseBoolean(isRequired); + } + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/reqattr/EaafRequestedAttributesImpl.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/reqattr/EaafRequestedAttributesImpl.java new file mode 100644 index 00000000..3b447538 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/reqattr/EaafRequestedAttributesImpl.java @@ -0,0 +1,56 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.impl.reqattr; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EaafRequestedAttribute; +import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EaafRequestedAttributes; +import org.opensaml.common.impl.AbstractSAMLObject; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.util.IndexedXMLObjectChildrenList; + +public class EaafRequestedAttributesImpl extends AbstractSAMLObject + implements EaafRequestedAttributes { + + private final IndexedXMLObjectChildrenList indexedChildren; + + public EaafRequestedAttributesImpl(final String namespaceUri, final String elementLocalName, + final String namespacePrefix) { + super(namespaceUri, elementLocalName, namespacePrefix); + indexedChildren = new IndexedXMLObjectChildrenList<>(this); + } + + @Override + public List getOrderedChildren() { + final List children = new ArrayList<>(); + children.addAll(indexedChildren); + return Collections.unmodifiableList(children); + + } + + @Override + public List getAttributes() { + return (List) indexedChildren + .subList(EaafRequestedAttribute.DEFAULT_ELEMENT_NAME); + } + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/utils/AbstractCredentialProvider.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/utils/AbstractCredentialProvider.java index acc5357e..ea361f11 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/utils/AbstractCredentialProvider.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/utils/AbstractCredentialProvider.java @@ -1,36 +1,32 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.impl.utils; import java.security.KeyStore; import java.security.PrivateKey; import java.security.interfaces.ECPrivateKey; import java.security.interfaces.RSAPrivateKey; - +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.impl.utils.KeyStoreUtils; +import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException; +import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.KeyStoreX509CredentialAdapter; import org.apache.commons.lang3.StringUtils; import org.opensaml.xml.security.credential.Credential; import org.opensaml.xml.security.credential.UsageType; @@ -40,186 +36,210 @@ import org.opensaml.xml.signature.SignatureConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.core.impl.utils.KeyStoreUtils; -import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException; -import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.KeyStoreX509CredentialAdapter; - public abstract class AbstractCredentialProvider { - - private static final Logger log = LoggerFactory.getLogger(AbstractCredentialProvider.class); - - private KeyStore keyStore = null; - - /** - * Get a friendlyName for this keyStore implementation - * This friendlyName is used for logging - * - * @return keyStore friendlyName - */ - public abstract String getFriendlyName(); - - /** - * Get KeyStore - * - * @return URL to the keyStore - * @throws EAAFException - */ - public abstract String getKeyStoreFilePath() throws EAAFException; - - /** - * Get keyStore password - * - * @return Password of the keyStore - */ - public abstract String getKeyStorePassword(); - - /** - * Get alias of key for metadata signing - * - * @return key alias - */ - public abstract String getMetadataKeyAlias(); - - /** - * Get password of key for metadata signing - * - * @return key password - */ - public abstract String getMetadataKeyPassword(); - - /** - * Get alias of key for request/response signing - * - * @return key alias - */ - public abstract String getSignatureKeyAlias(); - - /** - * Get password of key for request/response signing - * - * @return key password - */ - public abstract String getSignatureKeyPassword(); - - /** - * Get alias of key for IDP response encryption - * - * @return key alias - */ - public abstract String getEncryptionKeyAlias(); - - /** - * Get password of key for IDP response encryption - * - * @return key password - */ - public abstract String getEncryptionKeyPassword(); - - - public X509Credential getIDPMetaDataSigningCredential() - throws CredentialsNotAvailableException { - try { - - if (keyStore == null) - keyStore = KeyStoreUtils.loadKeyStore(getKeyStoreFilePath(), - getKeyStorePassword()); - - KeyStoreX509CredentialAdapter credentials = new KeyStoreX509CredentialAdapter( - keyStore, getMetadataKeyAlias(), getMetadataKeyPassword().toCharArray()); - - credentials.setUsageType(UsageType.SIGNING); - if (credentials.getPrivateKey() == null && credentials.getSecretKey() == null) { - log.error(getFriendlyName() + " Metadata Signing credentials is not found or contains no PrivateKey."); - throw new CredentialsNotAvailableException("config.27", new Object[]{getFriendlyName() + " Assertion Signing credentials (Alias: " - + getMetadataKeyAlias() + ") is not found or contains no PrivateKey."}); - - } - return credentials; - } catch (Exception e) { - log.error("Failed to generate " + getFriendlyName() + " Metadata Signing credentials"); - e.printStackTrace(); - throw new CredentialsNotAvailableException("config.27", new Object[]{e.getMessage()}, e); - } - } - - public X509Credential getIDPAssertionSigningCredential() - throws CredentialsNotAvailableException { - try { - if (keyStore == null) - keyStore = KeyStoreUtils.loadKeyStore(getKeyStoreFilePath(), - getKeyStorePassword()); - - KeyStoreX509CredentialAdapter credentials = new KeyStoreX509CredentialAdapter( - keyStore, getSignatureKeyAlias(), getSignatureKeyPassword().toCharArray()); - - credentials.setUsageType(UsageType.SIGNING); - if (credentials.getPrivateKey() == null && credentials.getSecretKey() == null) { - log.error(getFriendlyName() + " Assertion Signing credentials is not found or contains no PrivateKey."); - throw new CredentialsNotAvailableException("config.27", new Object[]{getFriendlyName() + " Assertion Signing credentials (Alias: " - + getSignatureKeyAlias() + ") is not found or contains no PrivateKey."}); - - } - - return (X509Credential) credentials; - } catch (Exception e) { - log.error("Failed to generate " + getFriendlyName() + " Assertion Signing credentials"); - e.printStackTrace(); - throw new CredentialsNotAvailableException("config.27", new Object[]{e.getMessage()}, e); - } - } - - public X509Credential getIDPAssertionEncryptionCredential() - throws CredentialsNotAvailableException { - try { - if (keyStore == null) - keyStore = KeyStoreUtils.loadKeyStore(getKeyStoreFilePath(), - getKeyStorePassword()); - - //if no encryption key is configured return null - if (StringUtils.isEmpty(getEncryptionKeyAlias())) - return null; - - KeyStoreX509CredentialAdapter credentials = new KeyStoreX509CredentialAdapter( - keyStore, getEncryptionKeyAlias(), getEncryptionKeyPassword().toCharArray()); - - credentials.setUsageType(UsageType.ENCRYPTION); - - if (credentials.getPrivateKey() == null && credentials.getSecretKey() == null) { - log.error(getFriendlyName() + " Assertion Encryption credentials is not found or contains no PrivateKey."); - throw new CredentialsNotAvailableException("config.27", new Object[]{getFriendlyName() + " Assertion Encryption credentials (Alias: " - + getEncryptionKeyAlias() + ") is not found or contains no PrivateKey."}); - - } - - return (X509Credential) credentials; - - } catch (Exception e) { - log.error("Failed to generate " + getFriendlyName() + " Assertion Encryption credentials"); - e.printStackTrace(); - throw new CredentialsNotAvailableException("config.27", new Object[]{e.getMessage()}, e); - } - } - - public static Signature getIDPSignature(Credential credentials) { - PrivateKey privatekey = credentials.getPrivateKey(); - Signature signer = SAML2Utils.createSAMLObject(Signature.class); - - if (privatekey instanceof RSAPrivateKey) { - signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); - - } else if (privatekey instanceof ECPrivateKey) { - signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA256); - - } else { - log.warn("Could NOT evaluate the Private-Key type from " + credentials.getEntityId() + " credential."); - - - } - - signer.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); - signer.setSigningCredential(credentials); - return signer; - - } + + private static final Logger log = LoggerFactory.getLogger(AbstractCredentialProvider.class); + + private KeyStore keyStore = null; + + /** + * Get a friendlyName for this keyStore implementation This friendlyName is used for logging. + * + * @return keyStore friendlyName + */ + public abstract String getFriendlyName(); + + /** + * Get KeyStore. + * + * @return URL to the keyStore + * @throws EaafException In case of an invalid filepath + */ + public abstract String getKeyStoreFilePath() throws EaafException; + + /** + * Get keyStore password. + * + * @return Password of the keyStore + */ + public abstract String getKeyStorePassword(); + + /** + * Get alias of key for metadata signing. + * + * @return key alias + */ + public abstract String getMetadataKeyAlias(); + + /** + * Get password of key for metadata signing. + * + * @return key password + */ + public abstract String getMetadataKeyPassword(); + + /** + * Get alias of key for request/response signing. + * + * @return key alias + */ + public abstract String getSignatureKeyAlias(); + + /** + * Get password of key for request/response signing. + * + * @return key password + */ + public abstract String getSignatureKeyPassword(); + + /** + * Get alias of key for IDP response encryption. + * + * @return key alias + */ + public abstract String getEncryptionKeyAlias(); + + /** + * Get password of key for IDP response encryption. + * + * @return key password + */ + public abstract String getEncryptionKeyPassword(); + + + /** + * Get Credentials to sign metadata. + * + * @return Credentials + * @throws CredentialsNotAvailableException In case of a credential error + */ + public X509Credential getIdpMetaDataSigningCredential() throws CredentialsNotAvailableException { + try { + + if (keyStore == null) { + keyStore = KeyStoreUtils.loadKeyStore(getKeyStoreFilePath(), getKeyStorePassword()); + } + + final KeyStoreX509CredentialAdapter credentials = new KeyStoreX509CredentialAdapter(keyStore, + getMetadataKeyAlias(), getMetadataKeyPassword().toCharArray()); + + credentials.setUsageType(UsageType.SIGNING); + if (credentials.getPrivateKey() == null && credentials.getSecretKey() == null) { + log.error(getFriendlyName() + + " Metadata Signing credentials is not found or contains no PrivateKey."); + throw new CredentialsNotAvailableException("config.27", + new Object[] {getFriendlyName() + " Assertion Signing credentials (Alias: " + + getMetadataKeyAlias() + ") is not found or contains no PrivateKey."}); + + } + return credentials; + } catch (final Exception e) { + log.error("Failed to generate " + getFriendlyName() + " Metadata Signing credentials"); + e.printStackTrace(); + throw new CredentialsNotAvailableException("config.27", new Object[] {e.getMessage()}, e); + } + } + + /** + * Get Credentials to sign Assertion. + * + * @return Credentials + * @throws CredentialsNotAvailableException In case of a credential error + */ + public X509Credential getIdpAssertionSigningCredential() throws CredentialsNotAvailableException { + try { + if (keyStore == null) { + keyStore = KeyStoreUtils.loadKeyStore(getKeyStoreFilePath(), getKeyStorePassword()); + } + + final KeyStoreX509CredentialAdapter credentials = new KeyStoreX509CredentialAdapter(keyStore, + getSignatureKeyAlias(), getSignatureKeyPassword().toCharArray()); + + credentials.setUsageType(UsageType.SIGNING); + if (credentials.getPrivateKey() == null && credentials.getSecretKey() == null) { + log.error(getFriendlyName() + + " Assertion Signing credentials is not found or contains no PrivateKey."); + throw new CredentialsNotAvailableException("config.27", + new Object[] {getFriendlyName() + " Assertion Signing credentials (Alias: " + + getSignatureKeyAlias() + ") is not found or contains no PrivateKey."}); + + } + + return credentials; + } catch (final Exception e) { + log.error("Failed to generate " + getFriendlyName() + " Assertion Signing credentials"); + e.printStackTrace(); + throw new CredentialsNotAvailableException("config.27", new Object[] {e.getMessage()}, e); + } + } + + /** + * Get Credentials to encrypt assertion. + * + * @return Credentials + * @throws CredentialsNotAvailableException In case of a credential error + */ + public X509Credential getIdpAssertionEncryptionCredential() + throws CredentialsNotAvailableException { + try { + if (keyStore == null) { + keyStore = KeyStoreUtils.loadKeyStore(getKeyStoreFilePath(), getKeyStorePassword()); + } + + // if no encryption key is configured return null + if (StringUtils.isEmpty(getEncryptionKeyAlias())) { + return null; + } + + final KeyStoreX509CredentialAdapter credentials = new KeyStoreX509CredentialAdapter(keyStore, + getEncryptionKeyAlias(), getEncryptionKeyPassword().toCharArray()); + + credentials.setUsageType(UsageType.ENCRYPTION); + + if (credentials.getPrivateKey() == null && credentials.getSecretKey() == null) { + log.error(getFriendlyName() + + " Assertion Encryption credentials is not found or contains no PrivateKey."); + throw new CredentialsNotAvailableException("config.27", + new Object[] {getFriendlyName() + " Assertion Encryption credentials (Alias: " + + getEncryptionKeyAlias() + ") is not found or contains no PrivateKey."}); + + } + + return credentials; + + } catch (final Exception e) { + log.error("Failed to generate " + getFriendlyName() + " Assertion Encryption credentials"); + e.printStackTrace(); + throw new CredentialsNotAvailableException("config.27", new Object[] {e.getMessage()}, e); + } + } + + /** + * Get an XML signature object. + * + * @param credentials Credentials for signing + * @return OpenSAML Signature object + */ + public static Signature getIdpSignature(final Credential credentials) { + final PrivateKey privatekey = credentials.getPrivateKey(); + final Signature signer = Saml2Utils.createSamlObject(Signature.class); + + if (privatekey instanceof RSAPrivateKey) { + signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); + + } else if (privatekey instanceof ECPrivateKey) { + signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA256); + + } else { + log.warn("Could NOT evaluate the Private-Key type from " + credentials.getEntityId() + + " credential."); + + + } + + signer.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); + signer.setSigningCredential(credentials); + return signer; + + } } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/utils/QAALevelVerifier.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/utils/QAALevelVerifier.java deleted file mode 100644 index 8e7183d3..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/utils/QAALevelVerifier.java +++ /dev/null @@ -1,104 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.utils; - -import java.util.List; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import at.gv.egiz.eaaf.core.api.data.EAAFConstants; -import at.gv.egiz.eaaf.modules.pvp2.exception.QAANotAllowedException; - -/** - * @author tlenz - * - */ -public class QAALevelVerifier { - - private static final Logger log = LoggerFactory.getLogger(QAALevelVerifier.class); - - private static boolean verifyQAALevel(String qaaAuth, String requiredLoA, String matchingMode) throws QAANotAllowedException { - //to MINIMUM machting - if (EAAFConstants.EIDAS_LOA_MATCHING_MINIMUM.equals(matchingMode)) { - log.trace("Perfom LoA matching in 'MINIMUM' mode ... "); - if (EAAFConstants.EIDAS_LOA_LOW.equals(requiredLoA) && - (EAAFConstants.EIDAS_LOA_LOW.equals(qaaAuth) || - EAAFConstants.EIDAS_LOA_SUBSTANTIAL.equals(qaaAuth) || - EAAFConstants.EIDAS_LOA_HIGH.equals(qaaAuth)) - ) - return true; - - else if (EAAFConstants.EIDAS_LOA_SUBSTANTIAL.equals(requiredLoA) && - (EAAFConstants.EIDAS_LOA_SUBSTANTIAL.equals(qaaAuth) || - EAAFConstants.EIDAS_LOA_HIGH.equals(qaaAuth)) - ) - return true; - - else if (EAAFConstants.EIDAS_LOA_HIGH.equals(requiredLoA) && EAAFConstants.EIDAS_LOA_HIGH.equals(qaaAuth)) - return true; - - } else if (EAAFConstants.EIDAS_LOA_MATCHING_EXACT.equals(matchingMode)) { - //to EXACT matching - log.trace("Perfom LoA matching in 'EXACT' mode ... "); - if (qaaAuth.equals(requiredLoA)) { - log.debug("Required LoA fits LoA from authentication. Continue auth process ... "); - return true; - - } - - } else { - log.warn("LoA matching-mode:" + matchingMode + " is NOT supported by this implementation"); - throw new QAANotAllowedException(qaaAuth, requiredLoA, matchingMode); - - } - - return false; - - } - - public static void verifyQAALevel(String qaaAuth, List requiredLoAs, String matchingMode) throws QAANotAllowedException { - log.trace("Starting LoA verification: authLoA: " + qaaAuth - + " requiredLoA: " + StringUtils.join(requiredLoAs, "|") - + " matchingMode: " + matchingMode); - - boolean hasMatch = false; - for (String loa : requiredLoAs) { - if (verifyQAALevel(qaaAuth, loa, matchingMode)) - hasMatch = true; - - } - - if (!hasMatch) - throw new QAANotAllowedException(qaaAuth, StringUtils.join(requiredLoAs, "|"), matchingMode); - - else - log.debug("Requesed LoA fits LoA from authentication. Continue auth process ... "); - - } -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/utils/QaaLevelVerifier.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/utils/QaaLevelVerifier.java new file mode 100644 index 00000000..876fa744 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/utils/QaaLevelVerifier.java @@ -0,0 +1,106 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.impl.utils; + +import java.util.List; +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; +import at.gv.egiz.eaaf.modules.pvp2.exception.QaaNotAllowedException; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * EAAF LoA Level verifier checks if requested LoA matchs to LoA of authentication. + * + * + * @author tlenz + * + */ +public class QaaLevelVerifier { + + private static final Logger log = LoggerFactory.getLogger(QaaLevelVerifier.class); + + private static boolean verifyQaaLevel(final String qaaAuth, final String requiredLoA, + final String matchingMode) throws QaaNotAllowedException { + // to MINIMUM machting + if (EAAFConstants.EIDAS_LOA_MATCHING_MINIMUM.equals(matchingMode)) { + log.trace("Perfom LoA matching in 'MINIMUM' mode ... "); + if (EAAFConstants.EIDAS_LOA_LOW.equals(requiredLoA) + && (EAAFConstants.EIDAS_LOA_LOW.equals(qaaAuth) + || EAAFConstants.EIDAS_LOA_SUBSTANTIAL.equals(qaaAuth) + || EAAFConstants.EIDAS_LOA_HIGH.equals(qaaAuth))) { + return true; + } else if (EAAFConstants.EIDAS_LOA_SUBSTANTIAL.equals(requiredLoA) + && (EAAFConstants.EIDAS_LOA_SUBSTANTIAL.equals(qaaAuth) + || EAAFConstants.EIDAS_LOA_HIGH.equals(qaaAuth))) { + return true; + } else if (EAAFConstants.EIDAS_LOA_HIGH.equals(requiredLoA) + && EAAFConstants.EIDAS_LOA_HIGH.equals(qaaAuth)) { + return true; + } + + } else if (EAAFConstants.EIDAS_LOA_MATCHING_EXACT.equals(matchingMode)) { + // to EXACT matching + log.trace("Perfom LoA matching in 'EXACT' mode ... "); + if (qaaAuth.equals(requiredLoA)) { + log.debug("Required LoA fits LoA from authentication. Continue auth process ... "); + return true; + + } + + } else { + log.warn("LoA matching-mode:" + matchingMode + " is NOT supported by this implementation"); + throw new QaaNotAllowedException(qaaAuth, requiredLoA, matchingMode); + + } + + return false; + + } + + /** + * Check LoA level. + * + * @param qaaAuth LoA of authentication + * @param requiredLoAs List of allowed LoA levels + * @param matchingMode LoA matching mode + * @throws QaaNotAllowedException If LoA does not match + */ + public static void verifyQaaLevel(final String qaaAuth, final List requiredLoAs, + final String matchingMode) throws QaaNotAllowedException { + log.trace("Starting LoA verification: authLoA: " + qaaAuth + " requiredLoA: " + + StringUtils.join(requiredLoAs, "|") + " matchingMode: " + matchingMode); + + boolean hasMatch = false; + for (final String loa : requiredLoAs) { + if (verifyQaaLevel(qaaAuth, loa, matchingMode)) { + hasMatch = true; + } + + } + + if (!hasMatch) { + throw new QaaNotAllowedException(qaaAuth, StringUtils.join(requiredLoAs, "|"), matchingMode); + } else { + log.debug("Requesed LoA fits LoA from authentication. Continue auth process ... "); + } + + } +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/utils/SAML2Utils.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/utils/SAML2Utils.java deleted file mode 100644 index d33ee6c6..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/utils/SAML2Utils.java +++ /dev/null @@ -1,201 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.utils; - -import java.io.IOException; -import java.security.NoSuchAlgorithmException; -import java.util.List; - -import javax.xml.namespace.QName; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.TransformerException; -import javax.xml.transform.dom.DOMSource; -import javax.xml.validation.Schema; -import javax.xml.validation.Validator; - -import org.apache.commons.lang3.StringUtils; -import org.opensaml.Configuration; -import org.opensaml.common.impl.SecureRandomIdentifierGenerator; -import org.opensaml.common.xml.SAMLSchemaBuilder; -import org.opensaml.saml2.core.Attribute; -import org.opensaml.saml2.core.Status; -import org.opensaml.saml2.core.StatusCode; -import org.opensaml.saml2.metadata.AssertionConsumerService; -import org.opensaml.saml2.metadata.SPSSODescriptor; -import org.opensaml.ws.soap.soap11.Body; -import org.opensaml.ws.soap.soap11.Envelope; -import org.opensaml.xml.XMLObject; -import org.opensaml.xml.XMLObjectBuilderFactory; -import org.opensaml.xml.io.Marshaller; -import org.opensaml.xml.io.MarshallingException; -import org.opensaml.xml.schema.XSString; -import org.opensaml.xml.schema.impl.XSStringBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; - -import at.gv.egiz.eaaf.core.impl.utils.Random; -import at.gv.egiz.eaaf.modules.pvp2.PVPConstants; -import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EAAFRequestedAttribute; - -public class SAML2Utils { - private static final Logger log = LoggerFactory.getLogger(SAML2Utils.class); - - public static T createSAMLObject(final Class clazz) { - try { - XMLObjectBuilderFactory builderFactory = Configuration - .getBuilderFactory(); - - QName defaultElementName = (QName) clazz.getDeclaredField( - "DEFAULT_ELEMENT_NAME").get(null); - @SuppressWarnings("unchecked") - T object = (T) builderFactory.getBuilder(defaultElementName) - .buildObject(defaultElementName); - return object; - } catch (Throwable e) { - e.printStackTrace(); - return null; - } - } - - public static String getSecureIdentifier() { - return "_".concat(Random.nextHexRandom16()); - - /*Bug-Fix: There are open problems with RandomNumberGenerator via Java SPI and Java JDK 8.121 - * Generation of a 16bit Random identifier FAILES with an Caused by: java.lang.ArrayIndexOutOfBoundsException - * Caused by: java.lang.ArrayIndexOutOfBoundsException - at iaik.security.random.o.engineNextBytes(Unknown Source) - at iaik.security.random.SecRandomSpi.engineNextBytes(Unknown Source) - at java.security.SecureRandom.nextBytes(SecureRandom.java:468) - at org.opensaml.common.impl.SecureRandomIdentifierGenerator.generateIdentifier(SecureRandomIdentifierGenerator.java:62) - at org.opensaml.common.impl.SecureRandomIdentifierGenerator.generateIdentifier(SecureRandomIdentifierGenerator.java:56) - at at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils.getSecureIdentifier(SAML2Utils.java:69) - */ - //return idGenerator.generateIdentifier(); - } - - private static SecureRandomIdentifierGenerator idGenerator; - - private static DocumentBuilder builder; - static { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - try { - builder = factory.newDocumentBuilder(); - } catch (ParserConfigurationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - try { - idGenerator = new SecureRandomIdentifierGenerator(); - } catch(NoSuchAlgorithmException e) { - e.printStackTrace(); - } - } - - public static Document asDOMDocument(XMLObject object) throws IOException, - MarshallingException, TransformerException { - Document document = builder.newDocument(); - Marshaller out = Configuration.getMarshallerFactory().getMarshaller( - object); - out.marshall(object, document); - return document; - } - - public static Status getSuccessStatus() { - Status status = SAML2Utils.createSAMLObject(Status.class); - StatusCode statusCode = SAML2Utils.createSAMLObject(StatusCode.class); - statusCode.setValue(StatusCode.SUCCESS_URI); - status.setStatusCode(statusCode); - return status; - } - - public static int getDefaultAssertionConsumerServiceIndex(SPSSODescriptor spSSODescriptor) { - - List assertionConsumerList = spSSODescriptor.getAssertionConsumerServices(); - - for (AssertionConsumerService el : assertionConsumerList) { - if (el.isDefault()) - return el.getIndex(); - - } - - return 0; - } - - public static Envelope buildSOAP11Envelope(XMLObject payload) { - XMLObjectBuilderFactory bf = Configuration.getBuilderFactory(); - Envelope envelope = (Envelope) bf.getBuilder(Envelope.DEFAULT_ELEMENT_NAME).buildObject(Envelope.DEFAULT_ELEMENT_NAME); - Body body = (Body) bf.getBuilder(Body.DEFAULT_ELEMENT_NAME).buildObject(Body.DEFAULT_ELEMENT_NAME); - - body.getUnknownXMLObjects().add(payload); - envelope.setBody(body); - - return envelope; - } - - public static EAAFRequestedAttribute generateReqAuthnAttributeSimple(Attribute attr, boolean isRequired, String value) { - EAAFRequestedAttribute requested = SAML2Utils.createSAMLObject(EAAFRequestedAttribute.class); - requested.setName(attr.getName()); - requested.setNameFormat(attr.getNameFormat()); - requested.setFriendlyName(attr.getFriendlyName()); - requested.setIsRequired(String.valueOf(isRequired)); - List attributeValues = requested.getAttributeValues(); - if (StringUtils.isNotEmpty(value)) { - XMLObject attributeValueForRequest = createAttributeValue(PVPConstants.EIDAS_REQUESTED_ATTRIBUTE_VALUE_TYPE, value); - attributeValues.add(attributeValueForRequest); - } - return requested; - - } - - public static void schemeValidation(XMLObject xmlObject) throws Exception { - try { - Schema test = SAMLSchemaBuilder.getSAML11Schema(); - Validator val = test.newValidator(); - DOMSource source = new DOMSource(xmlObject.getDOM()); - val.validate(source); - log.debug("SAML2 Scheme validation successful"); - return; - - } catch (Exception e) { - log.warn("SAML2 scheme validation FAILED.", e); - throw e; - - } - } - - private static XMLObject createAttributeValue(QName attributeValueType, String value) { - XSStringBuilder stringBuilder = (XSStringBuilder) Configuration.getBuilderFactory().getBuilder(XSString.TYPE_NAME); - XSString stringValue = stringBuilder.buildObject(attributeValueType, XSString.TYPE_NAME); - stringValue.setValue(value); - return stringValue; - - } -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/utils/Saml2Utils.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/utils/Saml2Utils.java new file mode 100644 index 00000000..1c7a9652 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/utils/Saml2Utils.java @@ -0,0 +1,247 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.impl.utils; + +import java.io.IOException; +import java.security.NoSuchAlgorithmException; +import java.util.List; +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.dom.DOMSource; +import javax.xml.validation.Schema; +import javax.xml.validation.Validator; +import at.gv.egiz.eaaf.core.impl.utils.Random; +import at.gv.egiz.eaaf.modules.pvp2.PvpConstants; +import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EaafRequestedAttribute; +import org.apache.commons.lang3.StringUtils; +import org.opensaml.common.impl.SecureRandomIdentifierGenerator; +import org.opensaml.common.xml.SAMLSchemaBuilder; +import org.opensaml.saml2.core.Attribute; +import org.opensaml.saml2.core.Status; +import org.opensaml.saml2.core.StatusCode; +import org.opensaml.saml2.metadata.AssertionConsumerService; +import org.opensaml.saml2.metadata.SPSSODescriptor; +import org.opensaml.ws.soap.soap11.Body; +import org.opensaml.ws.soap.soap11.Envelope; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.XMLObjectBuilderFactory; +import org.opensaml.xml.io.Marshaller; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.schema.XSString; +import org.opensaml.xml.schema.impl.XSStringBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; + +public class Saml2Utils { + private static final Logger log = LoggerFactory.getLogger(Saml2Utils.class); + + private static SecureRandomIdentifierGenerator idGenerator; + + private static DocumentBuilder builder; + + static { + final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + + try { + builder = factory.newDocumentBuilder(); + + } catch (final ParserConfigurationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + try { + idGenerator = new SecureRandomIdentifierGenerator(); + + } catch (final NoSuchAlgorithmException e) { + e.printStackTrace(); + + } + } + + /** + * Create a SAML2 object. + * + * @param SAML2 object class + * @param clazz object class + * @return SAML2 object + */ + public static T createSamlObject(final Class clazz) { + try { + final XMLObjectBuilderFactory builderFactory = + org.opensaml.xml.Configuration.getBuilderFactory(); + + final QName defaultElementName = + (QName) clazz.getDeclaredField("DEFAULT_ELEMENT_NAME").get(null); + @SuppressWarnings("unchecked") + final T object = + (T) builderFactory.getBuilder(defaultElementName).buildObject(defaultElementName); + return object; + } catch (final Throwable e) { + e.printStackTrace(); + return null; + } + } + + /** + * Get a new SAML2 conform random value. + * + * @return + */ + public static String getSecureIdentifier() { + return "_".concat(Random.nextHexRandom16()); + + } + + + /** + * Transform SAML2 Object to Element. + * + * @param object SAML2 object + * @return Element + * @throws IOException In case of an transformation error + * @throws MarshallingException In case of an transformation error + * @throws TransformerException In case of an transformation error + */ + public static Document asDomDocument(final XMLObject object) + throws IOException, MarshallingException, TransformerException { + final Document document = builder.newDocument(); + final Marshaller out = + org.opensaml.xml.Configuration.getMarshallerFactory().getMarshaller(object); + out.marshall(object, document); + return document; + } + + /** + * Build success status element. + * + * @return + */ + public static Status getSuccessStatus() { + final Status status = Saml2Utils.createSamlObject(Status.class); + final StatusCode statusCode = Saml2Utils.createSamlObject(StatusCode.class); + statusCode.setValue(StatusCode.SUCCESS_URI); + status.setStatusCode(statusCode); + return status; + } + + /** + * Get AssertionConsumerService Index from metadata element. + * + * @param spSsoDescriptor metadata element + * @return + */ + public static int getDefaultAssertionConsumerServiceIndex(final SPSSODescriptor spSsoDescriptor) { + + final List assertionConsumerList = + spSsoDescriptor.getAssertionConsumerServices(); + + for (final AssertionConsumerService el : assertionConsumerList) { + if (el.isDefault()) { + return el.getIndex(); + } + + } + + return 0; + } + + /** + * Build SOAP11 body from SAML2 object. + * + * @param payload SAML2 object + * @return + */ + public static Envelope buildSoap11Envelope(final XMLObject payload) { + final XMLObjectBuilderFactory bf = org.opensaml.xml.Configuration.getBuilderFactory(); + final Envelope envelope = (Envelope) bf.getBuilder(Envelope.DEFAULT_ELEMENT_NAME) + .buildObject(Envelope.DEFAULT_ELEMENT_NAME); + final Body body = + (Body) bf.getBuilder(Body.DEFAULT_ELEMENT_NAME).buildObject(Body.DEFAULT_ELEMENT_NAME); + + body.getUnknownXMLObjects().add(payload); + envelope.setBody(body); + + return envelope; + } + + /** + * Generate EAAF specific requested attribute. + * + * @param attr SAML2 attribute definition + * @param isRequired is-mandatory flag + * @param value Attribute value + * @return + */ + public static EaafRequestedAttribute generateReqAuthnAttributeSimple(final Attribute attr, + final boolean isRequired, final String value) { + final EaafRequestedAttribute requested = + Saml2Utils.createSamlObject(EaafRequestedAttribute.class); + requested.setName(attr.getName()); + requested.setNameFormat(attr.getNameFormat()); + requested.setFriendlyName(attr.getFriendlyName()); + requested.setIsRequired(String.valueOf(isRequired)); + final List attributeValues = requested.getAttributeValues(); + if (StringUtils.isNotEmpty(value)) { + final XMLObject attributeValueForRequest = + createAttributeValue(PvpConstants.EIDAS_REQUESTED_ATTRIBUTE_VALUE_TYPE, value); + attributeValues.add(attributeValueForRequest); + } + return requested; + + } + + /** + * Perform XML schema-validation on SAML2 object. + * + * @param xmlObject SAML2 object + * @throws Exception In case of a validation error + */ + public static void schemeValidation(final XMLObject xmlObject) throws Exception { + try { + final Schema test = SAMLSchemaBuilder.getSAML11Schema(); + final Validator val = test.newValidator(); + final DOMSource source = new DOMSource(xmlObject.getDOM()); + val.validate(source); + log.debug("SAML2 Scheme validation successful"); + return; + + } catch (final Exception e) { + log.warn("SAML2 scheme validation FAILED.", e); + throw e; + + } + } + + private static XMLObject createAttributeValue(final QName attributeValueType, + final String value) { + final XSStringBuilder stringBuilder = (XSStringBuilder) org.opensaml.xml.Configuration + .getBuilderFactory().getBuilder(XSString.TYPE_NAME); + final XSString stringValue = stringBuilder.buildObject(attributeValueType, XSString.TYPE_NAME); + stringValue.setValue(value); + return stringValue; + + } +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/EAAFURICompare.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/EAAFURICompare.java deleted file mode 100644 index 30b7dcf9..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/EAAFURICompare.java +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.validation; - -import org.opensaml.common.binding.decoding.URIComparator; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - -public class EAAFURICompare implements URIComparator { - private static final Logger log = LoggerFactory.getLogger(EAAFURICompare.class); - - private String serviceURL = ""; - - /** - * - * - * @param serviceURL public URL of the PVP S-Profile endpoint - */ - public EAAFURICompare(String serviceURL) { - this.serviceURL = serviceURL; - } - - public boolean compare(String uri1, String uri2) { - if (this.serviceURL.equals(uri1)) - return true; - - else { - log.warn("PVP request destination-endpoint: " + uri1 - + " does not match to IDP endpoint:" + serviceURL); - return false; - - } - } - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/EaafUriCompare.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/EaafUriCompare.java new file mode 100644 index 00000000..fcee2382 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/EaafUriCompare.java @@ -0,0 +1,53 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.impl.validation; + +import org.opensaml.common.binding.decoding.URIComparator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class EaafUriCompare implements URIComparator { + private static final Logger log = LoggerFactory.getLogger(EaafUriCompare.class); + + private String serviceUrl = ""; + + /** + * SAML2 URL comperator. + * + * @param serviceUrl public URL of the PVP S-Profile endpoint + */ + public EaafUriCompare(final String serviceUrl) { + this.serviceUrl = serviceUrl; + } + + @Override + public boolean compare(final String uri1, final String uri2) { + if (this.serviceUrl.equals(uri1)) { + return true; + } else { + log.warn("PVP request destination-endpoint: " + uri1 + " does not match to IDP endpoint:" + + serviceUrl); + return false; + + } + } + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/TrustEngineFactory.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/TrustEngineFactory.java index 18ee5797..d8ae95a0 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/TrustEngineFactory.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/TrustEngineFactory.java @@ -1,34 +1,26 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.impl.validation; import java.util.ArrayList; import java.util.List; - import org.opensaml.saml2.metadata.provider.MetadataProvider; import org.opensaml.security.MetadataCredentialResolver; import org.opensaml.xml.security.keyinfo.BasicProviderKeyInfoCredentialResolver; @@ -42,24 +34,31 @@ import org.opensaml.xml.signature.impl.ExplicitKeySignatureTrustEngine; public class TrustEngineFactory { - public static SignatureTrustEngine getSignatureKnownKeysTrustEngine(MetadataProvider provider) { - MetadataCredentialResolver resolver; + /** + * Get OpenSAML2 TrustEngine. + * + * @param provider Metadata provider + * @return + */ + public static SignatureTrustEngine getSignatureKnownKeysTrustEngine( + final MetadataProvider provider) { + MetadataCredentialResolver resolver; - resolver = new MetadataCredentialResolver(provider); + resolver = new MetadataCredentialResolver(provider); - List keyInfoProvider = new ArrayList(); - keyInfoProvider.add(new DSAKeyValueProvider()); - keyInfoProvider.add(new RSAKeyValueProvider()); - keyInfoProvider.add(new InlineX509DataProvider()); + final List keyInfoProvider = new ArrayList<>(); + keyInfoProvider.add(new DSAKeyValueProvider()); + keyInfoProvider.add(new RSAKeyValueProvider()); + keyInfoProvider.add(new InlineX509DataProvider()); - KeyInfoCredentialResolver keyInfoResolver = new BasicProviderKeyInfoCredentialResolver( - keyInfoProvider); + final KeyInfoCredentialResolver keyInfoResolver = + new BasicProviderKeyInfoCredentialResolver(keyInfoProvider); - ExplicitKeySignatureTrustEngine engine = new ExplicitKeySignatureTrustEngine( - resolver, keyInfoResolver); + final ExplicitKeySignatureTrustEngine engine = + new ExplicitKeySignatureTrustEngine(resolver, keyInfoResolver); - return engine; + return engine; - } + } } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/metadata/AbstractMetadataSignatureFilter.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/metadata/AbstractMetadataSignatureFilter.java index 424c4431..40cbdeb0 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/metadata/AbstractMetadataSignatureFilter.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/metadata/AbstractMetadataSignatureFilter.java @@ -1,35 +1,30 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.impl.validation.metadata; import java.util.ArrayList; import java.util.Iterator; import java.util.List; - +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2MetadataException; +import at.gv.egiz.eaaf.modules.pvp2.exception.SignatureValidationException; import org.opensaml.saml2.metadata.EntitiesDescriptor; import org.opensaml.saml2.metadata.EntityDescriptor; import org.opensaml.saml2.metadata.provider.MetadataFilter; @@ -37,118 +32,117 @@ import org.opensaml.xml.XMLObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2MetadataException; -import at.gv.egiz.eaaf.modules.pvp2.exception.SignatureValidationException; - public abstract class AbstractMetadataSignatureFilter implements MetadataFilter { - private static final Logger log = LoggerFactory.getLogger(AbstractMetadataSignatureFilter.class); - - public void doFilter(XMLObject metadata) throws SignatureValidationException { - try { - if (metadata instanceof EntitiesDescriptor) { - EntitiesDescriptor entitiesDescriptor = (EntitiesDescriptor) metadata; - if(entitiesDescriptor.getSignature() == null) { - throw new PVP2MetadataException("pvp2.26", - new Object[] {"Root element of metadata file has to be signed"}); - } - processEntitiesDescriptor(entitiesDescriptor); - - - if (entitiesDescriptor.getEntityDescriptors().size() == 0) { - throw new PVP2MetadataException("pvp2.26", - new Object[] {"No valid entity in metadata " + entitiesDescriptor.getName()}); - } - - - } else if (metadata instanceof EntityDescriptor) { - EntityDescriptor entityDescriptor = (EntityDescriptor) metadata; - processEntityDescriptorr(entityDescriptor); - - } else - throw new PVP2MetadataException("pvp2.26", - new Object[] {"Invalid Metadata file Root element is unknown"}); - - - - log.info("Metadata signature policy check done OK"); - } catch (EAAFException e) { - log.warn("Metadata signature policy check FAILED.", e); - throw new SignatureValidationException(e); - - } - } - - /** - * Signature verification of a SAML2 EntityDescriptor element - * - * @param desc - * @throws PVP2MetadataException if the signature is not valid or can not verified - */ - protected abstract void verify(EntityDescriptor desc) throws PVP2MetadataException; - - /** - * Signature verification of a SAML2 EntitiesDescriptor element - * - * @param desc - * @throws PVP2MetadataException if the signature is not valid or can not verified - */ - protected abstract void verify(EntitiesDescriptor desc) throws PVP2MetadataException; - - /** - * Verify a EntityDescriptor element of an EntitiesDescriptor - * - * @param entity EntityDescriptor to verify - * @param desc Full EntitiesDescriptor that contains the EntityDescriptor - * @throws PVP2MetadataException - */ - protected abstract void verify(EntityDescriptor entity, EntitiesDescriptor desc) throws PVP2MetadataException; - - - private void processEntityDescriptorr(EntityDescriptor desc) throws EAAFException { - verify(desc); - - } - - private void processEntitiesDescriptor(EntitiesDescriptor desc) throws EAAFException { - Iterator entID = desc.getEntitiesDescriptors().iterator(); - - if(desc.getSignature() != null) { - verify(desc); - - } - - while(entID.hasNext()) { - processEntitiesDescriptor(entID.next()); - } - - Iterator entIT = desc.getEntityDescriptors().iterator(); - List verifiedEntIT = new ArrayList(); - - //check every Entity - while(entIT.hasNext()) { - EntityDescriptor entity = entIT.next(); - log.debug("Validate metadata for entityID: " + entity.getEntityID() + " ..... "); - try { - verify(entity, desc); - - //add entity to verified entity-list - verifiedEntIT.add(entity); - log.debug("Metadata for entityID: " + entity.getEntityID() + " valid"); - - - } catch (Exception e) { - //remove entity of signature can not be verified. - log.info("Entity " + entity.getEntityID() + " is removed from metadata " - + desc.getName() + ". Entity verification error: " + e.getMessage()); - - } - - } - - //set only verified entity elements - desc.getEntityDescriptors().clear(); - desc.getEntityDescriptors().addAll(verifiedEntIT); - } + private static final Logger log = LoggerFactory.getLogger(AbstractMetadataSignatureFilter.class); + + @Override + public void doFilter(final XMLObject metadata) throws SignatureValidationException { + try { + if (metadata instanceof EntitiesDescriptor) { + final EntitiesDescriptor entitiesDescriptor = (EntitiesDescriptor) metadata; + if (entitiesDescriptor.getSignature() == null) { + throw new Pvp2MetadataException("pvp2.26", + new Object[] {"Root element of metadata file has to be signed"}); + } + processEntitiesDescriptor(entitiesDescriptor); + + + if (entitiesDescriptor.getEntityDescriptors().size() == 0) { + throw new Pvp2MetadataException("pvp2.26", + new Object[] {"No valid entity in metadata " + entitiesDescriptor.getName()}); + } + + + } else if (metadata instanceof EntityDescriptor) { + final EntityDescriptor entityDescriptor = (EntityDescriptor) metadata; + processEntityDescriptorr(entityDescriptor); + + } else { + throw new Pvp2MetadataException("pvp2.26", + new Object[] {"Invalid Metadata file Root element is unknown"}); + } + + + + log.info("Metadata signature policy check done OK"); + } catch (final EaafException e) { + log.warn("Metadata signature policy check FAILED.", e); + throw new SignatureValidationException(e); + + } + } + + /** + * Signature verification of a SAML2 EntityDescriptor element. + * + * @param desc EntityDescriptor + * @throws Pvp2MetadataException if the signature is not valid or can not verified + */ + protected abstract void verify(EntityDescriptor desc) throws Pvp2MetadataException; + + /** + * Signature verification of a SAML2 EntitiesDescriptor element. + * + * @param desc EntitiesDescriptor + * @throws Pvp2MetadataException if the signature is not valid or can not verified + */ + protected abstract void verify(EntitiesDescriptor desc) throws Pvp2MetadataException; + + /** + * Verify a EntityDescriptor element of an EntitiesDescriptor. + * + * @param entity EntityDescriptor to verify + * @param desc Full EntitiesDescriptor that contains the EntityDescriptor + * @throws Pvp2MetadataException In case of an verification error + */ + protected abstract void verify(EntityDescriptor entity, EntitiesDescriptor desc) + throws Pvp2MetadataException; + + + private void processEntityDescriptorr(final EntityDescriptor desc) throws EaafException { + verify(desc); + + } + + private void processEntitiesDescriptor(final EntitiesDescriptor desc) throws EaafException { + final Iterator entID = desc.getEntitiesDescriptors().iterator(); + + if (desc.getSignature() != null) { + verify(desc); + + } + + while (entID.hasNext()) { + processEntitiesDescriptor(entID.next()); + } + + final Iterator entIT = desc.getEntityDescriptors().iterator(); + final List verifiedEntIT = new ArrayList<>(); + + // check every Entity + while (entIT.hasNext()) { + final EntityDescriptor entity = entIT.next(); + log.debug("Validate metadata for entityID: " + entity.getEntityID() + " ..... "); + try { + verify(entity, desc); + + // add entity to verified entity-list + verifiedEntIT.add(entity); + log.debug("Metadata for entityID: " + entity.getEntityID() + " valid"); + + + } catch (final Exception e) { + // remove entity of signature can not be verified. + log.info("Entity " + entity.getEntityID() + " is removed from metadata " + desc.getName() + + ". Entity verification error: " + e.getMessage()); + + } + + } + + // set only verified entity elements + desc.getEntityDescriptors().clear(); + desc.getEntityDescriptors().addAll(verifiedEntIT); + } } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/metadata/PVPEntityCategoryFilter.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/metadata/PVPEntityCategoryFilter.java deleted file mode 100644 index 87ab31fb..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/metadata/PVPEntityCategoryFilter.java +++ /dev/null @@ -1,236 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.validation.metadata; - -import java.util.ArrayList; -import java.util.List; - -import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.saml2.common.Extensions; -import org.opensaml.saml2.core.Attribute; -import org.opensaml.saml2.metadata.AttributeConsumingService; -import org.opensaml.saml2.metadata.EntitiesDescriptor; -import org.opensaml.saml2.metadata.EntityDescriptor; -import org.opensaml.saml2.metadata.LocalizedString; -import org.opensaml.saml2.metadata.RequestedAttribute; -import org.opensaml.saml2.metadata.SPSSODescriptor; -import org.opensaml.saml2.metadata.ServiceName; -import org.opensaml.saml2.metadata.provider.FilterException; -import org.opensaml.saml2.metadata.provider.MetadataFilter; -import org.opensaml.samlext.saml2mdattr.EntityAttributes; -import org.opensaml.xml.XMLObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import at.gv.egiz.eaaf.core.impl.data.Trible; -import at.gv.egiz.eaaf.modules.pvp2.PVPConstants; -import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2MetadataException; -import at.gv.egiz.eaaf.modules.pvp2.impl.builder.PVPAttributeBuilder; -import at.gv.egiz.eaaf.modules.pvp2.impl.utils.SAML2Utils; - -/** - * @author tlenz - * - */ -public class PVPEntityCategoryFilter implements MetadataFilter { - private static final Logger log = LoggerFactory.getLogger(PVPEntityCategoryFilter.class); - - private boolean isUsed = false; - - /** - * Filter to map PVP EntityCategories into a set of single PVP attributes - * - * @param isUsed if true PVP EntityCategories are mapped, otherwise they are ignored - * - */ - public PVPEntityCategoryFilter(boolean isUsed) { - this.isUsed = isUsed; - } - - - /* (non-Javadoc) - * @see org.opensaml.saml2.metadata.provider.MetadataFilter#doFilter(org.opensaml.xml.XMLObject) - */ - @Override - public void doFilter(XMLObject metadata) throws FilterException { - - if (isUsed) { - log.trace("Map PVP EntityCategory to single PVP Attributes ... "); - String entityId = null; - try { - if (metadata instanceof EntitiesDescriptor) { - log.trace("Find EnitiesDescriptor ... "); - EntitiesDescriptor entitiesDesc = (EntitiesDescriptor) metadata; - if (entitiesDesc.getEntityDescriptors() != null) { - for (EntityDescriptor el : entitiesDesc.getEntityDescriptors()) - resolveEntityCategoriesToAttributes(el); - - } - - } else if (metadata instanceof EntityDescriptor) { - log.trace("Find EntityDescriptor"); - resolveEntityCategoriesToAttributes((EntityDescriptor)metadata); - - - } else - throw new PVP2MetadataException("pvp2.26", - new Object[] {"Invalid Metadata file Root element is no Entities- or EntityDescriptor"}); - - - - } catch (Exception e) { - log.warn("SAML2 Metadata processing FAILED: Can not resolve EntityCategories for metadata: " + entityId, e); - - } - - } else - log.trace("Filter to map PVP EntityCategory to single PVP Attributes is deactivated"); - - } - - private void resolveEntityCategoriesToAttributes(EntityDescriptor metadata) { - log.debug("Resolving EntityCategorie for Entity: " + metadata.getEntityID() + " ..."); - Extensions extensions = metadata.getExtensions(); - if (extensions != null) { - List listOfExt = extensions.getUnknownXMLObjects(); - if (listOfExt != null && !listOfExt.isEmpty()) { - log.trace("Find #" + listOfExt.size() + " 'Extension' elements "); - for (XMLObject el : listOfExt) { - log.trace("Find ExtensionElement: " + el.getElementQName().toString()); - if (el instanceof EntityAttributes) { - EntityAttributes entityAttrElem = (EntityAttributes)el; - if (entityAttrElem.getAttributes() != null) { - log.trace("Find EntityAttributes. Start attribute processing ..."); - for (Attribute entityAttr : entityAttrElem.getAttributes()) { - if (entityAttr.getName().equals(PVPConstants.ENTITY_CATEGORY_ATTRIBITE)) { - if (!entityAttr.getAttributeValues().isEmpty()) { - String entityAttrValue = entityAttr.getAttributeValues().get(0).getDOM().getTextContent(); - if (PVPConstants.EGOVTOKEN.equals(entityAttrValue)) { - log.debug("Find 'EGOVTOKEN' EntityAttribute. Adding single pvp attributes ... "); - addAttributesToEntityDescriptor(metadata, - buildAttributeList(PVPConstants.EGOVTOKEN_PVP_ATTRIBUTES), - entityAttrValue); - - - } else if (PVPConstants.CITIZENTOKEN.equals(entityAttrValue)) { - log.debug("Find 'CITIZENTOKEN' EntityAttribute. Adding single pvp attributes ... "); - addAttributesToEntityDescriptor(metadata, - buildAttributeList(PVPConstants.CITIZENTOKEN_PVP_ATTRIBUTES), - entityAttrValue); - - } else - log.info("EntityAttributeValue: " + entityAttrValue + " is UNKNOWN!"); - - } else - log.info("EntityAttribute: No attribute value"); - - } else - log.info("EntityAttribute: " + entityAttr.getName() + " is NOT supported"); - - } - - } else - log.info("Can NOT resolve EntityAttributes! Reason: Only EntityAttributes are supported!"); - - } - } - - } else - log.trace("'Extension' element is 'null' or empty"); - - } else - log.trace("No 'Extension' element found"); - - } - - /** - * @param metadata - * @param attrList - */ - private void addAttributesToEntityDescriptor(EntityDescriptor metadata, List attrList, String entityAttr) { - SPSSODescriptor spSSODesc = metadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS); - if (spSSODesc != null) { - if (spSSODesc.getAttributeConsumingServices() == null || - spSSODesc.getAttributeConsumingServices().isEmpty()) { - log.trace("No 'AttributeConsumingServices' found. Added it ..."); - - AttributeConsumingService attributeService = SAML2Utils.createSAMLObject(AttributeConsumingService.class); - attributeService.setIndex(0); - attributeService.setIsDefault(true); - ServiceName serviceName = SAML2Utils.createSAMLObject(ServiceName.class); - serviceName.setName(new LocalizedString("Default Service", "en")); - attributeService.getNames().add(serviceName); - - if (attrList != null && !attrList.isEmpty()) { - attributeService.getRequestAttributes().addAll(attrList); - log.info("Add " + attrList.size() + " attributes for 'EntityAttribute': " + entityAttr); - - } - - spSSODesc.getAttributeConsumingServices().add(attributeService); - - } else { - log.debug("Find 'AttributeConsumingServices'. Starting updating process ... "); - for (AttributeConsumingService el : spSSODesc.getAttributeConsumingServices()) { - log.debug("Update 'AttributeConsumingService' with Index: " + el.getIndex()); - - //load currently requested attributes - List currentlyReqAttr = new ArrayList(); - for (RequestedAttribute reqAttr : el.getRequestAttributes()) - currentlyReqAttr.add(reqAttr.getName()); - - - //check against EntityAttribute List - for (RequestedAttribute entityAttrListEl : attrList) { - if (!currentlyReqAttr.contains(entityAttrListEl.getName())) { - el.getRequestAttributes().add(entityAttrListEl); - - } else - log.debug("'AttributeConsumingService' already contains attr: " + entityAttrListEl.getName()); - - } - - } - - } - - } else - log.info("Can ONLY add 'EntityAttributes' to 'SPSSODescriptor'"); - - } - - private List buildAttributeList(List> attrSet) { - List requestedAttributes = new ArrayList(); - for (Trible el : attrSet) - requestedAttributes.add(PVPAttributeBuilder.buildReqAttribute(el.getFirst(), el.getSecond(), el.getThird())); - - return requestedAttributes; - - - } - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/metadata/PvpEntityCategoryFilter.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/metadata/PvpEntityCategoryFilter.java new file mode 100644 index 00000000..2d81b1f8 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/metadata/PvpEntityCategoryFilter.java @@ -0,0 +1,251 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.impl.validation.metadata; + +import java.util.ArrayList; +import java.util.List; +import at.gv.egiz.eaaf.core.impl.data.Trible; +import at.gv.egiz.eaaf.modules.pvp2.PvpConstants; +import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2MetadataException; +import at.gv.egiz.eaaf.modules.pvp2.impl.builder.PvpAttributeBuilder; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.Saml2Utils; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.saml2.core.Attribute; +import org.opensaml.saml2.metadata.AttributeConsumingService; +import org.opensaml.saml2.metadata.EntitiesDescriptor; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.LocalizedString; +import org.opensaml.saml2.metadata.RequestedAttribute; +import org.opensaml.saml2.metadata.SPSSODescriptor; +import org.opensaml.saml2.metadata.ServiceName; +import org.opensaml.saml2.metadata.provider.FilterException; +import org.opensaml.saml2.metadata.provider.MetadataFilter; +import org.opensaml.samlext.saml2mdattr.EntityAttributes; +import org.opensaml.xml.XMLObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Metadata filter that inject requested attributes based on Metadata EntityCategories. + * + * @author tlenz + * + */ +public class PvpEntityCategoryFilter implements MetadataFilter { + private static final Logger log = LoggerFactory.getLogger(PvpEntityCategoryFilter.class); + + private boolean isUsed = false; + + /** + * Filter to map PVP EntityCategories into a set of single PVP attributes. + * + * @param isUsed if true PVP EntityCategories are mapped, otherwise they are ignored + * + */ + public PvpEntityCategoryFilter(final boolean isUsed) { + this.isUsed = isUsed; + } + + + /* + * (non-Javadoc) + * + * @see org.opensaml.saml2.metadata.provider.MetadataFilter#doFilter(org.opensaml.xml.XMLObject) + */ + @Override + public void doFilter(final XMLObject metadata) throws FilterException { + + if (isUsed) { + log.trace("Map PVP EntityCategory to single PVP Attributes ... "); + final String entityId = null; + try { + if (metadata instanceof EntitiesDescriptor) { + log.trace("Find EnitiesDescriptor ... "); + final EntitiesDescriptor entitiesDesc = (EntitiesDescriptor) metadata; + if (entitiesDesc.getEntityDescriptors() != null) { + for (final EntityDescriptor el : entitiesDesc.getEntityDescriptors()) { + resolveEntityCategoriesToAttributes(el); + } + + } + + } else if (metadata instanceof EntityDescriptor) { + log.trace("Find EntityDescriptor"); + resolveEntityCategoriesToAttributes((EntityDescriptor) metadata); + + + } else { + throw new Pvp2MetadataException("pvp2.26", new Object[] { + "Invalid Metadata file Root element is no Entities- or EntityDescriptor"}); + } + + + + } catch (final Exception e) { + log.warn("SAML2 Metadata processing FAILED: Can not resolve EntityCategories for metadata: " + + entityId, e); + + } + + } else { + log.trace("Filter to map PVP EntityCategory to single PVP Attributes is deactivated"); + } + + } + + private void resolveEntityCategoriesToAttributes(final EntityDescriptor metadata) { + log.debug("Resolving EntityCategorie for Entity: " + metadata.getEntityID() + " ..."); + final Extensions extensions = metadata.getExtensions(); + if (extensions != null) { + final List listOfExt = extensions.getUnknownXMLObjects(); + if (listOfExt != null && !listOfExt.isEmpty()) { + log.trace("Find #" + listOfExt.size() + " 'Extension' elements "); + for (final XMLObject el : listOfExt) { + log.trace("Find ExtensionElement: " + el.getElementQName().toString()); + if (el instanceof EntityAttributes) { + final EntityAttributes entityAttrElem = (EntityAttributes) el; + if (entityAttrElem.getAttributes() != null) { + log.trace("Find EntityAttributes. Start attribute processing ..."); + for (final Attribute entityAttr : entityAttrElem.getAttributes()) { + if (entityAttr.getName().equals(PvpConstants.ENTITY_CATEGORY_ATTRIBITE)) { + if (!entityAttr.getAttributeValues().isEmpty()) { + final String entityAttrValue = + entityAttr.getAttributeValues().get(0).getDOM().getTextContent(); + if (PvpConstants.EGOVTOKEN.equals(entityAttrValue)) { + log.debug( + "Find 'EGOVTOKEN' EntityAttribute. Adding single pvp attributes ... "); + addAttributesToEntityDescriptor(metadata, + buildAttributeList(PvpConstants.EGOVTOKEN_PVP_ATTRIBUTES), + entityAttrValue); + + + } else if (PvpConstants.CITIZENTOKEN.equals(entityAttrValue)) { + log.debug( + "Find 'CITIZENTOKEN' EntityAttribute. Adding single pvp attributes ... "); + addAttributesToEntityDescriptor(metadata, + buildAttributeList(PvpConstants.CITIZENTOKEN_PVP_ATTRIBUTES), + entityAttrValue); + + } else { + log.info("EntityAttributeValue: " + entityAttrValue + " is UNKNOWN!"); + } + + } else { + log.info("EntityAttribute: No attribute value"); + } + + } else { + log.info("EntityAttribute: " + entityAttr.getName() + " is NOT supported"); + } + + } + + } else { + log.info( + "Can NOT resolve EntityAttributes! Reason: Only EntityAttributes are supported!"); + } + + } + } + + } else { + log.trace("'Extension' element is 'null' or empty"); + } + + } else { + log.trace("No 'Extension' element found"); + } + + } + + + private void addAttributesToEntityDescriptor(final EntityDescriptor metadata, + final List attrList, final String entityAttr) { + final SPSSODescriptor spSsoDesc = metadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS); + if (spSsoDesc != null) { + if (spSsoDesc.getAttributeConsumingServices() == null + || spSsoDesc.getAttributeConsumingServices().isEmpty()) { + log.trace("No 'AttributeConsumingServices' found. Added it ..."); + + final AttributeConsumingService attributeService = + Saml2Utils.createSamlObject(AttributeConsumingService.class); + attributeService.setIndex(0); + attributeService.setIsDefault(true); + final ServiceName serviceName = Saml2Utils.createSamlObject(ServiceName.class); + serviceName.setName(new LocalizedString("Default Service", "en")); + attributeService.getNames().add(serviceName); + + if (attrList != null && !attrList.isEmpty()) { + attributeService.getRequestAttributes().addAll(attrList); + log.info("Add " + attrList.size() + " attributes for 'EntityAttribute': " + entityAttr); + + } + + spSsoDesc.getAttributeConsumingServices().add(attributeService); + + } else { + log.debug("Find 'AttributeConsumingServices'. Starting updating process ... "); + for (final AttributeConsumingService el : spSsoDesc.getAttributeConsumingServices()) { + log.debug("Update 'AttributeConsumingService' with Index: " + el.getIndex()); + + // load currently requested attributes + final List currentlyReqAttr = new ArrayList<>(); + for (final RequestedAttribute reqAttr : el.getRequestAttributes()) { + currentlyReqAttr.add(reqAttr.getName()); + } + + + // check against EntityAttribute List + for (final RequestedAttribute entityAttrListEl : attrList) { + if (!currentlyReqAttr.contains(entityAttrListEl.getName())) { + el.getRequestAttributes().add(entityAttrListEl); + + } else { + log.debug("'AttributeConsumingService' already contains attr: " + + entityAttrListEl.getName()); + } + + } + + } + + } + + } else { + log.info("Can ONLY add 'EntityAttributes' to 'SPSSODescriptor'"); + } + + } + + private List buildAttributeList( + final List> attrSet) { + final List requestedAttributes = new ArrayList<>(); + for (final Trible el : attrSet) { + requestedAttributes + .add(PvpAttributeBuilder.buildReqAttribute(el.getFirst(), el.getSecond(), el.getThird())); + } + + return requestedAttributes; + + + } + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/metadata/SchemaValidationFilter.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/metadata/SchemaValidationFilter.java index b5de4b21..3ff78ca8 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/metadata/SchemaValidationFilter.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/validation/metadata/SchemaValidationFilter.java @@ -1,35 +1,28 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.impl.validation.metadata; import javax.xml.transform.dom.DOMSource; import javax.xml.validation.Schema; import javax.xml.validation.Validator; - +import at.gv.egiz.eaaf.modules.pvp2.exception.SchemaValidationException; import org.opensaml.common.xml.SAMLSchemaBuilder; import org.opensaml.saml2.metadata.provider.FilterException; import org.opensaml.saml2.metadata.provider.MetadataFilter; @@ -38,69 +31,65 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.SAXException; -import at.gv.egiz.eaaf.modules.pvp2.exception.SchemaValidationException; - -/** - * @author tlenz - * - */ public class SchemaValidationFilter implements MetadataFilter { - private static final Logger log = LoggerFactory.getLogger(SchemaValidationFilter.class); - private boolean isActive = true; - - public SchemaValidationFilter() { - } - - /** - * - */ - public SchemaValidationFilter(boolean useSchemaValidation) { - this.isActive = useSchemaValidation; - } - - - /* (non-Javadoc) - * @see org.opensaml.saml2.metadata.provider.MetadataFilter#doFilter(org.opensaml.xml.XMLObject) - */ - @Override - public void doFilter(XMLObject arg0) throws FilterException { - - String errString = null; - - if (isActive) { - try { - Schema test = SAMLSchemaBuilder.getSAML11Schema(); - Validator val = test.newValidator(); - DOMSource source = new DOMSource(arg0.getDOM()); - val.validate(source); - log.info("Metadata Schema validation check done OK"); - return; - - } catch (SAXException e) { - if (log.isDebugEnabled() || log.isTraceEnabled()) - log.warn("Metadata Schema validation FAILED with exception:", e); - else - log.warn("Metadata Schema validation FAILED with message: "+ e.getMessage()); - - errString = e.getMessage(); - - } catch (Exception e) { - if (log.isDebugEnabled() || log.isTraceEnabled()) - log.warn("Metadata Schema validation FAILED with exception:", e); - else - log.warn("Metadata Schema validation FAILED with message: "+ e.getMessage()); - - errString = e.getMessage(); - - } - - throw new FilterException( - new SchemaValidationException("pvp2.26", - new Object[] {"Metadata Schema validation FAILED with message: " + errString})); - - } else - log.info("Metadata Schema validation check is DEACTIVATED!"); - - } + private static final Logger log = LoggerFactory.getLogger(SchemaValidationFilter.class); + private boolean isActive = true; + + public SchemaValidationFilter() { + + } + + public SchemaValidationFilter(final boolean useSchemaValidation) { + this.isActive = useSchemaValidation; + } + + + /* + * (non-Javadoc) + * + * @see org.opensaml.saml2.metadata.provider.MetadataFilter#doFilter(org.opensaml.xml.XMLObject) + */ + @Override + public void doFilter(final XMLObject arg0) throws FilterException { + + String errString = null; + + if (isActive) { + try { + final Schema test = SAMLSchemaBuilder.getSAML11Schema(); + final Validator val = test.newValidator(); + final DOMSource source = new DOMSource(arg0.getDOM()); + val.validate(source); + log.info("Metadata Schema validation check done OK"); + return; + + } catch (final SAXException e) { + if (log.isDebugEnabled() || log.isTraceEnabled()) { + log.warn("Metadata Schema validation FAILED with exception:", e); + } else { + log.warn("Metadata Schema validation FAILED with message: " + e.getMessage()); + } + + errString = e.getMessage(); + + } catch (final Exception e) { + if (log.isDebugEnabled() || log.isTraceEnabled()) { + log.warn("Metadata Schema validation FAILED with exception:", e); + } else { + log.warn("Metadata Schema validation FAILED with message: " + e.getMessage()); + } + + errString = e.getMessage(); + + } + + throw new FilterException(new SchemaValidationException("pvp2.26", + new Object[] {"Metadata Schema validation FAILED with message: " + errString})); + + } else { + log.info("Metadata Schema validation check is DEACTIVATED!"); + } + + } } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/AbstractRequestSignedSecurityPolicyRule.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/AbstractRequestSignedSecurityPolicyRule.java index f1dd1269..fc1b6ea8 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/AbstractRequestSignedSecurityPolicyRule.java +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/AbstractRequestSignedSecurityPolicyRule.java @@ -1,36 +1,29 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.impl.verification; import javax.xml.namespace.QName; import javax.xml.transform.dom.DOMSource; import javax.xml.validation.Schema; import javax.xml.validation.Validator; - +import at.gv.egiz.eaaf.modules.pvp2.exception.SchemaValidationException; import org.apache.commons.lang3.StringUtils; import org.opensaml.common.SignableSAMLObject; import org.opensaml.common.xml.SAMLConstants; @@ -52,144 +45,154 @@ import org.slf4j.LoggerFactory; import org.w3c.dom.Element; import org.xml.sax.SAXException; -import at.gv.egiz.eaaf.modules.pvp2.exception.SchemaValidationException; - /** + * Signature Policy for SAML2 redirect-binding. + * * @author tlenz * */ public abstract class AbstractRequestSignedSecurityPolicyRule implements SecurityPolicyRule { - private static final Logger log = LoggerFactory.getLogger(AbstractRequestSignedSecurityPolicyRule.class); - - - private SignatureTrustEngine trustEngine = null; - private QName peerEntityRole = null; - /** - * @param peerEntityRole - * - */ - public AbstractRequestSignedSecurityPolicyRule(SignatureTrustEngine trustEngine, QName peerEntityRole) { - this.trustEngine = trustEngine; - this.peerEntityRole = peerEntityRole; - - } - - - /** - * Reload the PVP metadata for a given entity - * - * @param entityID for which the metadata should be refreshed. - * @return true if the refresh was successful, otherwise false - */ - protected abstract boolean refreshMetadataProvider(String entityID); - - - protected abstract SignableSAMLObject getSignedSAMLObject(XMLObject inboundData); - - /* (non-Javadoc) - * @see org.opensaml.ws.security.SecurityPolicyRule#evaluate(org.opensaml.ws.message.MessageContext) - */ - @Override - public void evaluate(MessageContext context) throws SecurityPolicyException { - try { - verifySignature(context); - - } catch (SecurityPolicyException e) { - if (StringUtils.isEmpty(context.getInboundMessageIssuer())) { - throw e; - - } - log.debug("PVP2X message validation FAILED. Reload metadata for entityID: " + context.getInboundMessageIssuer()); - if (!refreshMetadataProvider(context.getInboundMessageIssuer())) - throw e; - - else { - log.trace("PVP2X metadata reload finished. Check validate message again."); - verifySignature(context); - - } - log.trace("Second PVP2X message validation finished"); - - } - - - } - - private void verifySignature(MessageContext context) throws SecurityPolicyException { - SignableSAMLObject samlObj = getSignedSAMLObject(context.getInboundMessage()); - if (samlObj != null && samlObj.getSignature() != null) { - - SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); - try { - profileValidator.validate(samlObj.getSignature()); - performSchemaValidation(samlObj.getDOM()); - - } catch (ValidationException e) { - log.warn("Signature is not conform to SAML signature profile", e); - throw new SecurityPolicyException("Signature is not conform to SAML signature profile"); - - } catch (SchemaValidationException e) { - log.warn("Signature is not conform to SAML signature profile", e); - throw new SecurityPolicyException("Signature is not conform to SAML signature profile"); - - } - - - - CriteriaSet criteriaSet = new CriteriaSet(); - criteriaSet.add( new EntityIDCriteria(context.getInboundMessageIssuer()) ); - criteriaSet.add( new MetadataCriteria(peerEntityRole, SAMLConstants.SAML20P_NS) ); - criteriaSet.add( new UsageCriteria(UsageType.SIGNING) ); - - try { - if (!trustEngine.validate(samlObj.getSignature(), criteriaSet)) { - throw new SecurityPolicyException("Signature validation FAILED."); - - } - log.debug("PVP message signature valid."); - - } catch (org.opensaml.xml.security.SecurityException e) { - log.info("PVP2x message signature validation FAILED. Message:" + e.getMessage()); - throw new SecurityPolicyException("Signature validation FAILED."); - - } - - } else { - throw new SecurityPolicyException("PVP Message is not signed."); - - } - - } - - private void performSchemaValidation(Element source) throws SchemaValidationException { - - String err = null; - try { - Schema test = SAMLSchemaBuilder.getSAML11Schema(); - Validator val = test.newValidator(); - val.validate(new DOMSource(source)); - log.debug("Schema validation check done OK"); - return; - - } catch (SAXException e) { - err = e.getMessage(); - if (log.isDebugEnabled() || log.isTraceEnabled()) - log.warn("Schema validation FAILED with exception:", e); - else - log.warn("Schema validation FAILED with message: "+ e.getMessage()); - - } catch (Exception e) { - err = e.getMessage(); - if (log.isDebugEnabled() || log.isTraceEnabled()) - log.warn("Schema validation FAILED with exception:", e); - else - log.warn("Schema validation FAILED with message: "+ e.getMessage()); - - } - - throw new SchemaValidationException("pvp2.22", new Object[]{err}); - - } + private static final Logger log = + LoggerFactory.getLogger(AbstractRequestSignedSecurityPolicyRule.class); + + + private SignatureTrustEngine trustEngine = null; + private QName peerEntityRole = null; + + /** + * Role initializer. + * + * @param peerEntityRole + * + */ + public AbstractRequestSignedSecurityPolicyRule(final SignatureTrustEngine trustEngine, + final QName peerEntityRole) { + this.trustEngine = trustEngine; + this.peerEntityRole = peerEntityRole; + + } + + + /** + * Reload the PVP metadata for a given entity. + * + * @param entityID for which the metadata should be refreshed. + * @return true if the refresh was successful, otherwise false + */ + protected abstract boolean refreshMetadataProvider(String entityID); + + + protected abstract SignableSAMLObject getSignedSamlObject(XMLObject inboundData); + + /* + * (non-Javadoc) + * + * @see + * org.opensaml.ws.security.SecurityPolicyRule#evaluate(org.opensaml.ws.message.MessageContext) + */ + @Override + public void evaluate(final MessageContext context) throws SecurityPolicyException { + try { + verifySignature(context); + + } catch (final SecurityPolicyException e) { + if (StringUtils.isEmpty(context.getInboundMessageIssuer())) { + throw e; + + } + log.debug("PVP2X message validation FAILED. Reload metadata for entityID: " + + context.getInboundMessageIssuer()); + if (!refreshMetadataProvider(context.getInboundMessageIssuer())) { + throw e; + } else { + log.trace("PVP2X metadata reload finished. Check validate message again."); + verifySignature(context); + + } + log.trace("Second PVP2X message validation finished"); + + } + + + } + + private void verifySignature(final MessageContext context) throws SecurityPolicyException { + final SignableSAMLObject samlObj = getSignedSamlObject(context.getInboundMessage()); + if (samlObj != null && samlObj.getSignature() != null) { + + final SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); + try { + profileValidator.validate(samlObj.getSignature()); + performSchemaValidation(samlObj.getDOM()); + + } catch (final ValidationException e) { + log.warn("Signature is not conform to SAML signature profile", e); + throw new SecurityPolicyException("Signature is not conform to SAML signature profile"); + + } catch (final SchemaValidationException e) { + log.warn("Signature is not conform to SAML signature profile", e); + throw new SecurityPolicyException("Signature is not conform to SAML signature profile"); + + } + + + + final CriteriaSet criteriaSet = new CriteriaSet(); + criteriaSet.add(new EntityIDCriteria(context.getInboundMessageIssuer())); + criteriaSet.add(new MetadataCriteria(peerEntityRole, SAMLConstants.SAML20P_NS)); + criteriaSet.add(new UsageCriteria(UsageType.SIGNING)); + + try { + if (!trustEngine.validate(samlObj.getSignature(), criteriaSet)) { + throw new SecurityPolicyException("Signature validation FAILED."); + + } + log.debug("PVP message signature valid."); + + } catch (final org.opensaml.xml.security.SecurityException e) { + log.info("PVP2x message signature validation FAILED. Message:" + e.getMessage()); + throw new SecurityPolicyException("Signature validation FAILED."); + + } + + } else { + throw new SecurityPolicyException("PVP Message is not signed."); + + } + + } + + private void performSchemaValidation(final Element source) throws SchemaValidationException { + + String err = null; + try { + final Schema test = SAMLSchemaBuilder.getSAML11Schema(); + final Validator val = test.newValidator(); + val.validate(new DOMSource(source)); + log.debug("Schema validation check done OK"); + return; + + } catch (final SAXException e) { + err = e.getMessage(); + if (log.isDebugEnabled() || log.isTraceEnabled()) { + log.warn("Schema validation FAILED with exception:", e); + } else { + log.warn("Schema validation FAILED with message: " + e.getMessage()); + } + + } catch (final Exception e) { + err = e.getMessage(); + if (log.isDebugEnabled() || log.isTraceEnabled()) { + log.warn("Schema validation FAILED with exception:", e); + } else { + log.warn("Schema validation FAILED with message: " + e.getMessage()); + } + + } + + throw new SchemaValidationException("pvp2.22", new Object[] {err}); + + } } diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/PVPAuthRequestSignedRole.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/PVPAuthRequestSignedRole.java deleted file mode 100644 index 6d5fdff8..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/PVPAuthRequestSignedRole.java +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.verification; - -import java.util.List; - -import org.opensaml.common.binding.SAMLMessageContext; -import org.opensaml.saml2.binding.security.SAML2AuthnRequestsSignedRule; -import org.opensaml.ws.transport.http.HTTPInTransport; -import org.opensaml.xml.util.DatatypeHelper; - -/** - * @author tlenz - * - */ -public class PVPAuthRequestSignedRole extends SAML2AuthnRequestsSignedRule { - - @Override - protected boolean isMessageSigned(SAMLMessageContext messageContext) { - // This handles HTTP-Redirect and HTTP-POST-SimpleSign bindings. - HTTPInTransport inTransport = (HTTPInTransport) messageContext.getInboundMessageTransport(); - - //Check signature parameter exists only once and is not empty - List sigParam = inTransport.getParameterValues("Signature"); - boolean isValidSigned = sigParam.size() == 1 && !DatatypeHelper.isEmpty(sigParam.get(0)); - - //Check signature-algorithm parameter exists only once and is not empty - List sigAlgParam = inTransport.getParameterValues("SigAlg"); - boolean isValidSigAlgExists = sigAlgParam.size() == 1 && !DatatypeHelper.isEmpty(sigAlgParam.get(0)); - - //Check signature-content parameter exists only once and is not empty - List samlReqParam = inTransport.getParameterValues("SAMLRequest"); - List samlRespParam = inTransport.getParameterValues("SAMLResponse"); - boolean isValidContent = ( ( samlReqParam.size() == 1 && !DatatypeHelper.isEmpty(samlReqParam.get(0)) ) - || ( samlRespParam.size() == 1 && !DatatypeHelper.isEmpty(samlRespParam.get(0)) ) - ) && !(samlReqParam.size() == 1 && samlRespParam.size() == 1) - ; - - return isValidSigned && isValidSigAlgExists && isValidContent; - - } -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/PVPSignedRequestPolicyRule.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/PVPSignedRequestPolicyRule.java deleted file mode 100644 index eecaf4f0..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/PVPSignedRequestPolicyRule.java +++ /dev/null @@ -1,84 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.verification; - -import javax.xml.namespace.QName; - -import org.opensaml.common.SignableSAMLObject; -import org.opensaml.saml2.metadata.provider.MetadataProvider; -import org.opensaml.xml.XMLObject; -import org.opensaml.xml.signature.SignatureTrustEngine; - -import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IRefreshableMetadataProvider; - -/** - * @author tlenz - * - */ -public class PVPSignedRequestPolicyRule extends - AbstractRequestSignedSecurityPolicyRule { - - private IRefreshableMetadataProvider metadataProvider = null; - - /** - * @param metadataProvider - * @param trustEngine - * @param peerEntityRole - */ - public PVPSignedRequestPolicyRule(MetadataProvider metadataProvider, SignatureTrustEngine trustEngine, - QName peerEntityRole) { - super(trustEngine, peerEntityRole); - if (metadataProvider instanceof IRefreshableMetadataProvider) - this.metadataProvider = (IRefreshableMetadataProvider) metadataProvider; - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.validation.AbstractRequestSignedSecurityPolicyRule#refreshMetadataProvider(java.lang.String) - */ - @Override - protected boolean refreshMetadataProvider(String entityID) { - if (metadataProvider != null) - return metadataProvider.refreshMetadataProvider(entityID); - - return false; - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.validation.AbstractRequestSignedSecurityPolicyRule#getSignedSAMLObject(org.opensaml.xml.XMLObject) - */ - @Override - protected SignableSAMLObject getSignedSAMLObject(XMLObject inboundData) { - if (inboundData instanceof SignableSAMLObject) - return (SignableSAMLObject) inboundData; - - else - return null; - } - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/PvpAuthRequestSignedRole.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/PvpAuthRequestSignedRole.java new file mode 100644 index 00000000..4eb711f9 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/PvpAuthRequestSignedRole.java @@ -0,0 +1,56 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.impl.verification; + +import java.util.List; +import org.opensaml.common.binding.SAMLMessageContext; +import org.opensaml.saml2.binding.security.SAML2AuthnRequestsSignedRule; +import org.opensaml.ws.transport.http.HTTPInTransport; +import org.opensaml.xml.util.DatatypeHelper; + +public class PvpAuthRequestSignedRole extends SAML2AuthnRequestsSignedRule { + + @Override + protected boolean isMessageSigned(final SAMLMessageContext messageContext) { + // This handles HTTP-Redirect and HTTP-POST-SimpleSign bindings. + final HTTPInTransport inTransport = + (HTTPInTransport) messageContext.getInboundMessageTransport(); + + // Check signature parameter exists only once and is not empty + final List sigParam = inTransport.getParameterValues("Signature"); + final boolean isValidSigned = sigParam.size() == 1 && !DatatypeHelper.isEmpty(sigParam.get(0)); + + // Check signature-algorithm parameter exists only once and is not empty + final List sigAlgParam = inTransport.getParameterValues("SigAlg"); + final boolean isValidSigAlgExists = + sigAlgParam.size() == 1 && !DatatypeHelper.isEmpty(sigAlgParam.get(0)); + + // Check signature-content parameter exists only once and is not empty + final List samlReqParam = inTransport.getParameterValues("SAMLRequest"); + final List samlRespParam = inTransport.getParameterValues("SAMLResponse"); + final boolean isValidContent = + ((samlReqParam.size() == 1 && !DatatypeHelper.isEmpty(samlReqParam.get(0))) + || (samlRespParam.size() == 1 && !DatatypeHelper.isEmpty(samlRespParam.get(0)))) + && !(samlReqParam.size() == 1 && samlRespParam.size() == 1); + + return isValidSigned && isValidSigAlgExists && isValidContent; + + } +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/PvpSignedRequestPolicyRule.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/PvpSignedRequestPolicyRule.java new file mode 100644 index 00000000..0d108596 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/PvpSignedRequestPolicyRule.java @@ -0,0 +1,82 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.impl.verification; + +import javax.xml.namespace.QName; +import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IRefreshableMetadataProvider; +import org.opensaml.common.SignableSAMLObject; +import org.opensaml.saml2.metadata.provider.MetadataProvider; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.signature.SignatureTrustEngine; + +public class PvpSignedRequestPolicyRule extends AbstractRequestSignedSecurityPolicyRule { + + private IRefreshableMetadataProvider metadataProvider = null; + + /** + * EAAF specific signature rule for OpenSAML2 redirect-binding. + * + * @param metadataProvider SAML2 metadata provider + * @param trustEngine SAML2 TrustEngine + * @param peerEntityRole Role of the Entity + */ + public PvpSignedRequestPolicyRule(final MetadataProvider metadataProvider, + final SignatureTrustEngine trustEngine, final QName peerEntityRole) { + super(trustEngine, peerEntityRole); + if (metadataProvider instanceof IRefreshableMetadataProvider) { + this.metadataProvider = (IRefreshableMetadataProvider) metadataProvider; + } + + } + + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.protocols.pvp2x.validation.AbstractRequestSignedSecurityPolicyRule# + * refreshMetadataProvider(java.lang.String) + */ + @Override + protected boolean refreshMetadataProvider(final String entityID) { + if (metadataProvider != null) { + return metadataProvider.refreshMetadataProvider(entityID); + } + + return false; + + } + + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.protocols.pvp2x.validation.AbstractRequestSignedSecurityPolicyRule# + * getSignedSAMLObject(org.opensaml.xml.XMLObject) + */ + @Override + protected SignableSAMLObject getSignedSamlObject(final XMLObject inboundData) { + if (inboundData instanceof SignableSAMLObject) { + return (SignableSAMLObject) inboundData; + } else { + return null; + } + } + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/SAMLVerificationEngine.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/SAMLVerificationEngine.java deleted file mode 100644 index 078e4ac0..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/SAMLVerificationEngine.java +++ /dev/null @@ -1,207 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.verification; - -import javax.xml.namespace.QName; -import javax.xml.transform.dom.DOMSource; -import javax.xml.validation.Schema; -import javax.xml.validation.Validator; - -import org.apache.commons.lang3.StringUtils; -import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.common.xml.SAMLSchemaBuilder; -import org.opensaml.saml2.core.RequestAbstractType; -import org.opensaml.saml2.core.StatusResponseType; -import org.opensaml.saml2.metadata.IDPSSODescriptor; -import org.opensaml.saml2.metadata.SPSSODescriptor; -import org.opensaml.security.MetadataCriteria; -import org.opensaml.security.SAMLSignatureProfileValidator; -import org.opensaml.xml.security.CriteriaSet; -import org.opensaml.xml.security.credential.UsageType; -import org.opensaml.xml.security.criteria.EntityIDCriteria; -import org.opensaml.xml.security.criteria.UsageCriteria; -import org.opensaml.xml.signature.SignatureTrustEngine; -import org.opensaml.xml.validation.ValidationException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.w3c.dom.Element; -import org.xml.sax.SAXException; - -import at.gv.egiz.eaaf.core.exceptions.InvalidProtocolRequestException; -import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPVPMetadataProvider; -import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IRefreshableMetadataProvider; -import at.gv.egiz.eaaf.modules.pvp2.exception.SchemaValidationException; -import at.gv.egiz.eaaf.modules.pvp2.impl.message.InboundMessage; -import at.gv.egiz.eaaf.modules.pvp2.impl.message.PVPSProfileRequest; -import at.gv.egiz.eaaf.modules.pvp2.impl.message.PVPSProfileResponse; - -@Service("SAMLVerificationEngine") -public class SAMLVerificationEngine { - private static final Logger log = LoggerFactory.getLogger(SAMLVerificationEngine.class); - - - @Autowired(required=true) IPVPMetadataProvider metadataProvider; - - public void verify(InboundMessage msg, SignatureTrustEngine sigTrustEngine ) throws org.opensaml.xml.security.SecurityException, Exception { - try { - if (msg instanceof PVPSProfileRequest && - ((PVPSProfileRequest)msg).getSamlRequest() instanceof RequestAbstractType) - verifyRequest(((RequestAbstractType)((PVPSProfileRequest)msg).getSamlRequest()), sigTrustEngine); - - else - verifyIDPResponse(((PVPSProfileResponse)msg).getResponse(), sigTrustEngine); - - } catch (InvalidProtocolRequestException e) { - if (StringUtils.isEmpty(msg.getEntityID())) { - throw e; - - } - log.debug("PVP2X message validation FAILED. Relead metadata for entityID: " + msg.getEntityID()); - - if (metadataProvider == null || - !(metadataProvider instanceof IRefreshableMetadataProvider) || - !((IRefreshableMetadataProvider)metadataProvider).refreshMetadataProvider(msg.getEntityID())) - throw e; - - else { - log.trace("PVP2X metadata reload finished. Check validate message again."); - - if (msg instanceof PVPSProfileRequest && - ((PVPSProfileRequest)msg).getSamlRequest() instanceof RequestAbstractType) - verifyRequest(((RequestAbstractType)((PVPSProfileRequest)msg).getSamlRequest()), sigTrustEngine); - - else - verifyIDPResponse(((PVPSProfileResponse)msg).getResponse(), sigTrustEngine); - - } - log.trace("Second PVP2X message validation finished"); - } - } - - public void verifySLOResponse(StatusResponseType samlObj, SignatureTrustEngine sigTrustEngine ) throws InvalidProtocolRequestException { - verifyResponse(samlObj, sigTrustEngine, SPSSODescriptor.DEFAULT_ELEMENT_NAME); - - } - - public void verifyIDPResponse(StatusResponseType samlObj, SignatureTrustEngine sigTrustEngine) throws InvalidProtocolRequestException{ - verifyResponse(samlObj, sigTrustEngine, IDPSSODescriptor.DEFAULT_ELEMENT_NAME); - - } - - private void verifyResponse(StatusResponseType samlObj, SignatureTrustEngine sigTrustEngine, QName defaultElementName) throws InvalidProtocolRequestException{ - SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); - try { - profileValidator.validate(samlObj.getSignature()); - performSchemaValidation(samlObj.getDOM()); - - } catch (ValidationException e) { - log.warn("Signature is not conform to SAML signature profile", e); - throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); - - } catch (SchemaValidationException e) { - throw new InvalidProtocolRequestException("pvp2.22", new Object[] {e.getMessage()}); - - } - - CriteriaSet criteriaSet = new CriteriaSet(); - criteriaSet.add( new EntityIDCriteria(samlObj.getIssuer().getValue()) ); - criteriaSet.add( new MetadataCriteria(defaultElementName, SAMLConstants.SAML20P_NS) ); - criteriaSet.add( new UsageCriteria(UsageType.SIGNING) ); - - try { - if (!sigTrustEngine.validate(samlObj.getSignature(), criteriaSet)) { - throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); - } - } catch (org.opensaml.xml.security.SecurityException e) { - log.warn("PVP2x message signature validation FAILED.", e); - throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); - } - } - - private void verifyRequest(RequestAbstractType samlObj, SignatureTrustEngine sigTrustEngine ) throws InvalidProtocolRequestException { - SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); - try { - profileValidator.validate(samlObj.getSignature()); - performSchemaValidation(samlObj.getDOM()); - - } catch (ValidationException e) { - log.warn("Signature is not conform to SAML signature profile", e); - throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); - - } catch (SchemaValidationException e) { - throw new InvalidProtocolRequestException("pvp2.22", new Object[] {e.getMessage()}); - - } - - CriteriaSet criteriaSet = new CriteriaSet(); - criteriaSet.add( new EntityIDCriteria(samlObj.getIssuer().getValue()) ); - criteriaSet.add( new MetadataCriteria(SPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS) ); - criteriaSet.add( new UsageCriteria(UsageType.SIGNING) ); - - try { - if (!sigTrustEngine.validate(samlObj.getSignature(), criteriaSet)) { - throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); - } - } catch (org.opensaml.xml.security.SecurityException e) { - log.warn("PVP2x message signature validation FAILED.", e); - throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); - } - } - - protected void performSchemaValidation(Element source) throws SchemaValidationException { - - String err = null; - try { - Schema test = SAMLSchemaBuilder.getSAML11Schema(); - Validator val = test.newValidator(); - val.validate(new DOMSource(source)); - log.debug("Schema validation check done OK"); - return; - - } catch (SAXException e) { - err = e.getMessage(); - if (log.isDebugEnabled() || log.isTraceEnabled()) - log.warn("Schema validation FAILED with exception:", e); - else - log.warn("Schema validation FAILED with message: "+ e.getMessage()); - - } catch (Exception e) { - err = e.getMessage(); - if (log.isDebugEnabled() || log.isTraceEnabled()) - log.warn("Schema validation FAILED with exception:", e); - else - log.warn("Schema validation FAILED with message: "+ e.getMessage()); - - } - - throw new SchemaValidationException("pvp2.22", new Object[]{err}); - - } - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/SamlVerificationEngine.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/SamlVerificationEngine.java new file mode 100644 index 00000000..64eb5247 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/SamlVerificationEngine.java @@ -0,0 +1,218 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.impl.verification; + +import javax.xml.namespace.QName; +import javax.xml.transform.dom.DOMSource; +import javax.xml.validation.Schema; +import javax.xml.validation.Validator; +import at.gv.egiz.eaaf.core.exceptions.InvalidProtocolRequestException; +import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPvpMetadataProvider; +import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IRefreshableMetadataProvider; +import at.gv.egiz.eaaf.modules.pvp2.exception.SchemaValidationException; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.InboundMessage; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.PvpSProfileRequest; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.PvpSProfileResponse; +import org.apache.commons.lang3.StringUtils; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.common.xml.SAMLSchemaBuilder; +import org.opensaml.saml2.core.RequestAbstractType; +import org.opensaml.saml2.core.StatusResponseType; +import org.opensaml.saml2.metadata.IDPSSODescriptor; +import org.opensaml.saml2.metadata.SPSSODescriptor; +import org.opensaml.security.MetadataCriteria; +import org.opensaml.security.SAMLSignatureProfileValidator; +import org.opensaml.xml.security.CriteriaSet; +import org.opensaml.xml.security.credential.UsageType; +import org.opensaml.xml.security.criteria.EntityIDCriteria; +import org.opensaml.xml.security.criteria.UsageCriteria; +import org.opensaml.xml.signature.SignatureTrustEngine; +import org.opensaml.xml.validation.ValidationException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +@Service("SAMLVerificationEngine") +public class SamlVerificationEngine { + private static final Logger log = LoggerFactory.getLogger(SamlVerificationEngine.class); + + + @Autowired(required = true) + IPvpMetadataProvider metadataProvider; + + /** + * Verify signature of a signed SAML2 object. + * + * @param msg SAML2 message + * @param sigTrustEngine TrustEngine + * @throws org.opensaml.xml.security.SecurityException In case of invalid signature + * @throws Exception In case of a general error + */ + public void verify(final InboundMessage msg, final SignatureTrustEngine sigTrustEngine) + throws org.opensaml.xml.security.SecurityException, Exception { + try { + if (msg instanceof PvpSProfileRequest + && ((PvpSProfileRequest) msg).getSamlRequest() instanceof RequestAbstractType) { + verifyRequest(((RequestAbstractType) ((PvpSProfileRequest) msg).getSamlRequest()), + sigTrustEngine); + } else { + verifyIdpResponse(((PvpSProfileResponse) msg).getResponse(), sigTrustEngine); + } + + } catch (final InvalidProtocolRequestException e) { + if (StringUtils.isEmpty(msg.getEntityID())) { + throw e; + + } + log.debug( + "PVP2X message validation FAILED. Relead metadata for entityID: " + msg.getEntityID()); + + if (metadataProvider == null || !(metadataProvider instanceof IRefreshableMetadataProvider) + || !((IRefreshableMetadataProvider) metadataProvider) + .refreshMetadataProvider(msg.getEntityID())) { + throw e; + } else { + log.trace("PVP2X metadata reload finished. Check validate message again."); + + if (msg instanceof PvpSProfileRequest + && ((PvpSProfileRequest) msg).getSamlRequest() instanceof RequestAbstractType) { + verifyRequest(((RequestAbstractType) ((PvpSProfileRequest) msg).getSamlRequest()), + sigTrustEngine); + } else { + verifyIdpResponse(((PvpSProfileResponse) msg).getResponse(), sigTrustEngine); + } + + } + log.trace("Second PVP2X message validation finished"); + } + } + + public void verifySloResponse(final StatusResponseType samlObj, + final SignatureTrustEngine sigTrustEngine) throws InvalidProtocolRequestException { + verifyResponse(samlObj, sigTrustEngine, SPSSODescriptor.DEFAULT_ELEMENT_NAME); + + } + + public void verifyIdpResponse(final StatusResponseType samlObj, + final SignatureTrustEngine sigTrustEngine) throws InvalidProtocolRequestException { + verifyResponse(samlObj, sigTrustEngine, IDPSSODescriptor.DEFAULT_ELEMENT_NAME); + + } + + private void verifyResponse(final StatusResponseType samlObj, + final SignatureTrustEngine sigTrustEngine, final QName defaultElementName) + throws InvalidProtocolRequestException { + final SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); + try { + profileValidator.validate(samlObj.getSignature()); + performSchemaValidation(samlObj.getDOM()); + + } catch (final ValidationException e) { + log.warn("Signature is not conform to SAML signature profile", e); + throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); + + } catch (final SchemaValidationException e) { + throw new InvalidProtocolRequestException("pvp2.22", new Object[] {e.getMessage()}); + + } + + final CriteriaSet criteriaSet = new CriteriaSet(); + criteriaSet.add(new EntityIDCriteria(samlObj.getIssuer().getValue())); + criteriaSet.add(new MetadataCriteria(defaultElementName, SAMLConstants.SAML20P_NS)); + criteriaSet.add(new UsageCriteria(UsageType.SIGNING)); + + try { + if (!sigTrustEngine.validate(samlObj.getSignature(), criteriaSet)) { + throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); + } + } catch (final org.opensaml.xml.security.SecurityException e) { + log.warn("PVP2x message signature validation FAILED.", e); + throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); + } + } + + private void verifyRequest(final RequestAbstractType samlObj, + final SignatureTrustEngine sigTrustEngine) throws InvalidProtocolRequestException { + final SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); + try { + profileValidator.validate(samlObj.getSignature()); + performSchemaValidation(samlObj.getDOM()); + + } catch (final ValidationException e) { + log.warn("Signature is not conform to SAML signature profile", e); + throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); + + } catch (final SchemaValidationException e) { + throw new InvalidProtocolRequestException("pvp2.22", new Object[] {e.getMessage()}); + + } + + final CriteriaSet criteriaSet = new CriteriaSet(); + criteriaSet.add(new EntityIDCriteria(samlObj.getIssuer().getValue())); + criteriaSet + .add(new MetadataCriteria(SPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS)); + criteriaSet.add(new UsageCriteria(UsageType.SIGNING)); + + try { + if (!sigTrustEngine.validate(samlObj.getSignature(), criteriaSet)) { + throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); + } + } catch (final org.opensaml.xml.security.SecurityException e) { + log.warn("PVP2x message signature validation FAILED.", e); + throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); + } + } + + protected void performSchemaValidation(final Element source) throws SchemaValidationException { + + String err = null; + try { + final Schema test = SAMLSchemaBuilder.getSAML11Schema(); + final Validator val = test.newValidator(); + val.validate(new DOMSource(source)); + log.debug("Schema validation check done OK"); + return; + + } catch (final SAXException e) { + err = e.getMessage(); + if (log.isDebugEnabled() || log.isTraceEnabled()) { + log.warn("Schema validation FAILED with exception:", e); + } else { + log.warn("Schema validation FAILED with message: " + e.getMessage()); + } + + } catch (final Exception e) { + err = e.getMessage(); + if (log.isDebugEnabled() || log.isTraceEnabled()) { + log.warn("Schema validation FAILED with exception:", e); + } else { + log.warn("Schema validation FAILED with message: " + e.getMessage()); + } + + } + + throw new SchemaValidationException("pvp2.22", new Object[] {err}); + + } + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider b/eaaf_modules/eaaf_module_pvp2_core/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider index 9c60d724..8bc7508c 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider @@ -1 +1 @@ -at.gv.egiz.eaaf.modules.pvp2.PVP2SProfileCoreSpringResourceProvider \ No newline at end of file +at.gv.egiz.eaaf.modules.pvp2.Pvp2SProfileCoreSpringResourceProvider \ No newline at end of file diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/resources/eaaf_pvp.beans.xml b/eaaf_modules/eaaf_module_pvp2_core/src/main/resources/eaaf_pvp.beans.xml index 2cbcce20..ee4d3864 100644 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/resources/eaaf_pvp.beans.xml +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/resources/eaaf_pvp.beans.xml @@ -1,30 +1,25 @@ - - - - - - - - - - - - + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:context="http://www.springframework.org/schema/context" + xmlns:tx="http://www.springframework.org/schema/tx" + xmlns:aop="http://www.springframework.org/schema/aop" + xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd + http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> + + + + + + + + + \ No newline at end of file diff --git a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/PVP2SProfileIDPSpringResourceProvider.java b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/PVP2SProfileIDPSpringResourceProvider.java deleted file mode 100644 index d50c5ee4..00000000 --- a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/PVP2SProfileIDPSpringResourceProvider.java +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.idp; - -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; - -import at.gv.egiz.components.spring.api.SpringResourceProvider; - -public class PVP2SProfileIDPSpringResourceProvider implements SpringResourceProvider { - - @Override - public String getName() { - return "EAAF PVP2 S-Profile IDP SpringResourceProvider"; - } - - @Override - public String[] getPackagesToScan() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Resource[] getResourcesToLoad() { - ClassPathResource sl20AuthConfig = new ClassPathResource("/eaaf_pvp_idp.beans.xml", PVP2SProfileIDPSpringResourceProvider.class); - - return new Resource[] {sl20AuthConfig}; - } - -} diff --git a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/Pvp2SProfileIdpSpringResourceProvider.java b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/Pvp2SProfileIdpSpringResourceProvider.java new file mode 100644 index 00000000..9414dc33 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/Pvp2SProfileIdpSpringResourceProvider.java @@ -0,0 +1,47 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.idp; + +import at.gv.egiz.components.spring.api.SpringResourceProvider; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; + +public class Pvp2SProfileIdpSpringResourceProvider implements SpringResourceProvider { + + @Override + public String getName() { + return "EAAF PVP2 S-Profile IDP SpringResourceProvider"; + } + + @Override + public String[] getPackagesToScan() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Resource[] getResourcesToLoad() { + final ClassPathResource sl20AuthConfig = new ClassPathResource("/eaaf_pvp_idp.beans.xml", + Pvp2SProfileIdpSpringResourceProvider.class); + + return new Resource[] {sl20AuthConfig}; + } + +} diff --git a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/api/builder/ISubjectNameIdGenerator.java b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/api/builder/ISubjectNameIdGenerator.java index 90662f48..131be543 100644 --- a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/api/builder/ISubjectNameIdGenerator.java +++ b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/api/builder/ISubjectNameIdGenerator.java @@ -1,45 +1,39 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.idp.api.builder; import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; import at.gv.egiz.eaaf.core.impl.data.Pair; -import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; +import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2Exception; public interface ISubjectNameIdGenerator { - /** - * Generates a SAML2 subjectNameId from authentication data - * - * @param authData Authentication data for the current pending request - * @param spConfig Service provider configuration - * @return Pair of subjectNameId and NameIdFormat - * @throws PVP2Exception - */ - public Pair generateSubjectNameId(IAuthData authData, ISPConfiguration spConfig) throws PVP2Exception; + /** + * Generates a SAML2 subjectNameId from authentication data. + * + * @param authData Authentication data for the current pending request + * @param spConfig Service provider configuration + * @return Pair of subjectNameId and NameIdFormat + * @throws Pvp2Exception In case of an error + */ + public Pair generateSubjectNameId(IAuthData authData, IspConfiguration spConfig) + throws Pvp2Exception; } diff --git a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/InvalidAssertionConsumerServiceException.java b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/InvalidAssertionConsumerServiceException.java index 42424726..6d868558 100644 --- a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/InvalidAssertionConsumerServiceException.java +++ b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/InvalidAssertionConsumerServiceException.java @@ -1,54 +1,47 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.idp.exception; +import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2Exception; import org.opensaml.saml2.core.StatusCode; -import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; +public class InvalidAssertionConsumerServiceException extends Pvp2Exception { + + private static final long serialVersionUID = 7861790149343943091L; + + public InvalidAssertionConsumerServiceException(final int idx) { + super("pvp2.28", new Object[] {idx}); + this.statusCodeValue = StatusCode.REQUESTER_URI; + } -public class InvalidAssertionConsumerServiceException extends PVP2Exception { + /** + * Invalid assertion consumer-service URL. + * + * @param wrongUrl invalid URL + */ + public InvalidAssertionConsumerServiceException(final String wrongUrl) { + super("pvp2.23", new Object[] {wrongUrl}); + this.statusCodeValue = StatusCode.REQUESTER_URI; - public InvalidAssertionConsumerServiceException(int idx) { - super("pvp2.28", new Object[]{idx}); - this.statusCodeValue = StatusCode.REQUESTER_URI; - } + } - /** - * - */ - public InvalidAssertionConsumerServiceException(String wrongURL) { - super("pvp2.23", new Object[]{wrongURL}); - this.statusCodeValue = StatusCode.REQUESTER_URI; - - } - /** - * - */ - private static final long serialVersionUID = 7861790149343943091L; } diff --git a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/InvalidAssertionEncryptionException.java b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/InvalidAssertionEncryptionException.java index 55c94df1..0d75616a 100644 --- a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/InvalidAssertionEncryptionException.java +++ b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/InvalidAssertionEncryptionException.java @@ -1,42 +1,34 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.idp.exception; +import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2Exception; import org.opensaml.saml2.core.StatusCode; -import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; - -public class InvalidAssertionEncryptionException extends PVP2Exception { +public class InvalidAssertionEncryptionException extends Pvp2Exception { - private static final long serialVersionUID = 6513388841485355549L; + private static final long serialVersionUID = 6513388841485355549L; - public InvalidAssertionEncryptionException() { - super("pvp2.16", new Object[]{}); - this.statusCodeValue = StatusCode.RESPONDER_URI; - } + public InvalidAssertionEncryptionException() { + super("pvp2.16", new Object[] {}); + this.statusCodeValue = StatusCode.RESPONDER_URI; + } } diff --git a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/RequestDeniedException.java b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/RequestDeniedException.java index 6109c78d..ecceea12 100644 --- a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/RequestDeniedException.java +++ b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/RequestDeniedException.java @@ -1,45 +1,34 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.idp.exception; +import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2Exception; import org.opensaml.saml2.core.StatusCode; -import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; - -public class RequestDeniedException extends PVP2Exception { +public class RequestDeniedException extends Pvp2Exception { - public RequestDeniedException() { - super("pvp2.14", null); - this.statusCodeValue = StatusCode.REQUEST_DENIED_URI; - } + private static final long serialVersionUID = 4415896615794730553L; - /** - * - */ - private static final long serialVersionUID = 4415896615794730553L; + public RequestDeniedException() { + super("pvp2.14", null); + this.statusCodeValue = StatusCode.REQUEST_DENIED_URI; + } } diff --git a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/ResponderErrorException.java b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/ResponderErrorException.java index 7f565c00..331e11cd 100644 --- a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/ResponderErrorException.java +++ b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/ResponderErrorException.java @@ -1,50 +1,39 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.idp.exception; +import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2Exception; import org.opensaml.saml2.core.StatusCode; -import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; +public class ResponderErrorException extends Pvp2Exception { -public class ResponderErrorException extends PVP2Exception { + private static final long serialVersionUID = -425416760138285446L; - /** - * - */ - private static final long serialVersionUID = -425416760138285446L; + public ResponderErrorException(final String messageId, final Object[] parameters, + final Throwable wrapped) { + super(messageId, parameters, wrapped); + this.statusCodeValue = StatusCode.RESPONDER_URI; + } - public ResponderErrorException(String messageId, Object[] parameters, - Throwable wrapped) { - super(messageId, parameters, wrapped); - this.statusCodeValue = StatusCode.RESPONDER_URI; - } - - public ResponderErrorException(String messageId, Object[] parameters) { - super(messageId, parameters); - this.statusCodeValue = StatusCode.RESPONDER_URI; - } + public ResponderErrorException(final String messageId, final Object[] parameters) { + super(messageId, parameters); + this.statusCodeValue = StatusCode.RESPONDER_URI; + } } diff --git a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/SAMLRequestNotSignedException.java b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/SAMLRequestNotSignedException.java deleted file mode 100644 index a0fad363..00000000 --- a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/SAMLRequestNotSignedException.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.idp.exception; - -import org.opensaml.saml2.core.StatusCode; - -import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; - -public class SAMLRequestNotSignedException extends PVP2Exception { - - public SAMLRequestNotSignedException() { - super("pvp2.07", null); - this.statusCodeValue = StatusCode.REQUESTER_URI; - } - - public SAMLRequestNotSignedException(Throwable e) { - super("pvp2.07", null, e); - this.statusCodeValue = StatusCode.REQUESTER_URI; - } - - /** - * - */ - private static final long serialVersionUID = 1L; - -} diff --git a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/SAMLRequestNotSupported.java b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/SAMLRequestNotSupported.java deleted file mode 100644 index e59ebe0a..00000000 --- a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/SAMLRequestNotSupported.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.idp.exception; - -import org.opensaml.saml2.core.StatusCode; - -import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; - - -public class SAMLRequestNotSupported extends PVP2Exception { - - public SAMLRequestNotSupported() { - super("pvp2.09", null); - this.statusCodeValue = StatusCode.REQUEST_UNSUPPORTED_URI; - } - - /** - * - */ - private static final long serialVersionUID = 1244883178458802767L; - -} diff --git a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/SamlRequestNotSignedException.java b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/SamlRequestNotSignedException.java new file mode 100644 index 00000000..4650506d --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/SamlRequestNotSignedException.java @@ -0,0 +1,42 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.idp.exception; + +import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2Exception; +import org.opensaml.saml2.core.StatusCode; + +public class SamlRequestNotSignedException extends Pvp2Exception { + + private static final long serialVersionUID = 1L; + + public SamlRequestNotSignedException() { + super("pvp2.07", null); + this.statusCodeValue = StatusCode.REQUESTER_URI; + } + + public SamlRequestNotSignedException(final Throwable e) { + super("pvp2.07", null, e); + this.statusCodeValue = StatusCode.REQUESTER_URI; + } + + + + +} diff --git a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/SamlRequestNotSupported.java b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/SamlRequestNotSupported.java new file mode 100644 index 00000000..58a493b9 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/SamlRequestNotSupported.java @@ -0,0 +1,39 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.idp.exception; + +import org.opensaml.saml2.core.StatusCode; + +import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2Exception; + + +public class SamlRequestNotSupported extends Pvp2Exception { + + private static final long serialVersionUID = 1244883178458802767L; + + public SamlRequestNotSupported() { + super("pvp2.09", null); + this.statusCodeValue = StatusCode.REQUEST_UNSUPPORTED_URI; + } + + + + +} diff --git a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/UnprovideableAttributeException.java b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/UnprovideableAttributeException.java index 0dfda55f..41252b78 100644 --- a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/UnprovideableAttributeException.java +++ b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/exception/UnprovideableAttributeException.java @@ -1,43 +1,33 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.idp.exception; +import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2Exception; import org.opensaml.saml2.core.StatusCode; -import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; +public class UnprovideableAttributeException extends Pvp2Exception { -public class UnprovideableAttributeException extends PVP2Exception { - /** - * - */ - private static final long serialVersionUID = 3972197758163647157L; + private static final long serialVersionUID = 3972197758163647157L; - public UnprovideableAttributeException(String attributeName) { - super("pvp2.10", new Object[] {attributeName}); - this.statusCodeValue = StatusCode.UNKNOWN_ATTR_PROFILE_URI; - } + public UnprovideableAttributeException(final String attributeName) { + super("pvp2.10", new Object[] {attributeName}); + this.statusCodeValue = StatusCode.UNKNOWN_ATTR_PROFILE_URI; + } } diff --git a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/AbstractPVP2XProtocol.java b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/AbstractPVP2XProtocol.java deleted file mode 100644 index 3298559a..00000000 --- a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/AbstractPVP2XProtocol.java +++ /dev/null @@ -1,541 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.idp.impl; - -import java.util.List; - -import javax.annotation.PostConstruct; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang.StringEscapeUtils; -import org.apache.commons.lang3.StringUtils; -import org.joda.time.DateTime; -import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.saml2.core.AuthnRequest; -import org.opensaml.saml2.core.Issuer; -import org.opensaml.saml2.core.NameID; -import org.opensaml.saml2.core.Response; -import org.opensaml.saml2.core.Status; -import org.opensaml.saml2.core.StatusCode; -import org.opensaml.saml2.core.StatusMessage; -import org.opensaml.saml2.metadata.AssertionConsumerService; -import org.opensaml.saml2.metadata.EntityDescriptor; -import org.opensaml.saml2.metadata.SPSSODescriptor; -import org.opensaml.ws.security.SecurityPolicyException; -import org.opensaml.xml.security.x509.X509Credential; -import org.opensaml.xml.signature.SignableXMLObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - -import at.gv.egiz.components.eventlog.api.EventConstants; -import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.core.api.data.EAAFConstants; -import at.gv.egiz.eaaf.core.api.idp.IModulInfo; -import at.gv.egiz.eaaf.core.api.logging.IRevisionLogger; -import at.gv.egiz.eaaf.core.exceptions.AuthnRequestValidatorException; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.core.exceptions.InvalidProtocolRequestException; -import at.gv.egiz.eaaf.core.exceptions.NoPassivAuthenticationException; -import at.gv.egiz.eaaf.core.exceptions.SLOException; -import at.gv.egiz.eaaf.core.impl.idp.controller.AbstractController; -import at.gv.egiz.eaaf.modules.pvp2.PVPEventConstants; -import at.gv.egiz.eaaf.modules.pvp2.api.IPVP2BasicConfiguration; -import at.gv.egiz.eaaf.modules.pvp2.api.binding.IEncoder; -import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPVPMetadataProvider; -import at.gv.egiz.eaaf.modules.pvp2.api.validation.IAuthnRequestValidator; -import at.gv.egiz.eaaf.modules.pvp2.exception.InvalidPVPRequestException; -import at.gv.egiz.eaaf.modules.pvp2.exception.NameIDFormatNotSupportedException; -import at.gv.egiz.eaaf.modules.pvp2.exception.NoMetadataInformationException; -import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; -import at.gv.egiz.eaaf.modules.pvp2.idp.exception.InvalidAssertionConsumerServiceException; -import at.gv.egiz.eaaf.modules.pvp2.impl.binding.PostBinding; -import at.gv.egiz.eaaf.modules.pvp2.impl.binding.RedirectBinding; -import at.gv.egiz.eaaf.modules.pvp2.impl.binding.SoapBinding; -import at.gv.egiz.eaaf.modules.pvp2.impl.message.InboundMessage; -import at.gv.egiz.eaaf.modules.pvp2.impl.message.PVPSProfileRequest; -import at.gv.egiz.eaaf.modules.pvp2.impl.utils.AbstractCredentialProvider; -import at.gv.egiz.eaaf.modules.pvp2.impl.utils.SAML2Utils; -import at.gv.egiz.eaaf.modules.pvp2.impl.validation.EAAFURICompare; -import at.gv.egiz.eaaf.modules.pvp2.impl.validation.TrustEngineFactory; -import at.gv.egiz.eaaf.modules.pvp2.impl.verification.SAMLVerificationEngine; - -public abstract class AbstractPVP2XProtocol extends AbstractController implements IModulInfo { - private static final Logger log = LoggerFactory.getLogger(AbstractPVP2XProtocol.class); - - @Autowired(required=true) protected IPVP2BasicConfiguration pvpBasicConfiguration; - @Autowired(required=true) protected IPVPMetadataProvider metadataProvider; - @Autowired(required=true) protected SAMLVerificationEngine samlVerificationEngine; - @Autowired(required=true) protected IAuthnRequestValidator authRequestValidator; - - private AbstractCredentialProvider pvpIDPCredentials; - - - - /** - * Sets a specific credential provider for PVP S-Profile IDP component. - * @param pvpIDPCredentials credential provider - */ - public void setPvpIDPCredentials(AbstractCredentialProvider pvpIDPCredentials) { - this.pvpIDPCredentials = pvpIDPCredentials; - - } - - public boolean generateErrorMessage(Throwable e, - HttpServletRequest request, HttpServletResponse response, - IRequest protocolRequest) throws Throwable { - - if(protocolRequest == null) { - throw e; - } - - if(!(protocolRequest instanceof PVPSProfilePendingRequest) ) { - throw e; - } - PVPSProfilePendingRequest pvpRequest = (PVPSProfilePendingRequest)protocolRequest; - - Response samlResponse = - SAML2Utils.createSAMLObject(Response.class); - Status status = SAML2Utils.createSAMLObject(Status.class); - StatusCode statusCode = SAML2Utils.createSAMLObject(StatusCode.class); - StatusMessage statusMessage = SAML2Utils.createSAMLObject(StatusMessage.class); - - String moaError = null; - - if(e instanceof NoPassivAuthenticationException) { - statusCode.setValue(StatusCode.NO_PASSIVE_URI); - statusMessage.setMessage(StringEscapeUtils.escapeXml(e.getLocalizedMessage())); - - } else if (e instanceof NameIDFormatNotSupportedException) { - statusCode.setValue(StatusCode.INVALID_NAMEID_POLICY_URI); - statusMessage.setMessage(StringEscapeUtils.escapeXml(e.getLocalizedMessage())); - - } else if (e instanceof SLOException) { - //SLOExecpetions only occurs if session information is lost - return false; - - } else if(e instanceof PVP2Exception) { - PVP2Exception ex = (PVP2Exception) e; - statusCode.setValue(ex.getStatusCodeValue()); - String statusMessageValue = ex.getStatusMessageValue(); - if(statusMessageValue != null) { - statusMessage.setMessage(StringEscapeUtils.escapeXml(statusMessageValue)); - } - moaError = statusMessager.mapInternalErrorToExternalError(ex.getErrorId()); - - } else { - statusCode.setValue(StatusCode.RESPONDER_URI); - statusMessage.setMessage(StringEscapeUtils.escapeXml(e.getLocalizedMessage())); - moaError = statusMessager.getResponseErrorCode(e); - } - - - if (StringUtils.isNotEmpty(moaError)) { - StatusCode moaStatusCode = SAML2Utils.createSAMLObject(StatusCode.class); - moaStatusCode.setValue(moaError); - statusCode.setStatusCode(moaStatusCode); - } - - status.setStatusCode(statusCode); - if(statusMessage.getMessage() != null) { - status.setStatusMessage(statusMessage); - } - samlResponse.setStatus(status); - String remoteSessionID = SAML2Utils.getSecureIdentifier(); - samlResponse.setID(remoteSessionID); - - samlResponse.setIssueInstant(new DateTime()); - Issuer nissuer = SAML2Utils.createSAMLObject(Issuer.class); - nissuer.setValue(pvpBasicConfiguration.getIDPEntityId(pvpRequest.getAuthURL())); - nissuer.setFormat(NameID.ENTITY); - samlResponse.setIssuer(nissuer); - - IEncoder encoder = null; - - if(pvpRequest.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { - encoder = applicationContext.getBean("PVPRedirectBinding", RedirectBinding.class); - - } else if(pvpRequest.getBinding().equals(SAMLConstants.SAML2_POST_BINDING_URI)) { - encoder = applicationContext.getBean("PVPPOSTBinding", PostBinding.class); - - } else if (pvpRequest.getBinding().equals(SAMLConstants.SAML2_SOAP11_BINDING_URI)) { - encoder = applicationContext.getBean("PVPSOAPBinding", SoapBinding.class); - } - - if(encoder == null) { - // default to redirect binding - encoder = new RedirectBinding(); - } - - String relayState = null; - if (pvpRequest.getRequest() != null) - relayState = pvpRequest.getRequest().getRelayState(); - - X509Credential signCred = pvpIDPCredentials.getIDPAssertionSigningCredential(); - - encoder.encodeRespone(request, response, samlResponse, pvpRequest.getConsumerURL(), - relayState, signCred, protocolRequest); - return true; - } - - public boolean validate(HttpServletRequest request, - HttpServletResponse response, IRequest pending) { - - return true; - } - - protected void pvpMetadataRequest(HttpServletRequest req, HttpServletResponse resp) throws EAAFException { - //create pendingRequest object - PVPSProfilePendingRequest pendingReq = applicationContext.getBean(PVPSProfilePendingRequest.class); - pendingReq.initialize(req, authConfig); - pendingReq.setModule(getName()); - - revisionsLogger.logEvent( - pendingReq.getUniqueSessionIdentifier(), - pendingReq.getUniqueTransactionIdentifier(), - EventConstants.TRANSACTION_IP, - req.getRemoteAddr()); - - MetadataAction metadataAction = applicationContext.getBean(MetadataAction.class); - metadataAction.processRequest(pendingReq, - req, resp, null); - - } - - protected void PVPIDPPostRequest(HttpServletRequest req, HttpServletResponse resp) throws EAAFException { - PVPSProfilePendingRequest pendingReq = null; - - try { - //create pendingRequest object - pendingReq = applicationContext.getBean(PVPSProfilePendingRequest.class); - pendingReq.initialize(req, authConfig); - pendingReq.setModule(getName()); - - revisionsLogger.logEvent(EventConstants.SESSION_CREATED, pendingReq.getUniqueSessionIdentifier()); - revisionsLogger.logEvent(EventConstants.TRANSACTION_CREATED, pendingReq.getUniqueTransactionIdentifier()); - revisionsLogger.logEvent( - pendingReq.getUniqueSessionIdentifier(), - pendingReq.getUniqueTransactionIdentifier(), - EventConstants.TRANSACTION_IP, - req.getRemoteAddr()); - - //get POST-Binding decoder implementation - InboundMessage msg = (InboundMessage) new PostBinding().decode( - req, resp, metadataProvider, false, - new EAAFURICompare(pvpBasicConfiguration.getIDPSSOPostService(pendingReq.getAuthURL()))); - pendingReq.setRequest(msg); - - //preProcess Message - preProcess(req, resp, pendingReq); - - } catch (SecurityPolicyException e) { - String samlRequest = req.getParameter("SAMLRequest"); - log.warn("Receive INVALID protocol request: " + samlRequest, e); - - //write revision log entries - if (pendingReq != null) - revisionsLogger.logEvent(pendingReq, EventConstants.TRANSACTION_ERROR, pendingReq.getUniqueTransactionIdentifier()); - - throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); - - } catch (SecurityException e) { - String samlRequest = req.getParameter("SAMLRequest"); - log.warn("Receive INVALID protocol request: " + samlRequest, e); - - //write revision log entries - if (pendingReq != null) - revisionsLogger.logEvent(pendingReq, EventConstants.TRANSACTION_ERROR, pendingReq.getUniqueTransactionIdentifier()); - - throw new InvalidProtocolRequestException("pvp2.22", new Object[] {e.getMessage()}); - - } catch (EAAFException e) { - - //write revision log entries - if (pendingReq != null) - revisionsLogger.logEvent(pendingReq, EventConstants.TRANSACTION_ERROR, pendingReq.getUniqueTransactionIdentifier()); - - throw e; - - } catch (Throwable e) { - String samlRequest = req.getParameter("SAMLRequest"); - log.warn("Receive INVALID protocol request: " + samlRequest, e); - - //write revision log entries - if (pendingReq != null) - revisionsLogger.logEvent(pendingReq, EventConstants.TRANSACTION_ERROR, pendingReq.getUniqueTransactionIdentifier()); - - throw new EAAFException("pvp2.24", new Object[] {e.getMessage()}, e); - } - } - - protected void PVPIDPRedirecttRequest(HttpServletRequest req, HttpServletResponse resp) throws EAAFException { - PVPSProfilePendingRequest pendingReq = null; - try { - //create pendingRequest object - pendingReq = applicationContext.getBean(PVPSProfilePendingRequest.class); - pendingReq.initialize(req, authConfig); - pendingReq.setModule(getName()); - - revisionsLogger.logEvent(EventConstants.SESSION_CREATED, pendingReq.getUniqueSessionIdentifier()); - revisionsLogger.logEvent(EventConstants.TRANSACTION_CREATED, pendingReq.getUniqueTransactionIdentifier()); - revisionsLogger.logEvent( - pendingReq.getUniqueSessionIdentifier(), - pendingReq.getUniqueTransactionIdentifier(), - EventConstants.TRANSACTION_IP, - req.getRemoteAddr()); - - //get POST-Binding decoder implementation - InboundMessage msg = (InboundMessage) new RedirectBinding().decode( - req, resp, metadataProvider, false, - new EAAFURICompare(pvpBasicConfiguration.getIDPSSORedirectService(pendingReq.getAuthURL()))); - pendingReq.setRequest(msg); - - //preProcess Message - preProcess(req, resp, pendingReq); - - } catch (SecurityPolicyException e) { - String samlRequest = req.getParameter("SAMLRequest"); - log.warn("Receive INVALID protocol request: " + samlRequest, e); - - //write revision log entries - if (pendingReq != null) - revisionsLogger.logEvent(pendingReq, EventConstants.TRANSACTION_ERROR, pendingReq.getUniqueTransactionIdentifier()); - - throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); - - } catch (SecurityException e) { - String samlRequest = req.getParameter("SAMLRequest"); - log.warn("Receive INVALID protocol request: " + samlRequest, e); - - //write revision log entries - if (pendingReq != null) - revisionsLogger.logEvent(pendingReq, EventConstants.TRANSACTION_ERROR, pendingReq.getUniqueTransactionIdentifier()); - - throw new InvalidProtocolRequestException("pvp2.22", new Object[] {e.getMessage()}); - - } catch (EAAFException e) { - String samlRequest = req.getParameter("SAMLRequest"); - log.info("Receive INVALID protocol request: " + samlRequest); - - //write revision log entries - if (pendingReq != null) - revisionsLogger.logEvent(pendingReq, EventConstants.TRANSACTION_ERROR, pendingReq.getUniqueTransactionIdentifier()); - - throw e; - - } catch (Throwable e) { - String samlRequest = req.getParameter("SAMLRequest"); - log.warn("Receive INVALID protocol request: " + samlRequest, e); - - //write revision log entries - if (pendingReq != null) - revisionsLogger.logEvent(pendingReq, EventConstants.TRANSACTION_ERROR, pendingReq.getUniqueTransactionIdentifier()); - - throw new EAAFException("pvp2.24", new Object[] {e.getMessage()}, e); - } - } - - - - /** - * - * - * @param request - * @param response - * @param msg - * @return true if preprocess can handle this request type, otherwise false - * @throws Throwable - */ - abstract protected boolean childPreProcess(HttpServletRequest request, - HttpServletResponse response, PVPSProfilePendingRequest pendingReq) throws Throwable; - - protected void preProcess(HttpServletRequest request, - HttpServletResponse response, PVPSProfilePendingRequest pendingReq) throws Throwable { - - InboundMessage msg = pendingReq.getRequest(); - - if (StringUtils.isEmpty(msg.getEntityID())) { - throw new InvalidProtocolRequestException("pvp2.20", new Object[] {}); - - } - - if(!msg.isVerified()) { - samlVerificationEngine.verify(msg, - TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider)); - msg.setVerified(true); - - } - - revisionsLogger.logEvent(pendingReq, IRevisionLogger.AUTHPROTOCOL_TYPE, getAuthProtocolIdentifier()); - - if (msg instanceof PVPSProfileRequest && - ((PVPSProfileRequest)msg).getSamlRequest() instanceof AuthnRequest) - preProcessAuthRequest(request, response, pendingReq); - - else if (childPreProcess(request, response, pendingReq)) - log.debug("Find protocol handler in child implementation"); - - else { - log.error("Receive unsupported PVP21 message of type: " + ((PVPSProfileRequest)msg).getSamlRequest().getClass().getName()); - throw new InvalidPVPRequestException("pvp2.09", - new Object[] {((PVPSProfileRequest)msg).getSamlRequest().getClass().getName()}); - } - - - - //switch to session authentication - protAuthService.performAuthentication(request, response, pendingReq); - } - - - /** - * PreProcess Authn request - * @param request - * @param response - * @param pendingReq - * @throws Throwable - */ - private void preProcessAuthRequest(HttpServletRequest request, - HttpServletResponse response, PVPSProfilePendingRequest pendingReq) throws Throwable { - - PVPSProfileRequest moaRequest = ((PVPSProfileRequest)pendingReq.getRequest()); - SignableXMLObject samlReq = moaRequest.getSamlRequest(); - - if(!(samlReq instanceof AuthnRequest)) { - throw new InvalidPVPRequestException("Unsupported request", new Object[] {}); - } - - EntityDescriptor metadata = moaRequest.getEntityMetadata(metadataProvider); - if(metadata == null) { - throw new NoMetadataInformationException(); - } - SPSSODescriptor spSSODescriptor = metadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS); - - AuthnRequest authnRequest = (AuthnRequest)samlReq; - - if (authnRequest.getIssueInstant() == null) { - log.warn("Unsupported request: No IssueInstant Attribute found."); - throw new AuthnRequestValidatorException("pvp2.22", - new Object[] {"Unsupported request: No IssueInstant Attribute found"}, - pendingReq); - - } - - if (authnRequest.getIssueInstant().minusMinutes(EAAFConstants.ALLOWED_TIME_JITTER).isAfterNow()) { - log.warn("Unsupported request: No IssueInstant DateTime is not valid anymore."); - throw new AuthnRequestValidatorException("pvp2.22", - new Object[] {"Unsupported request: No IssueInstant DateTime is not valid anymore."}, - pendingReq); - - } - - //parse AssertionConsumerService - AssertionConsumerService consumerService = null; - if (StringUtils.isNotEmpty(authnRequest.getAssertionConsumerServiceURL()) && - StringUtils.isNotEmpty(authnRequest.getProtocolBinding())) { - //use AssertionConsumerServiceURL from request - - //check requested AssertionConsumingService URL against metadata - List metadataAssertionServiceList = spSSODescriptor.getAssertionConsumerServices(); - for (AssertionConsumerService service : metadataAssertionServiceList) { - if (authnRequest.getProtocolBinding().equals(service.getBinding()) - && authnRequest.getAssertionConsumerServiceURL().equals(service.getLocation())) { - consumerService = SAML2Utils.createSAMLObject(AssertionConsumerService.class); - consumerService.setBinding(authnRequest.getProtocolBinding()); - consumerService.setLocation(authnRequest.getAssertionConsumerServiceURL()); - log.debug("Requested AssertionConsumerServiceURL is valid."); - } - } - - if (consumerService == null) { - throw new InvalidAssertionConsumerServiceException(authnRequest.getAssertionConsumerServiceURL()); - - } - - - } else { - //use AssertionConsumerServiceIndex and select consumerService from metadata - Integer aIdx = authnRequest.getAssertionConsumerServiceIndex(); - int assertionidx = 0; - - if(aIdx != null) { - assertionidx = aIdx.intValue(); - - } else { - assertionidx = SAML2Utils.getDefaultAssertionConsumerServiceIndex(spSSODescriptor); - - } - consumerService = spSSODescriptor.getAssertionConsumerServices().get(assertionidx); - - if (consumerService == null) { - throw new InvalidAssertionConsumerServiceException(aIdx); - - } - } - - - //validate AuthnRequest - AuthnRequest authReq = (AuthnRequest) samlReq; - String oaURL = moaRequest.getEntityMetadata(metadataProvider).getEntityID(); - log.info("Dispatch PVP2 AuthnRequest: OAURL=" + oaURL + " Binding=" + consumerService.getBinding()); - - pendingReq.setSPEntityId(StringEscapeUtils.escapeHtml(oaURL)); - pendingReq.setOnlineApplicationConfiguration(authConfig.getServiceProviderConfiguration(pendingReq.getSPEntityId())); - pendingReq.setBinding(consumerService.getBinding()); - pendingReq.setRequest(moaRequest); - pendingReq.setConsumerURL(consumerService.getLocation()); - - //parse AuthRequest - pendingReq.setPassiv(authReq.isPassive()); - pendingReq.setForce(authReq.isForceAuthn()); - - //AuthnRequest needs authentication - pendingReq.setNeedAuthentication(true); - - //set protocol action, which should be executed after authentication - pendingReq.setAction(AuthenticationAction.class.getName()); - - log.trace("Starting extended AuthnRequest validation and processing ... "); - authRequestValidator.validate(request, pendingReq, authReq, spSSODescriptor); - log.debug("Extended AuthnRequest validation and processing finished"); - - //write revisionslog entry - revisionsLogger.logEvent(pendingReq, PVPEventConstants.AUTHPROTOCOL_PVP_REQUEST_AUTHREQUEST, authReq.getID()); - - } - - @PostConstruct - private void verifyInitialization() { - if (pvpIDPCredentials == null) { - log.error("No SAML2 credentialProvider injected!"); - throw new RuntimeException("No SAML2 credentialProvider injected!"); - - } - } - -} diff --git a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/AbstractPvp2XProtocol.java b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/AbstractPvp2XProtocol.java new file mode 100644 index 00000000..3fac7894 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/AbstractPvp2XProtocol.java @@ -0,0 +1,561 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.idp.impl; + +import java.util.List; +import javax.annotation.PostConstruct; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import at.gv.egiz.components.eventlog.api.EventConstants; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; +import at.gv.egiz.eaaf.core.api.idp.IModulInfo; +import at.gv.egiz.eaaf.core.api.logging.IRevisionLogger; +import at.gv.egiz.eaaf.core.exceptions.AuthnRequestValidatorException; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.exceptions.InvalidProtocolRequestException; +import at.gv.egiz.eaaf.core.exceptions.NoPassivAuthenticationException; +import at.gv.egiz.eaaf.core.exceptions.SloException; +import at.gv.egiz.eaaf.core.impl.idp.controller.AbstractController; +import at.gv.egiz.eaaf.modules.pvp2.PvpEventConstants; +import at.gv.egiz.eaaf.modules.pvp2.api.IPvo2BasicConfiguration; +import at.gv.egiz.eaaf.modules.pvp2.api.binding.IEncoder; +import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPvpMetadataProvider; +import at.gv.egiz.eaaf.modules.pvp2.api.validation.IAuthnRequestValidator; +import at.gv.egiz.eaaf.modules.pvp2.exception.InvalidPvpRequestException; +import at.gv.egiz.eaaf.modules.pvp2.exception.NameIdFormatNotSupportedException; +import at.gv.egiz.eaaf.modules.pvp2.exception.NoMetadataInformationException; +import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2Exception; +import at.gv.egiz.eaaf.modules.pvp2.idp.exception.InvalidAssertionConsumerServiceException; +import at.gv.egiz.eaaf.modules.pvp2.impl.binding.PostBinding; +import at.gv.egiz.eaaf.modules.pvp2.impl.binding.RedirectBinding; +import at.gv.egiz.eaaf.modules.pvp2.impl.binding.SoapBinding; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.InboundMessage; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.PvpSProfileRequest; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.AbstractCredentialProvider; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.Saml2Utils; +import at.gv.egiz.eaaf.modules.pvp2.impl.validation.EaafUriCompare; +import at.gv.egiz.eaaf.modules.pvp2.impl.validation.TrustEngineFactory; +import at.gv.egiz.eaaf.modules.pvp2.impl.verification.SamlVerificationEngine; +import org.apache.commons.lang.StringEscapeUtils; +import org.apache.commons.lang3.StringUtils; +import org.joda.time.DateTime; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.AuthnRequest; +import org.opensaml.saml2.core.Issuer; +import org.opensaml.saml2.core.NameIDType; +import org.opensaml.saml2.core.Response; +import org.opensaml.saml2.core.Status; +import org.opensaml.saml2.core.StatusCode; +import org.opensaml.saml2.core.StatusMessage; +import org.opensaml.saml2.metadata.AssertionConsumerService; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.SPSSODescriptor; +import org.opensaml.ws.security.SecurityPolicyException; +import org.opensaml.xml.security.x509.X509Credential; +import org.opensaml.xml.signature.SignableXMLObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +public abstract class AbstractPvp2XProtocol extends AbstractController implements IModulInfo { + private static final Logger log = LoggerFactory.getLogger(AbstractPvp2XProtocol.class); + + @Autowired(required = true) + protected IPvo2BasicConfiguration pvpBasicConfiguration; + @Autowired(required = true) + protected IPvpMetadataProvider metadataProvider; + @Autowired(required = true) + protected SamlVerificationEngine samlVerificationEngine; + @Autowired(required = true) + protected IAuthnRequestValidator authRequestValidator; + + private AbstractCredentialProvider pvpIdpCredentials; + + + + /** + * Sets a specific credential provider for PVP S-Profile IDP component. + * + * @param pvpIdpCredentials credential provider + */ + public void setPvpIdpCredentials(final AbstractCredentialProvider pvpIdpCredentials) { + this.pvpIdpCredentials = pvpIdpCredentials; + + } + + @Override + public boolean generateErrorMessage(final Throwable e, final HttpServletRequest request, + final HttpServletResponse response, final IRequest protocolRequest) throws Throwable { + + if (protocolRequest == null) { + throw e; + } + + if (!(protocolRequest instanceof PvpSProfilePendingRequest)) { + throw e; + } + final PvpSProfilePendingRequest pvpRequest = (PvpSProfilePendingRequest) protocolRequest; + + final Response samlResponse = Saml2Utils.createSamlObject(Response.class); + final Status status = Saml2Utils.createSamlObject(Status.class); + final StatusCode statusCode = Saml2Utils.createSamlObject(StatusCode.class); + final StatusMessage statusMessage = Saml2Utils.createSamlObject(StatusMessage.class); + + String moaError = null; + + if (e instanceof NoPassivAuthenticationException) { + statusCode.setValue(StatusCode.NO_PASSIVE_URI); + statusMessage.setMessage(StringEscapeUtils.escapeXml(e.getLocalizedMessage())); + + } else if (e instanceof NameIdFormatNotSupportedException) { + statusCode.setValue(StatusCode.INVALID_NAMEID_POLICY_URI); + statusMessage.setMessage(StringEscapeUtils.escapeXml(e.getLocalizedMessage())); + + } else if (e instanceof SloException) { + // SLOExecpetions only occurs if session information is lost + return false; + + } else if (e instanceof Pvp2Exception) { + final Pvp2Exception ex = (Pvp2Exception) e; + statusCode.setValue(ex.getStatusCodeValue()); + final String statusMessageValue = ex.getStatusMessageValue(); + if (statusMessageValue != null) { + statusMessage.setMessage(StringEscapeUtils.escapeXml(statusMessageValue)); + } + moaError = statusMessager.mapInternalErrorToExternalError(ex.getErrorId()); + + } else { + statusCode.setValue(StatusCode.RESPONDER_URI); + statusMessage.setMessage(StringEscapeUtils.escapeXml(e.getLocalizedMessage())); + moaError = statusMessager.getResponseErrorCode(e); + } + + + if (StringUtils.isNotEmpty(moaError)) { + final StatusCode moaStatusCode = Saml2Utils.createSamlObject(StatusCode.class); + moaStatusCode.setValue(moaError); + statusCode.setStatusCode(moaStatusCode); + } + + status.setStatusCode(statusCode); + if (statusMessage.getMessage() != null) { + status.setStatusMessage(statusMessage); + } + samlResponse.setStatus(status); + final String remoteSessionID = Saml2Utils.getSecureIdentifier(); + samlResponse.setID(remoteSessionID); + + samlResponse.setIssueInstant(new DateTime()); + final Issuer nissuer = Saml2Utils.createSamlObject(Issuer.class); + nissuer.setValue(pvpBasicConfiguration.getIdpEntityId(pvpRequest.getAuthUrl())); + nissuer.setFormat(NameIDType.ENTITY); + samlResponse.setIssuer(nissuer); + + IEncoder encoder = null; + + if (pvpRequest.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { + encoder = applicationContext.getBean("PVPRedirectBinding", RedirectBinding.class); + + } else if (pvpRequest.getBinding().equals(SAMLConstants.SAML2_POST_BINDING_URI)) { + encoder = applicationContext.getBean("PVPPOSTBinding", PostBinding.class); + + } else if (pvpRequest.getBinding().equals(SAMLConstants.SAML2_SOAP11_BINDING_URI)) { + encoder = applicationContext.getBean("PVPSOAPBinding", SoapBinding.class); + } + + if (encoder == null) { + // default to redirect binding + encoder = new RedirectBinding(); + } + + String relayState = null; + if (pvpRequest.getRequest() != null) { + relayState = pvpRequest.getRequest().getRelayState(); + } + + final X509Credential signCred = pvpIdpCredentials.getIdpAssertionSigningCredential(); + + encoder.encodeRespone(request, response, samlResponse, pvpRequest.getConsumerUrl(), relayState, + signCred, protocolRequest); + return true; + } + + @Override + public boolean validate(final HttpServletRequest request, final HttpServletResponse response, + final IRequest pending) { + + return true; + } + + protected void pvpMetadataRequest(final HttpServletRequest req, final HttpServletResponse resp) + throws EaafException { + // create pendingRequest object + final PvpSProfilePendingRequest pendingReq = + applicationContext.getBean(PvpSProfilePendingRequest.class); + pendingReq.initialize(req, authConfig); + pendingReq.setModule(getName()); + + revisionsLogger.logEvent(pendingReq.getUniqueSessionIdentifier(), + pendingReq.getUniqueTransactionIdentifier(), EventConstants.TRANSACTION_IP, + req.getRemoteAddr()); + + final MetadataAction metadataAction = applicationContext.getBean(MetadataAction.class); + metadataAction.processRequest(pendingReq, req, resp, null); + + } + + protected void pvpIdpPostRequest(final HttpServletRequest req, final HttpServletResponse resp) + throws EaafException { + PvpSProfilePendingRequest pendingReq = null; + + try { + // create pendingRequest object + pendingReq = applicationContext.getBean(PvpSProfilePendingRequest.class); + pendingReq.initialize(req, authConfig); + pendingReq.setModule(getName()); + + revisionsLogger.logEvent(EventConstants.SESSION_CREATED, + pendingReq.getUniqueSessionIdentifier()); + revisionsLogger.logEvent(EventConstants.TRANSACTION_CREATED, + pendingReq.getUniqueTransactionIdentifier()); + revisionsLogger.logEvent(pendingReq.getUniqueSessionIdentifier(), + pendingReq.getUniqueTransactionIdentifier(), EventConstants.TRANSACTION_IP, + req.getRemoteAddr()); + + // get POST-Binding decoder implementation + final InboundMessage msg = (InboundMessage) new PostBinding().decode(req, resp, + metadataProvider, false, + new EaafUriCompare(pvpBasicConfiguration.getIdpSsoPostService(pendingReq.getAuthUrl()))); + pendingReq.setRequest(msg); + + // preProcess Message + preProcess(req, resp, pendingReq); + + } catch (final SecurityPolicyException e) { + final String samlRequest = req.getParameter("SAMLRequest"); + log.warn("Receive INVALID protocol request: " + samlRequest, e); + + // write revision log entries + if (pendingReq != null) { + revisionsLogger.logEvent(pendingReq, EventConstants.TRANSACTION_ERROR, + pendingReq.getUniqueTransactionIdentifier()); + } + + throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); + + } catch (final SecurityException e) { + final String samlRequest = req.getParameter("SAMLRequest"); + log.warn("Receive INVALID protocol request: " + samlRequest, e); + + // write revision log entries + if (pendingReq != null) { + revisionsLogger.logEvent(pendingReq, EventConstants.TRANSACTION_ERROR, + pendingReq.getUniqueTransactionIdentifier()); + } + + throw new InvalidProtocolRequestException("pvp2.22", new Object[] {e.getMessage()}); + + } catch (final EaafException e) { + + // write revision log entries + if (pendingReq != null) { + revisionsLogger.logEvent(pendingReq, EventConstants.TRANSACTION_ERROR, + pendingReq.getUniqueTransactionIdentifier()); + } + + throw e; + + } catch (final Throwable e) { + final String samlRequest = req.getParameter("SAMLRequest"); + log.warn("Receive INVALID protocol request: " + samlRequest, e); + + // write revision log entries + if (pendingReq != null) { + revisionsLogger.logEvent(pendingReq, EventConstants.TRANSACTION_ERROR, + pendingReq.getUniqueTransactionIdentifier()); + } + + throw new EaafException("pvp2.24", new Object[] {e.getMessage()}, e); + } + } + + protected void pvpIdpRedirecttRequest(final HttpServletRequest req, + final HttpServletResponse resp) throws EaafException { + PvpSProfilePendingRequest pendingReq = null; + try { + // create pendingRequest object + pendingReq = applicationContext.getBean(PvpSProfilePendingRequest.class); + pendingReq.initialize(req, authConfig); + pendingReq.setModule(getName()); + + revisionsLogger.logEvent(EventConstants.SESSION_CREATED, + pendingReq.getUniqueSessionIdentifier()); + revisionsLogger.logEvent(EventConstants.TRANSACTION_CREATED, + pendingReq.getUniqueTransactionIdentifier()); + revisionsLogger.logEvent(pendingReq.getUniqueSessionIdentifier(), + pendingReq.getUniqueTransactionIdentifier(), EventConstants.TRANSACTION_IP, + req.getRemoteAddr()); + + // get POST-Binding decoder implementation + final InboundMessage msg = (InboundMessage) new RedirectBinding().decode(req, resp, + metadataProvider, false, new EaafUriCompare( + pvpBasicConfiguration.getIdpSsoRedirectService(pendingReq.getAuthUrl()))); + pendingReq.setRequest(msg); + + // preProcess Message + preProcess(req, resp, pendingReq); + + } catch (final SecurityPolicyException e) { + final String samlRequest = req.getParameter("SAMLRequest"); + log.warn("Receive INVALID protocol request: " + samlRequest, e); + + // write revision log entries + if (pendingReq != null) { + revisionsLogger.logEvent(pendingReq, EventConstants.TRANSACTION_ERROR, + pendingReq.getUniqueTransactionIdentifier()); + } + + throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); + + } catch (final SecurityException e) { + final String samlRequest = req.getParameter("SAMLRequest"); + log.warn("Receive INVALID protocol request: " + samlRequest, e); + + // write revision log entries + if (pendingReq != null) { + revisionsLogger.logEvent(pendingReq, EventConstants.TRANSACTION_ERROR, + pendingReq.getUniqueTransactionIdentifier()); + } + + throw new InvalidProtocolRequestException("pvp2.22", new Object[] {e.getMessage()}); + + } catch (final EaafException e) { + final String samlRequest = req.getParameter("SAMLRequest"); + log.info("Receive INVALID protocol request: " + samlRequest); + + // write revision log entries + if (pendingReq != null) { + revisionsLogger.logEvent(pendingReq, EventConstants.TRANSACTION_ERROR, + pendingReq.getUniqueTransactionIdentifier()); + } + + throw e; + + } catch (final Throwable e) { + final String samlRequest = req.getParameter("SAMLRequest"); + log.warn("Receive INVALID protocol request: " + samlRequest, e); + + // write revision log entries + if (pendingReq != null) { + revisionsLogger.logEvent(pendingReq, EventConstants.TRANSACTION_ERROR, + pendingReq.getUniqueTransactionIdentifier()); + } + + throw new EaafException("pvp2.24", new Object[] {e.getMessage()}, e); + } + } + + + + /** + * Authentication request pre-processor. + * + * @param request http request + * @param response http response + * @param pendingReq current pending request + * @return true if preprocess can handle this request type, otherwise false + * @throws Throwable In case of an error + */ + protected abstract boolean childPreProcess(HttpServletRequest request, + HttpServletResponse response, PvpSProfilePendingRequest pendingReq) throws Throwable; + + protected void preProcess(final HttpServletRequest request, final HttpServletResponse response, + final PvpSProfilePendingRequest pendingReq) throws Throwable { + + final InboundMessage msg = pendingReq.getRequest(); + + if (StringUtils.isEmpty(msg.getEntityID())) { + throw new InvalidProtocolRequestException("pvp2.20", new Object[] {}); + + } + + if (!msg.isVerified()) { + samlVerificationEngine.verify(msg, + TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider)); + msg.setVerified(true); + + } + + revisionsLogger.logEvent(pendingReq, IRevisionLogger.AUTHPROTOCOL_TYPE, + getAuthProtocolIdentifier()); + + if (msg instanceof PvpSProfileRequest + && ((PvpSProfileRequest) msg).getSamlRequest() instanceof AuthnRequest) { + preProcessAuthRequest(request, response, pendingReq); + } else if (childPreProcess(request, response, pendingReq)) { + log.debug("Find protocol handler in child implementation"); + } else { + log.error("Receive unsupported PVP21 message of type: " + + ((PvpSProfileRequest) msg).getSamlRequest().getClass().getName()); + throw new InvalidPvpRequestException("pvp2.09", + new Object[] {((PvpSProfileRequest) msg).getSamlRequest().getClass().getName()}); + } + + + + // switch to session authentication + protAuthService.performAuthentication(request, response, pendingReq); + } + + + /** + * PreProcess Authn request. + * + * @param request http request + * @param response http response + * @param pendingReq current pending request + * @throws Throwable in case of an error + */ + private void preProcessAuthRequest(final HttpServletRequest request, + final HttpServletResponse response, final PvpSProfilePendingRequest pendingReq) + throws Throwable { + + final PvpSProfileRequest moaRequest = ((PvpSProfileRequest) pendingReq.getRequest()); + final SignableXMLObject samlReq = moaRequest.getSamlRequest(); + + if (!(samlReq instanceof AuthnRequest)) { + throw new InvalidPvpRequestException("Unsupported request", new Object[] {}); + } + + final EntityDescriptor metadata = moaRequest.getEntityMetadata(metadataProvider); + if (metadata == null) { + throw new NoMetadataInformationException(); + } + final SPSSODescriptor spSsoDescriptor = metadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS); + + final AuthnRequest authnRequest = (AuthnRequest) samlReq; + + if (authnRequest.getIssueInstant() == null) { + log.warn("Unsupported request: No IssueInstant Attribute found."); + throw new AuthnRequestValidatorException("pvp2.22", + new Object[] {"Unsupported request: No IssueInstant Attribute found"}, pendingReq); + + } + + if (authnRequest.getIssueInstant().minusMinutes(EAAFConstants.ALLOWED_TIME_JITTER) + .isAfterNow()) { + log.warn("Unsupported request: No IssueInstant DateTime is not valid anymore."); + throw new AuthnRequestValidatorException("pvp2.22", + new Object[] {"Unsupported request: No IssueInstant DateTime is not valid anymore."}, + pendingReq); + + } + + // parse AssertionConsumerService + AssertionConsumerService consumerService = null; + if (StringUtils.isNotEmpty(authnRequest.getAssertionConsumerServiceURL()) + && StringUtils.isNotEmpty(authnRequest.getProtocolBinding())) { + // use AssertionConsumerServiceURL from request + + // check requested AssertionConsumingService URL against metadata + final List metadataAssertionServiceList = + spSsoDescriptor.getAssertionConsumerServices(); + for (final AssertionConsumerService service : metadataAssertionServiceList) { + if (authnRequest.getProtocolBinding().equals(service.getBinding()) + && authnRequest.getAssertionConsumerServiceURL().equals(service.getLocation())) { + consumerService = Saml2Utils.createSamlObject(AssertionConsumerService.class); + consumerService.setBinding(authnRequest.getProtocolBinding()); + consumerService.setLocation(authnRequest.getAssertionConsumerServiceURL()); + log.debug("Requested AssertionConsumerServiceURL is valid."); + } + } + + if (consumerService == null) { + throw new InvalidAssertionConsumerServiceException( + authnRequest.getAssertionConsumerServiceURL()); + + } + + + } else { + // use AssertionConsumerServiceIndex and select consumerService from metadata + final Integer aIdx = authnRequest.getAssertionConsumerServiceIndex(); + int assertionidx = 0; + + if (aIdx != null) { + assertionidx = aIdx.intValue(); + + } else { + assertionidx = Saml2Utils.getDefaultAssertionConsumerServiceIndex(spSsoDescriptor); + + } + consumerService = spSsoDescriptor.getAssertionConsumerServices().get(assertionidx); + + if (consumerService == null) { + throw new InvalidAssertionConsumerServiceException(aIdx); + + } + } + + + // validate AuthnRequest + final AuthnRequest authReq = (AuthnRequest) samlReq; + final String oaUrl = moaRequest.getEntityMetadata(metadataProvider).getEntityID(); + log.info( + "Dispatch PVP2 AuthnRequest: OAURL=" + oaUrl + " Binding=" + consumerService.getBinding()); + + pendingReq.setSpEntityId(StringEscapeUtils.escapeHtml(oaUrl)); + pendingReq.setOnlineApplicationConfiguration( + authConfig.getServiceProviderConfiguration(pendingReq.getSpEntityId())); + pendingReq.setBinding(consumerService.getBinding()); + pendingReq.setRequest(moaRequest); + pendingReq.setConsumerUrl(consumerService.getLocation()); + + // parse AuthRequest + pendingReq.setPassiv(authReq.isPassive()); + pendingReq.setForce(authReq.isForceAuthn()); + + // AuthnRequest needs authentication + pendingReq.setNeedAuthentication(true); + + // set protocol action, which should be executed after authentication + pendingReq.setAction(AuthenticationAction.class.getName()); + + log.trace("Starting extended AuthnRequest validation and processing ... "); + authRequestValidator.validate(request, pendingReq, authReq, spSsoDescriptor); + log.debug("Extended AuthnRequest validation and processing finished"); + + // write revisionslog entry + revisionsLogger.logEvent(pendingReq, PvpEventConstants.AUTHPROTOCOL_PVP_REQUEST_AUTHREQUEST, + authReq.getID()); + + } + + @PostConstruct + private void verifyInitialization() { + if (pvpIdpCredentials == null) { + log.error("No SAML2 credentialProvider injected!"); + throw new RuntimeException("No SAML2 credentialProvider injected!"); + + } + } + +} diff --git a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/AuthenticationAction.java b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/AuthenticationAction.java index cbbed659..9378b579 100644 --- a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/AuthenticationAction.java +++ b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/AuthenticationAction.java @@ -1,35 +1,47 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.idp.impl; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.idp.IAction; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.api.idp.slo.SloInformationInterface; +import at.gv.egiz.eaaf.core.api.logging.IRevisionLogger; +import at.gv.egiz.eaaf.core.exceptions.EaafException; +import at.gv.egiz.eaaf.core.impl.data.SLOInformationImpl; +import at.gv.egiz.eaaf.modules.pvp2.api.IPvo2BasicConfiguration; +import at.gv.egiz.eaaf.modules.pvp2.api.binding.IEncoder; +import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPvpMetadataProvider; +import at.gv.egiz.eaaf.modules.pvp2.exception.BindingNotSupportedException; +import at.gv.egiz.eaaf.modules.pvp2.idp.exception.ResponderErrorException; +import at.gv.egiz.eaaf.modules.pvp2.idp.impl.builder.AuthResponseBuilder; +import at.gv.egiz.eaaf.modules.pvp2.idp.impl.builder.Pvp2AssertionBuilder; +import at.gv.egiz.eaaf.modules.pvp2.impl.binding.PostBinding; +import at.gv.egiz.eaaf.modules.pvp2.impl.binding.RedirectBinding; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.PvpSProfileRequest; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.AbstractCredentialProvider; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.Saml2Utils; import org.joda.time.DateTime; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.core.Assertion; @@ -45,141 +57,125 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Service; -import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.core.api.idp.IAction; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.api.idp.slo.SLOInformationInterface; -import at.gv.egiz.eaaf.core.api.logging.IRevisionLogger; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.core.impl.data.SLOInformationImpl; -import at.gv.egiz.eaaf.modules.pvp2.api.IPVP2BasicConfiguration; -import at.gv.egiz.eaaf.modules.pvp2.api.binding.IEncoder; -import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPVPMetadataProvider; -import at.gv.egiz.eaaf.modules.pvp2.exception.BindingNotSupportedException; -import at.gv.egiz.eaaf.modules.pvp2.idp.exception.ResponderErrorException; -import at.gv.egiz.eaaf.modules.pvp2.idp.impl.builder.AuthResponseBuilder; -import at.gv.egiz.eaaf.modules.pvp2.idp.impl.builder.PVP2AssertionBuilder; -import at.gv.egiz.eaaf.modules.pvp2.impl.binding.PostBinding; -import at.gv.egiz.eaaf.modules.pvp2.impl.binding.RedirectBinding; -import at.gv.egiz.eaaf.modules.pvp2.impl.message.PVPSProfileRequest; -import at.gv.egiz.eaaf.modules.pvp2.impl.utils.AbstractCredentialProvider; -import at.gv.egiz.eaaf.modules.pvp2.impl.utils.SAML2Utils; - @Service("PVPAuthenticationRequestAction") public class AuthenticationAction implements IAction { - private static final Logger log = LoggerFactory.getLogger(AuthenticationAction.class); - - private static final String CONFIG_PROPERTY_PVP2_ENABLE_ENCRYPTION = "protocols.pvp2.assertion.encryption.active"; - - @Autowired(required=true) private IPVPMetadataProvider metadataProvider; - @Autowired(required=true) ApplicationContext springContext; - @Autowired(required=true) IConfiguration authConfig; - @Autowired(required=true) PVP2AssertionBuilder assertionBuilder; - @Autowired(required=true) IPVP2BasicConfiguration pvpBasicConfiguration; - @Autowired(required=true) IRevisionLogger revisionsLogger; - - private AbstractCredentialProvider pvpIDPCredentials; - - /** - * Sets a specific credential provider for PVP S-Profile IDP component. - * @param pvpIDPCredentials credential provider - */ - public void setPvpIDPCredentials(AbstractCredentialProvider pvpIDPCredentials) { - this.pvpIDPCredentials = pvpIDPCredentials; - - } - - @Override - public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, - HttpServletResponse httpResp, IAuthData authData) throws ResponderErrorException { - final PVPSProfilePendingRequest pvpRequest = (PVPSProfilePendingRequest) req; - try { - //get basic information - final PVPSProfileRequest moaRequest = (PVPSProfileRequest) pvpRequest.getRequest(); - final AuthnRequest authnRequest = (AuthnRequest) moaRequest.getSamlRequest(); - final EntityDescriptor peerEntity = moaRequest.getEntityMetadata(metadataProvider); - - final AssertionConsumerService consumerService = - SAML2Utils.createSAMLObject(AssertionConsumerService.class); - consumerService.setBinding(pvpRequest.getBinding()); - consumerService.setLocation(pvpRequest.getConsumerURL()); - - final DateTime date = new DateTime(); - final SLOInformationImpl sloInformation = new SLOInformationImpl(); - final String issuerEntityID = pvpBasicConfiguration.getIDPEntityId(pvpRequest.getAuthURL()); - - //build Assertion - final Assertion assertion = assertionBuilder.buildAssertion(issuerEntityID, pvpRequest, authnRequest, authData, - peerEntity, date, consumerService, sloInformation); - - final Response authResponse = AuthResponseBuilder.buildResponse( - metadataProvider, issuerEntityID, authnRequest, - date, assertion, authConfig.getBasicConfigurationBoolean( - CONFIG_PROPERTY_PVP2_ENABLE_ENCRYPTION, true)); - - IEncoder binding = null; - - if (consumerService.getBinding().equals( - SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { - binding = springContext.getBean("PVPRedirectBinding", RedirectBinding.class); - - } else if (consumerService.getBinding().equals( - SAMLConstants.SAML2_POST_BINDING_URI)) { - binding = springContext.getBean("PVPPOSTBinding", PostBinding.class); - - } - - if (binding == null) { - throw new BindingNotSupportedException(consumerService.getBinding()); - } - - binding.encodeRespone(httpReq, httpResp, authResponse, - consumerService.getLocation(), moaRequest.getRelayState(), - pvpIDPCredentials.getIDPAssertionSigningCredential(), req); - - revisionsLogger.logEvent(req, 3105, authResponse.getID()); - - //set protocol type - sloInformation.setProtocolType(req.requestedModule()); - sloInformation.setSpEntityID(req.getServiceProviderConfiguration().getUniqueIdentifier()); - return sloInformation; - - } catch (MessageEncodingException | SecurityException e) { - log.warn("Message Encoding exception", e); - throw new ResponderErrorException("pvp2.01", null, e); - - } catch (final EAAFException e) { - log.info("Response generation error: Msg: ", e.getMessage()); - throw new ResponderErrorException(e.getErrorId(), e.getParams(), e); - - } catch (final Exception e) { - log.warn("Response generation error", e); - throw new ResponderErrorException("pvp2.01", null, e); - - } - - } - - @Override - public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, - HttpServletResponse httpResp) { - return true; - } - - @Override - public String getDefaultActionName() { - return "PVPAuthenticationRequestAction"; - - } - - @PostConstruct - private void verifyInitialization() { - if (pvpIDPCredentials == null) { - log.error("No SAML2 credentialProvider injected!"); - throw new RuntimeException("No SAML2 credentialProvider injected!"); - - } - } + private static final Logger log = LoggerFactory.getLogger(AuthenticationAction.class); + + private static final String CONFIG_PROPERTY_PVP2_ENABLE_ENCRYPTION = + "protocols.pvp2.assertion.encryption.active"; + + @Autowired(required = true) + private IPvpMetadataProvider metadataProvider; + @Autowired(required = true) + ApplicationContext springContext; + @Autowired(required = true) + IConfiguration authConfig; + @Autowired(required = true) + Pvp2AssertionBuilder assertionBuilder; + @Autowired(required = true) + IPvo2BasicConfiguration pvpBasicConfiguration; + @Autowired(required = true) + IRevisionLogger revisionsLogger; + + private AbstractCredentialProvider pvpIdpCredentials; + + /** + * Sets a specific credential provider for PVP S-Profile IDP component. + * + * @param pvpIdpCredentials credential provider + */ + public void setPvpIdpCredentials(final AbstractCredentialProvider pvpIdpCredentials) { + this.pvpIdpCredentials = pvpIdpCredentials; + + } + + @Override + public SloInformationInterface processRequest(final IRequest req, + final HttpServletRequest httpReq, final HttpServletResponse httpResp, + final IAuthData authData) throws ResponderErrorException { + final PvpSProfilePendingRequest pvpRequest = (PvpSProfilePendingRequest) req; + try { + // get basic information + final PvpSProfileRequest moaRequest = (PvpSProfileRequest) pvpRequest.getRequest(); + final AuthnRequest authnRequest = (AuthnRequest) moaRequest.getSamlRequest(); + final EntityDescriptor peerEntity = moaRequest.getEntityMetadata(metadataProvider); + + final AssertionConsumerService consumerService = + Saml2Utils.createSamlObject(AssertionConsumerService.class); + consumerService.setBinding(pvpRequest.getBinding()); + consumerService.setLocation(pvpRequest.getConsumerUrl()); + + final DateTime date = new DateTime(); + final SLOInformationImpl sloInformation = new SLOInformationImpl(); + final String issuerEntityID = pvpBasicConfiguration.getIdpEntityId(pvpRequest.getAuthUrl()); + + // build Assertion + final Assertion assertion = assertionBuilder.buildAssertion(issuerEntityID, pvpRequest, + authnRequest, authData, peerEntity, date, consumerService, sloInformation); + + final Response authResponse = AuthResponseBuilder.buildResponse(metadataProvider, + issuerEntityID, authnRequest, date, assertion, + authConfig.getBasicConfigurationBoolean(CONFIG_PROPERTY_PVP2_ENABLE_ENCRYPTION, true)); + + IEncoder binding = null; + + if (consumerService.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { + binding = springContext.getBean("PVPRedirectBinding", RedirectBinding.class); + + } else if (consumerService.getBinding().equals(SAMLConstants.SAML2_POST_BINDING_URI)) { + binding = springContext.getBean("PVPPOSTBinding", PostBinding.class); + + } + + if (binding == null) { + throw new BindingNotSupportedException(consumerService.getBinding()); + } + + binding.encodeRespone(httpReq, httpResp, authResponse, consumerService.getLocation(), + moaRequest.getRelayState(), pvpIdpCredentials.getIdpAssertionSigningCredential(), req); + + revisionsLogger.logEvent(req, 3105, authResponse.getID()); + + // set protocol type + sloInformation.setProtocolType(req.requestedModule()); + sloInformation.setSpEntityID(req.getServiceProviderConfiguration().getUniqueIdentifier()); + return sloInformation; + + } catch (MessageEncodingException | SecurityException e) { + log.warn("Message Encoding exception", e); + throw new ResponderErrorException("pvp2.01", null, e); + + } catch (final EaafException e) { + log.info("Response generation error: Msg: ", e.getMessage()); + throw new ResponderErrorException(e.getErrorId(), e.getParams(), e); + + } catch (final Exception e) { + log.warn("Response generation error", e); + throw new ResponderErrorException("pvp2.01", null, e); + + } + + } + + @Override + public boolean needAuthentication(final IRequest req, final HttpServletRequest httpReq, + final HttpServletResponse httpResp) { + return true; + } + + @Override + public String getDefaultActionName() { + return "PVPAuthenticationRequestAction"; + + } + + @PostConstruct + private void verifyInitialization() { + if (pvpIdpCredentials == null) { + log.error("No SAML2 credentialProvider injected!"); + throw new RuntimeException("No SAML2 credentialProvider injected!"); + + } + } } diff --git a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/MetadataAction.java b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/MetadataAction.java index 6b957522..a1e8b5ba 100644 --- a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/MetadataAction.java +++ b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/MetadataAction.java @@ -1,123 +1,121 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.idp.impl; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.MediaType; -import org.springframework.stereotype.Service; - import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.idp.IAction; import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.slo.SLOInformationInterface; +import at.gv.egiz.eaaf.core.api.idp.slo.SloInformationInterface; import at.gv.egiz.eaaf.core.api.logging.IRevisionLogger; -import at.gv.egiz.eaaf.modules.pvp2.PVPEventConstants; -import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPVPMetadataBuilderConfiguration; -import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPVPMetadataConfigurationFactory; -import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2MetadataException; -import at.gv.egiz.eaaf.modules.pvp2.impl.builder.PVPMetadataBuilder; +import at.gv.egiz.eaaf.modules.pvp2.PvpEventConstants; +import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPvpMetadataBuilderConfiguration; +import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPvpMetadataConfigurationFactory; +import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2MetadataException; +import at.gv.egiz.eaaf.modules.pvp2.impl.builder.PvpMetadataBuilder; import at.gv.egiz.eaaf.modules.pvp2.impl.utils.AbstractCredentialProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Service; @Service("pvpMetadataService") public class MetadataAction implements IAction { - private static final Logger log = LoggerFactory.getLogger(MetadataAction.class); - - @Autowired private IRevisionLogger revisionsLogger; - @Autowired private PVPMetadataBuilder metadatabuilder; - @Autowired private IPVPMetadataConfigurationFactory configFactory; - - private AbstractCredentialProvider pvpIDPCredentials; - - /** - * Sets a specific credential provider for PVP S-Profile IDP component. - * @param pvpIDPCredentials credential provider - */ - public void setPvpIDPCredentials(AbstractCredentialProvider pvpIDPCredentials) { - this.pvpIDPCredentials = pvpIDPCredentials; - - } - - public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, - HttpServletResponse httpResp, IAuthData authData) throws PVP2MetadataException { - try { - revisionsLogger.logEvent(req, PVPEventConstants.AUTHPROTOCOL_PVP_METADATA); - - //build metadata - IPVPMetadataBuilderConfiguration metadataConfig = - configFactory.generateMetadataBuilderConfiguration( - req.getAuthURLWithOutSlash(), - pvpIDPCredentials); - - ; - - String metadataXML = metadatabuilder.buildPVPMetadata(metadataConfig); - log.debug("METADATA: " + metadataXML); - - byte[] content = metadataXML.getBytes("UTF-8"); - httpResp.setStatus(HttpServletResponse.SC_OK); - httpResp.setContentLength(content.length); - httpResp.setContentType(MediaType.APPLICATION_XML_VALUE); - httpResp.getOutputStream().write(content); - return null; - - } catch (Exception e) { - log.error("Failed to generate metadata", e); - throw new PVP2MetadataException("pvp2.27", null); - } - } - - public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, - HttpServletResponse httpResp) { - return false; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IAction#getDefaultActionName() - */ - @Override - public String getDefaultActionName() { - return "IDP - PVP Metadata action"; - } - - @PostConstruct - private void verifyInitialization() { - if (pvpIDPCredentials == null) { - log.error("No SAML2 credentialProvider injected!"); - throw new RuntimeException("No SAML2 credentialProvider injected!"); - - } - } - + private static final Logger log = LoggerFactory.getLogger(MetadataAction.class); + + @Autowired + private IRevisionLogger revisionsLogger; + @Autowired + private PvpMetadataBuilder metadatabuilder; + @Autowired + private IPvpMetadataConfigurationFactory configFactory; + + private AbstractCredentialProvider pvpIdpCredentials; + + /** + * Sets a specific credential provider for PVP S-Profile IDP component. + * + * @param pvpIdpCredentials credential provider + */ + public void setPvpIdpCredentials(final AbstractCredentialProvider pvpIdpCredentials) { + this.pvpIdpCredentials = pvpIdpCredentials; + + } + + @Override + public SloInformationInterface processRequest(final IRequest req, + final HttpServletRequest httpReq, final HttpServletResponse httpResp, + final IAuthData authData) throws Pvp2MetadataException { + try { + revisionsLogger.logEvent(req, PvpEventConstants.AUTHPROTOCOL_PVP_METADATA); + + // build metadata + final IPvpMetadataBuilderConfiguration metadataConfig = configFactory + .generateMetadataBuilderConfiguration(req.getAuthUrlWithOutSlash(), pvpIdpCredentials); + + + + final String metadataXml = metadatabuilder.buildPvpMetadata(metadataConfig); + log.trace("METADATA: " + metadataXml); + + final byte[] content = metadataXml.getBytes("UTF-8"); + httpResp.setStatus(HttpServletResponse.SC_OK); + httpResp.setContentLength(content.length); + httpResp.setContentType(MediaType.APPLICATION_XML_VALUE); + httpResp.getOutputStream().write(content); + return null; + + } catch (final Exception e) { + log.error("Failed to generate metadata", e); + throw new Pvp2MetadataException("pvp2.27", null); + } + } + + @Override + public boolean needAuthentication(final IRequest req, final HttpServletRequest httpReq, + final HttpServletResponse httpResp) { + return false; + } + + /* + * (non-Javadoc) + * + * @see at.gv.egovernment.moa.id.moduls.IAction#getDefaultActionName() + */ + @Override + public String getDefaultActionName() { + return "IDP - PVP Metadata action"; + } + + @PostConstruct + private void verifyInitialization() { + if (pvpIdpCredentials == null) { + log.error("No SAML2 credentialProvider injected!"); + throw new RuntimeException("No SAML2 credentialProvider injected!"); + + } + } + } diff --git a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/PVPSProfilePendingRequest.java b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/PVPSProfilePendingRequest.java deleted file mode 100644 index 7f086ff6..00000000 --- a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/PVPSProfilePendingRequest.java +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.idp.impl; - -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import at.gv.egiz.eaaf.core.impl.idp.controller.protocols.RequestImpl; -import at.gv.egiz.eaaf.modules.pvp2.impl.message.InboundMessage; - -@Component("PVPSProfilePendingRequest") -@Scope(value = BeanDefinition.SCOPE_PROTOTYPE) -public class PVPSProfilePendingRequest extends RequestImpl { - private static final long serialVersionUID = 4889919265919638188L; - - InboundMessage request; - String binding; - String consumerURL; - - public InboundMessage getRequest() { - return request; - } - - public void setRequest(InboundMessage request) { - this.request = request; - } - - public String getBinding() { - return binding; - } - - public void setBinding(String binding) { - this.binding = binding; - } - - public String getConsumerURL() { - return consumerURL; - } - - public void setConsumerURL(String consumerURL) { - this.consumerURL = consumerURL; - - } -} diff --git a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/PvpSProfilePendingRequest.java b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/PvpSProfilePendingRequest.java new file mode 100644 index 00000000..6c621841 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/PvpSProfilePendingRequest.java @@ -0,0 +1,61 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.idp.impl; + +import at.gv.egiz.eaaf.core.impl.idp.controller.protocols.RequestImpl; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.InboundMessage; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Component("PVPSProfilePendingRequest") +@Scope(value = BeanDefinition.SCOPE_PROTOTYPE) +public class PvpSProfilePendingRequest extends RequestImpl { + private static final long serialVersionUID = 4889919265919638188L; + + InboundMessage request; + String binding; + String consumerUrl; + + public InboundMessage getRequest() { + return request; + } + + public void setRequest(final InboundMessage request) { + this.request = request; + } + + public String getBinding() { + return binding; + } + + public void setBinding(final String binding) { + this.binding = binding; + } + + public String getConsumerUrl() { + return consumerUrl; + } + + public void setConsumerUrl(final String consumerUrl) { + this.consumerUrl = consumerUrl; + + } +} diff --git a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/builder/AuthResponseBuilder.java b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/builder/AuthResponseBuilder.java index 07423c19..bf51ac0f 100644 --- a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/builder/AuthResponseBuilder.java +++ b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/builder/AuthResponseBuilder.java @@ -1,41 +1,35 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.idp.impl.builder; import java.util.ArrayList; import java.util.List; - +import at.gv.egiz.eaaf.modules.pvp2.PvpConstants; +import at.gv.egiz.eaaf.modules.pvp2.idp.exception.InvalidAssertionEncryptionException; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.Saml2Utils; import org.joda.time.DateTime; -import org.opensaml.Configuration; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.core.Assertion; import org.opensaml.saml2.core.EncryptedAssertion; import org.opensaml.saml2.core.Issuer; -import org.opensaml.saml2.core.NameID; +import org.opensaml.saml2.core.NameIDType; import org.opensaml.saml2.core.RequestAbstractType; import org.opensaml.saml2.core.Response; import org.opensaml.saml2.encryption.Encrypter; @@ -57,97 +51,111 @@ import org.opensaml.xml.security.x509.X509Credential; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import at.gv.egiz.eaaf.modules.pvp2.PVPConstants; -import at.gv.egiz.eaaf.modules.pvp2.idp.exception.InvalidAssertionEncryptionException; -import at.gv.egiz.eaaf.modules.pvp2.impl.utils.SAML2Utils; - /** + * Authentication response builder. + * * @author tlenz * */ public class AuthResponseBuilder { - private static final Logger log = LoggerFactory.getLogger(AuthResponseBuilder.class); - - public static Response buildResponse(MetadataProvider metadataProvider, String issuerEntityID, RequestAbstractType req, DateTime date, Assertion assertion, boolean enableEncryption) throws InvalidAssertionEncryptionException { - Response authResponse = SAML2Utils.createSAMLObject(Response.class); - - Issuer nissuer = SAML2Utils.createSAMLObject(Issuer.class); - - nissuer.setValue(issuerEntityID); - nissuer.setFormat(NameID.ENTITY); - authResponse.setIssuer(nissuer); - authResponse.setInResponseTo(req.getID()); - - //set responseID - String remoteSessionID = SAML2Utils.getSecureIdentifier(); - authResponse.setID(remoteSessionID); - - - //SAML2 response required IssueInstant - authResponse.setIssueInstant(date); - - authResponse.setStatus(SAML2Utils.getSuccessStatus()); - - //check, if metadata includes an encryption key - MetadataCredentialResolver mdCredResolver = - new MetadataCredentialResolver(metadataProvider); - - CriteriaSet criteriaSet = new CriteriaSet(); - criteriaSet.add( new EntityIDCriteria(req.getIssuer().getValue()) ); - criteriaSet.add( new MetadataCriteria(SPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS) ); - criteriaSet.add( new UsageCriteria(UsageType.ENCRYPTION) ); - - X509Credential encryptionCredentials = null; - try { - encryptionCredentials = (X509Credential) mdCredResolver.resolveSingle(criteriaSet); - - } catch (SecurityException e2) { - log.warn("Can not extract the Assertion Encryption-Key from metadata", e2); - throw new InvalidAssertionEncryptionException(); - - } - - if (encryptionCredentials != null && enableEncryption) { - //encrypt SAML2 assertion - - try { - - EncryptionParameters dataEncParams = new EncryptionParameters(); - dataEncParams.setAlgorithm(PVPConstants.DEFAULT_SYM_ENCRYPTION_METHODE); - - List keyEncParamList = new ArrayList(); - KeyEncryptionParameters keyEncParam = new KeyEncryptionParameters(); - - keyEncParam.setEncryptionCredential(encryptionCredentials); - keyEncParam.setAlgorithm(PVPConstants.DEFAULT_ASYM_ENCRYPTION_METHODE); - KeyInfoGeneratorFactory kigf = Configuration.getGlobalSecurityConfiguration() - .getKeyInfoGeneratorManager().getDefaultManager() - .getFactory(encryptionCredentials); - keyEncParam.setKeyInfoGenerator(kigf.newInstance()); - keyEncParamList.add(keyEncParam); - - Encrypter samlEncrypter = new Encrypter(dataEncParams, keyEncParamList); - //samlEncrypter.setKeyPlacement(KeyPlacement.INLINE); - samlEncrypter.setKeyPlacement(KeyPlacement.PEER); - - EncryptedAssertion encryptAssertion = null; - - encryptAssertion = samlEncrypter.encrypt(assertion); - - authResponse.getEncryptedAssertions().add(encryptAssertion); - - } catch (EncryptionException e1) { - log.warn("Can not encrypt the PVP2 assertion", e1); - throw new InvalidAssertionEncryptionException(); - - } - - } else { - authResponse.getAssertions().add(assertion); - - } - - return authResponse; - } + private static final Logger log = LoggerFactory.getLogger(AuthResponseBuilder.class); + + /** + * Build PVP2 S-Profile authentication response. + * + * @param metadataProvider Service-Provider metadata + * @param issuerEntityID IDP entityId + * @param req current pending request + * @param date Timestamp + * @param assertion PVP2 S-Profil Assertion + * @param enableEncryption encrypt Assertion flag + * @return PVP2 S-Profile authentication response + * @throws InvalidAssertionEncryptionException In case of an error + */ + public static Response buildResponse(final MetadataProvider metadataProvider, + final String issuerEntityID, final RequestAbstractType req, final DateTime date, + final Assertion assertion, final boolean enableEncryption) + throws InvalidAssertionEncryptionException { + final Response authResponse = Saml2Utils.createSamlObject(Response.class); + + final Issuer nissuer = Saml2Utils.createSamlObject(Issuer.class); + + nissuer.setValue(issuerEntityID); + nissuer.setFormat(NameIDType.ENTITY); + authResponse.setIssuer(nissuer); + authResponse.setInResponseTo(req.getID()); + + // set responseID + final String remoteSessionID = Saml2Utils.getSecureIdentifier(); + authResponse.setID(remoteSessionID); + + + // SAML2 response required IssueInstant + authResponse.setIssueInstant(date); + + authResponse.setStatus(Saml2Utils.getSuccessStatus()); + + // check, if metadata includes an encryption key + final MetadataCredentialResolver mdCredResolver = + new MetadataCredentialResolver(metadataProvider); + + final CriteriaSet criteriaSet = new CriteriaSet(); + criteriaSet.add(new EntityIDCriteria(req.getIssuer().getValue())); + criteriaSet + .add(new MetadataCriteria(SPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS)); + criteriaSet.add(new UsageCriteria(UsageType.ENCRYPTION)); + + X509Credential encryptionCredentials = null; + try { + encryptionCredentials = (X509Credential) mdCredResolver.resolveSingle(criteriaSet); + + } catch (final SecurityException e2) { + log.warn("Can not extract the Assertion Encryption-Key from metadata", e2); + throw new InvalidAssertionEncryptionException(); + + } + + if (encryptionCredentials != null && enableEncryption) { + // encrypt SAML2 assertion + + try { + + final EncryptionParameters dataEncParams = new EncryptionParameters(); + dataEncParams.setAlgorithm(PvpConstants.DEFAULT_SYM_ENCRYPTION_METHODE); + + final List keyEncParamList = new ArrayList<>(); + final KeyEncryptionParameters keyEncParam = new KeyEncryptionParameters(); + + keyEncParam.setEncryptionCredential(encryptionCredentials); + keyEncParam.setAlgorithm(PvpConstants.DEFAULT_ASYM_ENCRYPTION_METHODE); + final KeyInfoGeneratorFactory kigf = + org.opensaml.xml.Configuration.getGlobalSecurityConfiguration() + .getKeyInfoGeneratorManager().getDefaultManager().getFactory(encryptionCredentials); + keyEncParam.setKeyInfoGenerator(kigf.newInstance()); + keyEncParamList.add(keyEncParam); + + final Encrypter samlEncrypter = new Encrypter(dataEncParams, keyEncParamList); + // samlEncrypter.setKeyPlacement(KeyPlacement.INLINE); + samlEncrypter.setKeyPlacement(KeyPlacement.PEER); + + EncryptedAssertion encryptAssertion = null; + + encryptAssertion = samlEncrypter.encrypt(assertion); + + authResponse.getEncryptedAssertions().add(encryptAssertion); + + } catch (final EncryptionException e1) { + log.warn("Can not encrypt the PVP2 assertion", e1); + throw new InvalidAssertionEncryptionException(); + + } + + } else { + authResponse.getAssertions().add(assertion); + + } + + return authResponse; + } } diff --git a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/builder/PVP2AssertionBuilder.java b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/builder/PVP2AssertionBuilder.java deleted file mode 100644 index 2ccc2c9e..00000000 --- a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/builder/PVP2AssertionBuilder.java +++ /dev/null @@ -1,459 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.idp.impl.builder; - -import java.security.MessageDigest; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.apache.commons.lang3.StringUtils; -import org.joda.time.DateTime; -import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.saml2.core.Assertion; -import org.opensaml.saml2.core.Attribute; -import org.opensaml.saml2.core.AttributeQuery; -import org.opensaml.saml2.core.AttributeStatement; -import org.opensaml.saml2.core.Audience; -import org.opensaml.saml2.core.AudienceRestriction; -import org.opensaml.saml2.core.AuthnContext; -import org.opensaml.saml2.core.AuthnContextClassRef; -import org.opensaml.saml2.core.AuthnRequest; -import org.opensaml.saml2.core.AuthnStatement; -import org.opensaml.saml2.core.Conditions; -import org.opensaml.saml2.core.Issuer; -import org.opensaml.saml2.core.NameID; -import org.opensaml.saml2.core.RequestedAuthnContext; -import org.opensaml.saml2.core.Subject; -import org.opensaml.saml2.core.SubjectConfirmation; -import org.opensaml.saml2.core.SubjectConfirmationData; -import org.opensaml.saml2.core.impl.AuthnRequestImpl; -import org.opensaml.saml2.metadata.AssertionConsumerService; -import org.opensaml.saml2.metadata.AttributeConsumingService; -import org.opensaml.saml2.metadata.EntityDescriptor; -import org.opensaml.saml2.metadata.NameIDFormat; -import org.opensaml.saml2.metadata.RequestedAttribute; -import org.opensaml.saml2.metadata.SPSSODescriptor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.util.Base64Utils; - -import at.gv.egiz.eaaf.core.api.data.EAAFConstants; -import at.gv.egiz.eaaf.core.api.data.ILoALevelMapper; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.api.idp.slo.SLOInformationInterface; -import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; -import at.gv.egiz.eaaf.core.impl.data.Pair; -import at.gv.egiz.eaaf.core.impl.idp.controller.protocols.RequestImpl; -import at.gv.egiz.eaaf.core.impl.utils.Random; -import at.gv.egiz.eaaf.modules.pvp2.PVPConstants; -import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; -import at.gv.egiz.eaaf.modules.pvp2.exception.QAANotSupportedException; -import at.gv.egiz.eaaf.modules.pvp2.idp.api.builder.ISubjectNameIdGenerator; -import at.gv.egiz.eaaf.modules.pvp2.idp.exception.ResponderErrorException; -import at.gv.egiz.eaaf.modules.pvp2.idp.exception.UnprovideableAttributeException; -import at.gv.egiz.eaaf.modules.pvp2.idp.impl.PVPSProfilePendingRequest; -import at.gv.egiz.eaaf.modules.pvp2.impl.builder.PVPAttributeBuilder; -import at.gv.egiz.eaaf.modules.pvp2.impl.utils.QAALevelVerifier; -import at.gv.egiz.eaaf.modules.pvp2.impl.utils.SAML2Utils; - -@Service("PVP2AssertionBuilder") -public class PVP2AssertionBuilder implements PVPConstants { - - private static final Logger log = LoggerFactory.getLogger(PVP2AssertionBuilder.class); - @Autowired private ILoALevelMapper loaLevelMapper; - @Autowired private ISubjectNameIdGenerator subjectNameIdGenerator; - - - /** - * Build a PVP assertion as response for a SAML2 AttributeQuery request - * - * @param issuerEntityID EnitiyID, which should be used for this IDP response - * @param attrQuery AttributeQuery request from Service-Provider - * @param attrList List of PVP response attributes - * @param now Current time - * @param validTo ValidTo time of the assertion - * @param qaaLevel QAA level of the authentication - * @param sessionIndex SAML2 SessionIndex, which should be included * - * @return PVP 2.1 Assertion - * @throws PVP2Exception - */ - public Assertion buildAssertion(String issuerEntityID, AttributeQuery attrQuery, - List attrList, DateTime now, DateTime validTo, String qaaLevel, String sessionIndex) throws PVP2Exception { - - AuthnContextClassRef authnContextClassRef = SAML2Utils.createSAMLObject(AuthnContextClassRef.class); - authnContextClassRef.setAuthnContextClassRef(qaaLevel); - - NameID subjectNameID = SAML2Utils.createSAMLObject(NameID.class); - subjectNameID.setFormat(attrQuery.getSubject().getNameID().getFormat()); - subjectNameID.setValue(attrQuery.getSubject().getNameID().getValue()); - - SubjectConfirmationData subjectConfirmationData = null; - - return buildGenericAssertion(issuerEntityID, attrQuery.getIssuer().getValue(), now, - authnContextClassRef, attrList, subjectNameID, subjectConfirmationData, sessionIndex, - validTo); - } - - - /** - * Build a PVP 2.1 assertion as response of a SAML2 AuthnRequest - * - * @param issuerEntityID EnitiyID, which should be used for this IDP response - * @param pendingReq Current processed pendingRequest DAO - * @param authnRequest Current processed PVP AuthnRequest - * @param authData AuthenticationData of the user, which is already authenticated - * @param peerEntity SAML2 EntityDescriptor of the service-provider, which receives the response - * @param date TimeStamp - * @param assertionConsumerService SAML2 endpoint of the service-provider, which should be used - * @param sloInformation Single LogOut information DAO - * @return - * @throws PVP2Exception - */ - public Assertion buildAssertion(String issuerEntityID, PVPSProfilePendingRequest pendingReq, AuthnRequest authnRequest, - IAuthData authData, EntityDescriptor peerEntity, DateTime date, - AssertionConsumerService assertionConsumerService, SLOInformationInterface sloInformation) - throws PVP2Exception { - - ISPConfiguration oaParam = pendingReq.getServiceProviderConfiguration(); - AuthnContextClassRef authnContextClassRef = SAML2Utils.createSAMLObject(AuthnContextClassRef.class); - - //check if authn. request contains LoA - RequestedAuthnContext reqAuthnContext = authnRequest.getRequestedAuthnContext(); - if (reqAuthnContext == null) { - authnContextClassRef.setAuthnContextClassRef(authData.getEIDASQAALevel()); - - } else { - //authn. request requests LoA levels. To LoA validation - List reqAuthnContextClassRefIt = reqAuthnContext.getAuthnContextClassRefs(); - - //get matching mode from authn. request - String loaMatchingMode = EAAFConstants.EIDAS_LOA_MATCHING_MINIMUM; - if (reqAuthnContext.getComparison() != null && - StringUtils.isNotEmpty(reqAuthnContext.getComparison().toString())) - loaMatchingMode = reqAuthnContext.getComparison().toString(); - - //get requested LoAs - if (reqAuthnContextClassRefIt.size() == 0) { - QAALevelVerifier.verifyQAALevel(authData.getEIDASQAALevel(), - oaParam.getRequiredLoA(), loaMatchingMode); - authnContextClassRef.setAuthnContextClassRef(authData.getEIDASQAALevel()); - - } else { - List eIDASLoaFromRequest = new ArrayList(); - for (AuthnContextClassRef authnClassRef : reqAuthnContextClassRefIt) { - String qaa_uri = authnClassRef.getAuthnContextClassRef(); - - if (!qaa_uri.trim().startsWith(EAAFConstants.EIDAS_LOA_PREFIX)) { - if (loaLevelMapper != null) { - log.debug("Find no eIDAS LoA in AuthnReq. Start mapping process ... " ); - eIDASLoaFromRequest.add(loaLevelMapper.mapToeIDASLoA(qaa_uri.trim())); - - } else - log.debug("AuthnRequest contains no eIDAS LoA. NO LoA mapper FOUND, ignore " - + "'" + qaa_uri.trim() + "'"); - } else - eIDASLoaFromRequest.add(qaa_uri.trim()); - - } - - //stop process if no supported LoA scheme is requested - if (eIDASLoaFromRequest.isEmpty()) { - log.info("Authn. request contains no supported LoA level. Stop authentication process ... "); - throw new QAANotSupportedException("No supported LoA in Authn. request"); - - } - - //verifiy LoAs from request to authentication LoA - QAALevelVerifier.verifyQAALevel(authData.getEIDASQAALevel(), eIDASLoaFromRequest , loaMatchingMode); - authnContextClassRef.setAuthnContextClassRef(authData.getEIDASQAALevel()); - - } - } - - - //load SPSS decriptor from service-provider metadata - SPSSODescriptor spSSODescriptor = peerEntity.getSPSSODescriptor(SAMLConstants.SAML20P_NS); - - //add Attributes to Assertion - List attrList = new ArrayList(); - if (spSSODescriptor.getAttributeConsumingServices() != null && - spSSODescriptor.getAttributeConsumingServices().size() > 0) { - - Integer aIdx = authnRequest.getAttributeConsumingServiceIndex(); - int idx = 0; - - AttributeConsumingService attributeConsumingService = null; - if (aIdx != null) { - idx = aIdx.intValue(); - attributeConsumingService = spSSODescriptor - .getAttributeConsumingServices().get(idx); - - } else { - List attrConsumingServiceList = spSSODescriptor.getAttributeConsumingServices(); - for (AttributeConsumingService el : attrConsumingServiceList) { - if (el.isDefault()) - attributeConsumingService = el; - } - } - - /* - * TODO: maybe use first AttributeConsumingService if no is selected - * in request or on service is marked as default - * - */ - if (attributeConsumingService == null ) { - List attrConsumingServiceList = spSSODescriptor.getAttributeConsumingServices(); - if (attrConsumingServiceList != null && !attrConsumingServiceList.isEmpty()) - attributeConsumingService = attrConsumingServiceList.get(0); - - } - - - if (attributeConsumingService != null) { - Iterator it = attributeConsumingService - .getRequestAttributes().iterator(); - while (it.hasNext()) { - RequestedAttribute reqAttribut = it.next(); - try { - Attribute attr = PVPAttributeBuilder.buildAttribute( - reqAttribut.getName(), oaParam, authData); - if (attr == null) { - if (reqAttribut.isRequired()) { - throw new UnprovideableAttributeException( - reqAttribut.getName()); - } - } else { - attrList.add(attr); - } - - } catch (UnavailableAttributeException e) { - log.info( - "Attribute generation for " - + reqAttribut.getFriendlyName() + " not possible."); - if (reqAttribut.isRequired()) { - throw new UnprovideableAttributeException( - reqAttribut.getName()); - } - - - } catch (PVP2Exception e) { - log.info( - "Attribute generation failed! for " - + reqAttribut.getFriendlyName()); - if (reqAttribut.isRequired()) { - throw new UnprovideableAttributeException( - reqAttribut.getName()); - } - - } catch (Exception e) { - log.warn( - "General Attribute generation failed! for " - + reqAttribut.getFriendlyName(), e); - if (reqAttribut.isRequired()) { - throw new UnprovideableAttributeException( - reqAttribut.getName()); - } - - } - } - } - } - - //generate subjectNameId - NameID subjectNameID = SAML2Utils.createSAMLObject(NameID.class); - Pair subjectNameIdPair = subjectNameIdGenerator.generateSubjectNameId(authData, oaParam); - subjectNameID.setValue(subjectNameIdPair.getFirst()); - subjectNameID.setNameQualifier(subjectNameIdPair.getSecond()); - - //get NameIDFormat from request - String nameIDFormat = NameID.TRANSIENT; - AuthnRequest authnReq = (AuthnRequestImpl) authnRequest; - if (authnReq.getNameIDPolicy() != null && - StringUtils.isNotEmpty(authnReq.getNameIDPolicy().getFormat())) { - nameIDFormat = authnReq.getNameIDPolicy().getFormat(); - - } else { - //get NameIDFormat from metadata - List metadataNameIDFormats = spSSODescriptor.getNameIDFormats(); - - if (metadataNameIDFormats != null) { - - for (NameIDFormat el : metadataNameIDFormats) { - if (NameID.PERSISTENT.equals(el.getFormat())) { - nameIDFormat = NameID.PERSISTENT; - break; - - } else if (NameID.TRANSIENT.equals(el.getFormat()) || - NameID.UNSPECIFIED.equals(el.getFormat())) - break; - - } - } - } - - if (NameID.TRANSIENT.equals(nameIDFormat) || NameID.UNSPECIFIED.equals(nameIDFormat)) { - String random = Random.nextHexRandom32(); - String nameID = subjectNameID.getValue(); - - try { - MessageDigest md = MessageDigest.getInstance("SHA-1"); - byte[] hash = md.digest((nameID + random).getBytes("ISO-8859-1")); - subjectNameID.setValue(Base64Utils.encodeToString(hash)); - subjectNameID.setNameQualifier(null); - subjectNameID.setFormat(NameID.TRANSIENT); - - } catch (Exception e) { - log.warn("PVP2 subjectNameID error", e); - throw new ResponderErrorException("internal.03", null, e); - - } - - } else - subjectNameID.setFormat(nameIDFormat); - - - String sessionIndex = null; - - //if request is a reauthentication and NameIDFormat match reuse old session information - if (StringUtils.isNotEmpty(authData.getNameID()) && - StringUtils.isNotEmpty(authData.getNameIDFormat()) && - nameIDFormat.equals(authData.getNameIDFormat())) { - subjectNameID.setValue(authData.getNameID()); - sessionIndex = authData.getSessionIndex(); - - } - - // - if (StringUtils.isEmpty(sessionIndex)) - sessionIndex = SAML2Utils.getSecureIdentifier(); - - SubjectConfirmationData subjectConfirmationData = SAML2Utils - .createSAMLObject(SubjectConfirmationData.class); - subjectConfirmationData.setInResponseTo(authnRequest.getID()); - subjectConfirmationData.setNotOnOrAfter(new DateTime(authData.getSsoSessionValidTo().getTime())); - - //set 'recipient' attribute in subjectConformationData - subjectConfirmationData.setRecipient(assertionConsumerService.getLocation()); - - //set IP address of the user machine as 'Address' attribute in subjectConformationData - String usersIPAddress = pendingReq.getRawData( - RequestImpl.DATAID_REQUESTER_IP_ADDRESS, String.class); - if (StringUtils.isNotEmpty(usersIPAddress)) - subjectConfirmationData.setAddress(usersIPAddress); - - //set SLO information - sloInformation.setUserNameIdentifier(subjectNameID.getValue()); - sloInformation.setNameIDFormat(subjectNameID.getFormat()); - sloInformation.setSessionIndex(sessionIndex); - - return buildGenericAssertion(issuerEntityID, peerEntity.getEntityID(), date, authnContextClassRef, attrList, subjectNameID, subjectConfirmationData, sessionIndex, subjectConfirmationData.getNotOnOrAfter()); - } - - /** - * - * @param issuer IDP EntityID - * @param entityID Service Provider EntityID - * @param date - * @param authnContextClassRef - * @param attrList - * @param subjectNameID - * @param subjectConfirmationData - * @param sessionIndex - * @param isValidTo - * @return - * @throws ConfigurationException - */ - - public Assertion buildGenericAssertion(String issuer, String entityID, DateTime date, - AuthnContextClassRef authnContextClassRef, List attrList, - NameID subjectNameID, SubjectConfirmationData subjectConfirmationData, - String sessionIndex, DateTime isValidTo) throws ResponderErrorException { - Assertion assertion = SAML2Utils.createSAMLObject(Assertion.class); - - AuthnContext authnContext = SAML2Utils - .createSAMLObject(AuthnContext.class); - authnContext.setAuthnContextClassRef(authnContextClassRef); - - AuthnStatement authnStatement = SAML2Utils - .createSAMLObject(AuthnStatement.class); - - authnStatement.setAuthnInstant(date); - authnStatement.setSessionIndex(sessionIndex); - authnStatement.setAuthnContext(authnContext); - - assertion.getAuthnStatements().add(authnStatement); - - AttributeStatement attributeStatement = SAML2Utils - .createSAMLObject(AttributeStatement.class); - attributeStatement.getAttributes().addAll(attrList); - if (attributeStatement.getAttributes().size() > 0) { - assertion.getAttributeStatements().add(attributeStatement); - } - - Subject subject = SAML2Utils.createSAMLObject(Subject.class); - subject.setNameID(subjectNameID); - - SubjectConfirmation subjectConfirmation = SAML2Utils - .createSAMLObject(SubjectConfirmation.class); - subjectConfirmation.setMethod(SubjectConfirmation.METHOD_BEARER); - subjectConfirmation.setSubjectConfirmationData(subjectConfirmationData); - - subject.getSubjectConfirmations().add(subjectConfirmation); - - Conditions conditions = SAML2Utils.createSAMLObject(Conditions.class); - AudienceRestriction audienceRestriction = SAML2Utils - .createSAMLObject(AudienceRestriction.class); - Audience audience = SAML2Utils.createSAMLObject(Audience.class); - - audience.setAudienceURI(entityID); - audienceRestriction.getAudiences().add(audience); - conditions.setNotBefore(date); - conditions.setNotOnOrAfter(isValidTo); - - conditions.getAudienceRestrictions().add(audienceRestriction); - - assertion.setConditions(conditions); - - Issuer issuerObj = SAML2Utils.createSAMLObject(Issuer.class); - - if (issuer.endsWith("/")) - issuer = issuer.substring(0, issuer.length()-1); - issuerObj.setValue(issuer); - issuerObj.setFormat(NameID.ENTITY); - - assertion.setIssuer(issuerObj); - assertion.setSubject(subject); - assertion.setID(SAML2Utils.getSecureIdentifier()); - assertion.setIssueInstant(date); - - return assertion; - } -} diff --git a/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/builder/Pvp2AssertionBuilder.java b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/builder/Pvp2AssertionBuilder.java new file mode 100644 index 00000000..79de4567 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_idp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/idp/impl/builder/Pvp2AssertionBuilder.java @@ -0,0 +1,465 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.idp.impl.builder; + +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; +import at.gv.egiz.eaaf.core.api.data.ILoALevelMapper; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IspConfiguration; +import at.gv.egiz.eaaf.core.api.idp.slo.SloInformationInterface; +import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; +import at.gv.egiz.eaaf.core.impl.data.Pair; +import at.gv.egiz.eaaf.core.impl.idp.controller.protocols.RequestImpl; +import at.gv.egiz.eaaf.core.impl.utils.Random; +import at.gv.egiz.eaaf.modules.pvp2.PvpConstants; +import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2Exception; +import at.gv.egiz.eaaf.modules.pvp2.exception.QaaNotSupportedException; +import at.gv.egiz.eaaf.modules.pvp2.idp.api.builder.ISubjectNameIdGenerator; +import at.gv.egiz.eaaf.modules.pvp2.idp.exception.ResponderErrorException; +import at.gv.egiz.eaaf.modules.pvp2.idp.exception.UnprovideableAttributeException; +import at.gv.egiz.eaaf.modules.pvp2.idp.impl.PvpSProfilePendingRequest; +import at.gv.egiz.eaaf.modules.pvp2.impl.builder.PvpAttributeBuilder; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.QaaLevelVerifier; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.Saml2Utils; +import org.apache.commons.lang3.StringUtils; +import org.joda.time.DateTime; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.Assertion; +import org.opensaml.saml2.core.Attribute; +import org.opensaml.saml2.core.AttributeQuery; +import org.opensaml.saml2.core.AttributeStatement; +import org.opensaml.saml2.core.Audience; +import org.opensaml.saml2.core.AudienceRestriction; +import org.opensaml.saml2.core.AuthnContext; +import org.opensaml.saml2.core.AuthnContextClassRef; +import org.opensaml.saml2.core.AuthnRequest; +import org.opensaml.saml2.core.AuthnStatement; +import org.opensaml.saml2.core.Conditions; +import org.opensaml.saml2.core.Issuer; +import org.opensaml.saml2.core.NameID; +import org.opensaml.saml2.core.NameIDType; +import org.opensaml.saml2.core.RequestedAuthnContext; +import org.opensaml.saml2.core.Subject; +import org.opensaml.saml2.core.SubjectConfirmation; +import org.opensaml.saml2.core.SubjectConfirmationData; +import org.opensaml.saml2.metadata.AssertionConsumerService; +import org.opensaml.saml2.metadata.AttributeConsumingService; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.NameIDFormat; +import org.opensaml.saml2.metadata.RequestedAttribute; +import org.opensaml.saml2.metadata.SPSSODescriptor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.util.Base64Utils; + +@Service("PVP2AssertionBuilder") +public class Pvp2AssertionBuilder implements PvpConstants { + + private static final Logger log = LoggerFactory.getLogger(Pvp2AssertionBuilder.class); + @Autowired + private ILoALevelMapper loaLevelMapper; + @Autowired + private ISubjectNameIdGenerator subjectNameIdGenerator; + + + /** + * Build a PVP assertion as response for a SAML2 AttributeQuery request. + * + * @param issuerEntityID EnitiyID, which should be used for this IDP response + * @param attrQuery AttributeQuery request from Service-Provider + * @param attrList List of PVP response attributes + * @param now Current time + * @param validTo ValidTo time of the assertion + * @param qaaLevel QAA level of the authentication + * @param sessionIndex SAML2 SessionIndex, which should be included * + * @return PVP 2.1 Assertion + * @throws Pvp2Exception In case of an error + */ + public Assertion buildAssertion(final String issuerEntityID, final AttributeQuery attrQuery, + final List attrList, final DateTime now, final DateTime validTo, + final String qaaLevel, final String sessionIndex) throws Pvp2Exception { + + final AuthnContextClassRef authnContextClassRef = + Saml2Utils.createSamlObject(AuthnContextClassRef.class); + authnContextClassRef.setAuthnContextClassRef(qaaLevel); + + final NameID subjectNameID = Saml2Utils.createSamlObject(NameID.class); + subjectNameID.setFormat(attrQuery.getSubject().getNameID().getFormat()); + subjectNameID.setValue(attrQuery.getSubject().getNameID().getValue()); + + final SubjectConfirmationData subjectConfirmationData = null; + + return buildGenericAssertion(issuerEntityID, attrQuery.getIssuer().getValue(), now, + authnContextClassRef, attrList, subjectNameID, subjectConfirmationData, sessionIndex, + validTo); + } + + + /** + * Build a PVP 2.1 assertion as response of a SAML2 AuthnRequest. + * + * @param issuerEntityID EnitiyID, which should be used for this IDP response + * @param pendingReq Current processed pendingRequest DAO + * @param authnRequest Current processed PVP AuthnRequest + * @param authData AuthenticationData of the user, which is already authenticated + * @param peerEntity SAML2 EntityDescriptor of the service-provider, which receives the response + * @param date TimeStamp + * @param assertionConsumerService SAML2 endpoint of the service-provider, which should be used + * @param sloInformation Single LogOut information DAO + * @return PVP2 S-Profil Assertion + * @throws Pvp2Exception In case of an error + */ + public Assertion buildAssertion(final String issuerEntityID, + final PvpSProfilePendingRequest pendingReq, final AuthnRequest authnRequest, + final IAuthData authData, final EntityDescriptor peerEntity, final DateTime date, + final AssertionConsumerService assertionConsumerService, + final SloInformationInterface sloInformation) throws Pvp2Exception { + + final IspConfiguration oaParam = pendingReq.getServiceProviderConfiguration(); + final AuthnContextClassRef authnContextClassRef = + Saml2Utils.createSamlObject(AuthnContextClassRef.class); + + // check if authn. request contains LoA + final RequestedAuthnContext reqAuthnContext = authnRequest.getRequestedAuthnContext(); + if (reqAuthnContext == null) { + authnContextClassRef.setAuthnContextClassRef(authData.getEidasQaaLevel()); + + } else { + // authn. request requests LoA levels. To LoA validation + final List reqAuthnContextClassRefIt = + reqAuthnContext.getAuthnContextClassRefs(); + + // get matching mode from authn. request + String loaMatchingMode = EAAFConstants.EIDAS_LOA_MATCHING_MINIMUM; + if (reqAuthnContext.getComparison() != null + && StringUtils.isNotEmpty(reqAuthnContext.getComparison().toString())) { + loaMatchingMode = reqAuthnContext.getComparison().toString(); + } + + // get requested LoAs + if (reqAuthnContextClassRefIt.size() == 0) { + QaaLevelVerifier.verifyQaaLevel(authData.getEidasQaaLevel(), oaParam.getRequiredLoA(), + loaMatchingMode); + authnContextClassRef.setAuthnContextClassRef(authData.getEidasQaaLevel()); + + } else { + final List eidasLoaFromRequest = new ArrayList<>(); + for (final AuthnContextClassRef authnClassRef : reqAuthnContextClassRefIt) { + final String qaa_uri = authnClassRef.getAuthnContextClassRef(); + + if (!qaa_uri.trim().startsWith(EAAFConstants.EIDAS_LOA_PREFIX)) { + if (loaLevelMapper != null) { + log.debug("Find no eIDAS LoA in AuthnReq. Start mapping process ... "); + eidasLoaFromRequest.add(loaLevelMapper.mapToeIDASLoA(qaa_uri.trim())); + + } else { + log.debug("AuthnRequest contains no eIDAS LoA. NO LoA mapper FOUND, ignore " + "'" + + qaa_uri.trim() + "'"); + } + } else { + eidasLoaFromRequest.add(qaa_uri.trim()); + } + + } + + // stop process if no supported LoA scheme is requested + if (eidasLoaFromRequest.isEmpty()) { + log.info( + "Authn. request contains no supported LoA level. Stop authentication process ... "); + throw new QaaNotSupportedException("No supported LoA in Authn. request"); + + } + + // verifiy LoAs from request to authentication LoA + QaaLevelVerifier.verifyQaaLevel(authData.getEidasQaaLevel(), eidasLoaFromRequest, + loaMatchingMode); + authnContextClassRef.setAuthnContextClassRef(authData.getEidasQaaLevel()); + + } + } + + + // load SPSS decriptor from service-provider metadata + final SPSSODescriptor spSsoDescriptor = peerEntity.getSPSSODescriptor(SAMLConstants.SAML20P_NS); + + // add Attributes to Assertion + final List attrList = new ArrayList<>(); + if (spSsoDescriptor.getAttributeConsumingServices() != null + && spSsoDescriptor.getAttributeConsumingServices().size() > 0) { + + final Integer aIdx = authnRequest.getAttributeConsumingServiceIndex(); + int idx = 0; + + AttributeConsumingService attributeConsumingService = null; + if (aIdx != null) { + idx = aIdx.intValue(); + attributeConsumingService = spSsoDescriptor.getAttributeConsumingServices().get(idx); + + } else { + final List attrConsumingServiceList = + spSsoDescriptor.getAttributeConsumingServices(); + for (final AttributeConsumingService el : attrConsumingServiceList) { + if (el.isDefault()) { + attributeConsumingService = el; + } + } + } + + /* + * TODO: maybe use first AttributeConsumingService if no is selected in request or on service + * is marked as default + * + */ + if (attributeConsumingService == null) { + final List attrConsumingServiceList = + spSsoDescriptor.getAttributeConsumingServices(); + if (attrConsumingServiceList != null && !attrConsumingServiceList.isEmpty()) { + attributeConsumingService = attrConsumingServiceList.get(0); + } + + } + + + if (attributeConsumingService != null) { + final Iterator it = + attributeConsumingService.getRequestAttributes().iterator(); + while (it.hasNext()) { + final RequestedAttribute reqAttribut = it.next(); + try { + final Attribute attr = + PvpAttributeBuilder.buildAttribute(reqAttribut.getName(), oaParam, authData); + if (attr == null) { + if (reqAttribut.isRequired()) { + throw new UnprovideableAttributeException(reqAttribut.getName()); + } + } else { + attrList.add(attr); + } + + } catch (final UnavailableAttributeException e) { + log.info( + "Attribute generation for " + reqAttribut.getFriendlyName() + " not possible."); + if (reqAttribut.isRequired()) { + throw new UnprovideableAttributeException(reqAttribut.getName()); + } + + + } catch (final Pvp2Exception e) { + log.info("Attribute generation failed! for " + reqAttribut.getFriendlyName()); + if (reqAttribut.isRequired()) { + throw new UnprovideableAttributeException(reqAttribut.getName()); + } + + } catch (final Exception e) { + log.warn("General Attribute generation failed! for " + reqAttribut.getFriendlyName(), + e); + if (reqAttribut.isRequired()) { + throw new UnprovideableAttributeException(reqAttribut.getName()); + } + + } + } + } + } + + // generate subjectNameId + final NameID subjectNameID = Saml2Utils.createSamlObject(NameID.class); + final Pair subjectNameIdPair = + subjectNameIdGenerator.generateSubjectNameId(authData, oaParam); + subjectNameID.setValue(subjectNameIdPair.getFirst()); + subjectNameID.setNameQualifier(subjectNameIdPair.getSecond()); + + // get NameIDFormat from request + String nameIdFormat = NameIDType.TRANSIENT; + final AuthnRequest authnReq = authnRequest; + if (authnReq.getNameIDPolicy() != null + && StringUtils.isNotEmpty(authnReq.getNameIDPolicy().getFormat())) { + nameIdFormat = authnReq.getNameIDPolicy().getFormat(); + + } else { + // get NameIDFormat from metadata + final List metadataNameIdFormats = spSsoDescriptor.getNameIDFormats(); + + if (metadataNameIdFormats != null) { + + for (final NameIDFormat el : metadataNameIdFormats) { + if (NameIDType.PERSISTENT.equals(el.getFormat())) { + nameIdFormat = NameIDType.PERSISTENT; + break; + + } else if (NameIDType.TRANSIENT.equals(el.getFormat()) + || NameIDType.UNSPECIFIED.equals(el.getFormat())) { + break; + } + + } + } + } + + if (NameIDType.TRANSIENT.equals(nameIdFormat) || NameIDType.UNSPECIFIED.equals(nameIdFormat)) { + final String random = Random.nextHexRandom32(); + final String nameID = subjectNameID.getValue(); + + try { + final MessageDigest md = MessageDigest.getInstance("SHA-1"); + final byte[] hash = md.digest((nameID + random).getBytes("ISO-8859-1")); + subjectNameID.setValue(Base64Utils.encodeToString(hash)); + subjectNameID.setNameQualifier(null); + subjectNameID.setFormat(NameIDType.TRANSIENT); + + } catch (final Exception e) { + log.warn("PVP2 subjectNameID error", e); + throw new ResponderErrorException("internal.03", null, e); + + } + + } else { + subjectNameID.setFormat(nameIdFormat); + } + + + String sessionIndex = null; + + // if request is a reauthentication and NameIDFormat match reuse old session information + if (StringUtils.isNotEmpty(authData.getNameID()) + && StringUtils.isNotEmpty(authData.getNameIdFormat()) + && nameIdFormat.equals(authData.getNameIdFormat())) { + subjectNameID.setValue(authData.getNameID()); + sessionIndex = authData.getSessionIndex(); + + } + + // + if (StringUtils.isEmpty(sessionIndex)) { + sessionIndex = Saml2Utils.getSecureIdentifier(); + } + + final SubjectConfirmationData subjectConfirmationData = + Saml2Utils.createSamlObject(SubjectConfirmationData.class); + subjectConfirmationData.setInResponseTo(authnRequest.getID()); + subjectConfirmationData + .setNotOnOrAfter(new DateTime(authData.getSsoSessionValidTo().getTime())); + + // set 'recipient' attribute in subjectConformationData + subjectConfirmationData.setRecipient(assertionConsumerService.getLocation()); + + // set IP address of the user machine as 'Address' attribute in subjectConformationData + final String usersIpAddress = + pendingReq.getRawData(RequestImpl.DATAID_REQUESTER_IP_ADDRESS, String.class); + if (StringUtils.isNotEmpty(usersIpAddress)) { + subjectConfirmationData.setAddress(usersIpAddress); + } + + // set SLO information + sloInformation.setUserNameIdentifier(subjectNameID.getValue()); + sloInformation.setNameIdFormat(subjectNameID.getFormat()); + sloInformation.setSessionIndex(sessionIndex); + + return buildGenericAssertion(issuerEntityID, peerEntity.getEntityID(), date, + authnContextClassRef, attrList, subjectNameID, subjectConfirmationData, sessionIndex, + subjectConfirmationData.getNotOnOrAfter()); + } + + /** + * Build generic part of PVP S-Profile Assertion. + * + * @param issuer IDP EntityID + * @param entityID Service Provider EntityID + * @param date Timestamp + * @param authnContextClassRef SAML2 AuthnContextClassReference + * @param attrList List of attributes + * @param subjectNameID SubjectNameId + * @param subjectConfirmationData SubjectConfirmationInformation + * @param sessionIndex SessionIndex + * @param isValidTo ValidTo Timestamp + * @return PVP S-Profile Assertion + * @throws ConfigurationException In case on an error + */ + + public Assertion buildGenericAssertion(String issuer, final String entityID, final DateTime date, + final AuthnContextClassRef authnContextClassRef, final List attrList, + final NameID subjectNameID, final SubjectConfirmationData subjectConfirmationData, + final String sessionIndex, final DateTime isValidTo) throws ResponderErrorException { + final Assertion assertion = Saml2Utils.createSamlObject(Assertion.class); + + final AuthnContext authnContext = Saml2Utils.createSamlObject(AuthnContext.class); + authnContext.setAuthnContextClassRef(authnContextClassRef); + + final AuthnStatement authnStatement = Saml2Utils.createSamlObject(AuthnStatement.class); + + authnStatement.setAuthnInstant(date); + authnStatement.setSessionIndex(sessionIndex); + authnStatement.setAuthnContext(authnContext); + + assertion.getAuthnStatements().add(authnStatement); + + final AttributeStatement attributeStatement = + Saml2Utils.createSamlObject(AttributeStatement.class); + attributeStatement.getAttributes().addAll(attrList); + if (attributeStatement.getAttributes().size() > 0) { + assertion.getAttributeStatements().add(attributeStatement); + } + + final Subject subject = Saml2Utils.createSamlObject(Subject.class); + subject.setNameID(subjectNameID); + + final SubjectConfirmation subjectConfirmation = + Saml2Utils.createSamlObject(SubjectConfirmation.class); + subjectConfirmation.setMethod(SubjectConfirmation.METHOD_BEARER); + subjectConfirmation.setSubjectConfirmationData(subjectConfirmationData); + + subject.getSubjectConfirmations().add(subjectConfirmation); + + final Conditions conditions = Saml2Utils.createSamlObject(Conditions.class); + final AudienceRestriction audienceRestriction = + Saml2Utils.createSamlObject(AudienceRestriction.class); + final Audience audience = Saml2Utils.createSamlObject(Audience.class); + + audience.setAudienceURI(entityID); + audienceRestriction.getAudiences().add(audience); + conditions.setNotBefore(date); + conditions.setNotOnOrAfter(isValidTo); + + conditions.getAudienceRestrictions().add(audienceRestriction); + + assertion.setConditions(conditions); + + final Issuer issuerObj = Saml2Utils.createSamlObject(Issuer.class); + + if (issuer.endsWith("/")) { + issuer = issuer.substring(0, issuer.length() - 1); + } + issuerObj.setValue(issuer); + issuerObj.setFormat(NameIDType.ENTITY); + + assertion.setIssuer(issuerObj); + assertion.setSubject(subject); + assertion.setID(Saml2Utils.getSecureIdentifier()); + assertion.setIssueInstant(date); + + return assertion; + } +} diff --git a/eaaf_modules/eaaf_module_pvp2_idp/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider b/eaaf_modules/eaaf_module_pvp2_idp/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider index cda12a62..c3c68e20 100644 --- a/eaaf_modules/eaaf_module_pvp2_idp/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider +++ b/eaaf_modules/eaaf_module_pvp2_idp/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider @@ -1 +1 @@ -at.gv.egiz.eaaf.modules.pvp2.idp.PVP2SProfileIDPSpringResourceProvider \ No newline at end of file +at.gv.egiz.eaaf.modules.pvp2.idp.Pvp2SProfileIdpSpringResourceProvider \ No newline at end of file diff --git a/eaaf_modules/eaaf_module_pvp2_idp/src/main/resources/eaaf_pvp_idp.beans.xml b/eaaf_modules/eaaf_module_pvp2_idp/src/main/resources/eaaf_pvp_idp.beans.xml index b01a09ff..d29b5aba 100644 --- a/eaaf_modules/eaaf_module_pvp2_idp/src/main/resources/eaaf_pvp_idp.beans.xml +++ b/eaaf_modules/eaaf_module_pvp2_idp/src/main/resources/eaaf_pvp_idp.beans.xml @@ -1,22 +1,19 @@ - - - - - - - + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:context="http://www.springframework.org/schema/context" + xmlns:tx="http://www.springframework.org/schema/tx" + xmlns:aop="http://www.springframework.org/schema/aop" + xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd + http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> + + + + + \ No newline at end of file diff --git a/eaaf_modules/eaaf_module_pvp2_sp/pom.xml b/eaaf_modules/eaaf_module_pvp2_sp/pom.xml index b3e11151..51219563 100644 --- a/eaaf_modules/eaaf_module_pvp2_sp/pom.xml +++ b/eaaf_modules/eaaf_module_pvp2_sp/pom.xml @@ -5,7 +5,7 @@ at.gv.egiz.eaaf eaaf_modules - 1.0.14-SNAPSHOT + 1.1.0-SNAPSHOT eaaf_module_pvp2_sp eaaf_module_pvp2_sp diff --git a/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/api/IPVPAuthnRequestBuilderConfiguruation.java b/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/api/IPVPAuthnRequestBuilderConfiguruation.java deleted file mode 100644 index b8a8e796..00000000 --- a/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/api/IPVPAuthnRequestBuilderConfiguruation.java +++ /dev/null @@ -1,195 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.sp.api; - -import java.util.List; - -import org.opensaml.saml2.core.AuthnContextComparisonTypeEnumeration; -import org.opensaml.saml2.metadata.EntityDescriptor; -import org.opensaml.xml.security.credential.Credential; -import org.w3c.dom.Element; - -import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EAAFRequestedAttribute; - -/** - * @author tlenz - * - */ -public interface IPVPAuthnRequestBuilderConfiguruation { - - /** - * Defines a unique name for this PVP Service-provider, which is used for logging - * - * @return - */ - public String getSPNameForLogging(); - - /** - * If true, the SAML2 isPassive flag is set in the AuthnRequest - * - * @return - */ - public Boolean isPassivRequest(); - - /** - * Define the ID of the AssertionConsumerService, - * which defines the required attributes in service-provider metadata. - * - * @return - */ - public Integer getAssertionConsumerServiceId(); - - /** - * Define the SAML2 EntityID of the service provider. - * - * @return - */ - public String getSPEntityID(); - - /** - * Define the SAML2 NameIDPolicy - * - * @return Service-Provider EntityID, but never null - */ - public String getNameIDPolicyFormat(); - - /** - * Define the AuthnContextClassRefernece of this request - * - * Example: - * http://www.ref.gv.at/ns/names/agiz/pvp/secclass/0-3 - * http://www.stork.gov.eu/1.0/citizenQAALevel/4 - * - * - * @return - */ - public String getAuthnContextClassRef(); - - /** - * Define the AuthnContextComparison model, which should be used - * - * @return - */ - public AuthnContextComparisonTypeEnumeration getAuthnContextComparison(); - - - /** - * Define the credential, which should be used to sign the AuthnRequest - * - * @return - */ - public Credential getAuthnRequestSigningCredential(); - - - /** - * Define the SAML2 EntityDescriptor of the IDP, which should receive the AuthnRequest - * - * @return Credential, but never null. - */ - public EntityDescriptor getIDPEntityDescriptor(); - - /** - * Set the SAML2 NameIDPolicy allow-creation flag - * - * @return EntityDescriptor, but never null. - */ - public boolean getNameIDPolicyAllowCreation(); - - - /** - * Set the requested SubjectNameID - * - * @return SubjectNameID, or null if no SubjectNameID should be used - */ - public String getSubjectNameID(); - - /** - * Define the qualifier of the SubjectNameID - *

    - * Like: 'urn:publicid:gv.at:cdid+BF' - * - * @return qualifier, or null if no qualifier should be set - */ - public String getSubjectNameIDQualifier(); - - /** - * Define the format of the subjectNameID, which is included in authn-request - * - * - * @return nameIDFormat, of SAML2 'transient' if nothing is defined - */ - public String getSubjectNameIDFormat(); - - /** - * Define a SP specific SAML2 requestID - * - * @return requestID, or null if the requestID should be generated automatically - */ - public String getRequestID(); - - /** - * Defines the 'method' attribute in 'SubjectConformation' element - * - * @return method, or null if no method should set - */ - public String getSubjectConformationMethode(); - - /** - * Define the information, which should be added as 'subjectConformationDate' - * in 'SubjectConformation' element - * - * @return subjectConformation information or null if no subjectConformation should be set - */ - public Element getSubjectConformationDate(); - - - /** - * Get the EntityId of the SP in case of a SAML2 proxy use-case - * - * @return - */ - public String getScopeRequesterId(); - - - /** - * Get a FriendlyName for the SP that sends the request - * - * @return - */ - public String getProviderName(); - - - /** - * Get a Set of SAML2 attributes that are requested by using SAML2 requested attributes - *
    - * Info: Attributes are requested by using eIDAS SAML2 extension for requested attributes - * - * @return - */ - public List getRequestedAttributes(); - -} diff --git a/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/api/IPvpAuthnRequestBuilderConfiguruation.java b/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/api/IPvpAuthnRequestBuilderConfiguruation.java new file mode 100644 index 00000000..d050dd4b --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/api/IPvpAuthnRequestBuilderConfiguruation.java @@ -0,0 +1,187 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.sp.api; + +import java.util.List; +import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EaafRequestedAttribute; +import org.opensaml.saml2.core.AuthnContextComparisonTypeEnumeration; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.xml.security.credential.Credential; +import org.w3c.dom.Element; + +/** + * Configuration of a PVP2 S-Profile authentication-request builder. + * + * @author tlenz + * + */ +public interface IPvpAuthnRequestBuilderConfiguruation { + + /** + * Defines a unique name for this PVP Service-provider, which is used for logging. + * + * @return + */ + public String getSpNameForLogging(); + + /** + * If true, the SAML2 isPassive flag is set in the AuthnRequest. + * + * @return + */ + public Boolean isPassivRequest(); + + /** + * Define the ID of the AssertionConsumerService, which defines the required attributes in + * service-provider metadata. + * + * @return + */ + public Integer getAssertionConsumerServiceId(); + + /** + * Define the SAML2 EntityID of the service provider. + * + * @return + */ + public String getSpEntityID(); + + /** + * Define the SAML2 NameIDPolicy. + * + * @return Service-Provider EntityID, but never null + */ + public String getNameIdPolicyFormat(); + + /** + * Define the AuthnContextClassRefernece of this request. + * + *

    + * Example: http://www.ref.gv.at/ns/names/agiz/pvp/secclass/0-3 + * http://www.stork.gov.eu/1.0/citizenQAALevel/4 + *

    + * + * @return + */ + public String getAuthnContextClassRef(); + + /** + * Define the AuthnContextComparison model, which should be used. + * + * @return + */ + public AuthnContextComparisonTypeEnumeration getAuthnContextComparison(); + + + /** + * Define the credential, which should be used to sign the AuthnRequest. + * + * @return + */ + public Credential getAuthnRequestSigningCredential(); + + + /** + * Define the SAML2 EntityDescriptor of the IDP, which should receive the AuthnRequest. + * + * @return Credential, but never null. + */ + public EntityDescriptor getIdpEntityDescriptor(); + + /** + * Set the SAML2 NameIDPolicy allow-creation flag. + * + * @return EntityDescriptor, but never null. + */ + public boolean getNameIdPolicyAllowCreation(); + + + /** + * Set the requested SubjectNameID. + * + * @return SubjectNameID, or null if no SubjectNameID should be used + */ + public String getSubjectNameID(); + + /** + * Define the qualifier of the SubjectNameID
    + *
    + * Like: 'urn:publicid:gv.at:cdid+BF' + * + * @return qualifier, or null if no qualifier should be set + */ + public String getSubjectNameIdQualifier(); + + /** + * Define the format of the subjectNameID, which is included in authn-request. + * + * + * @return nameIDFormat, of SAML2 'transient' if nothing is defined + */ + public String getSubjectNameIdFormat(); + + /** + * Define a SP specific SAML2 requestID. + * + * @return requestID, or null if the requestID should be generated automatically + */ + public String getRequestID(); + + /** + * Defines the 'method' attribute in 'SubjectConformation' element. + * + * @return method, or null if no method should set + */ + public String getSubjectConformationMethode(); + + /** + * Define the information, which should be added as 'subjectConformationDate' in + * 'SubjectConformation' element. + * + * @return subjectConformation information or null if no subjectConformation should be set + */ + public Element getSubjectConformationDate(); + + + /** + * Get the EntityId of the SP in case of a SAML2 proxy use-case. + * + * @return + */ + public String getScopeRequesterId(); + + + /** + * Get a FriendlyName for the SP that sends the request. + * + * @return + */ + public String getProviderName(); + + + /** + * Get a Set of SAML2 attributes that are requested by using SAML2 requested attributes.
    + * Info: Attributes are requested by using eIDAS SAML2 extension for requested attributes + * + * @return + */ + public List getRequestedAttributes(); + +} diff --git a/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/exception/AssertionAttributeExtractorExeption.java b/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/exception/AssertionAttributeExtractorExeption.java index 3afcc65d..4411d9c6 100644 --- a/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/exception/AssertionAttributeExtractorExeption.java +++ b/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/exception/AssertionAttributeExtractorExeption.java @@ -1,56 +1,40 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.sp.exception; -import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; +import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2Exception; -/** - * @author tlenz - * - */ -public class AssertionAttributeExtractorExeption extends PVP2Exception { - - /** - * - */ - private static final long serialVersionUID = -6459000942830951492L; - - public AssertionAttributeExtractorExeption(String attributeName) { - super("Parse PVP2.1 assertion FAILED: Attribute " + attributeName - + " can not extract.", null); - } - - public AssertionAttributeExtractorExeption(String messageId, - Object[] parameters) { - super(messageId, parameters); - } - - public AssertionAttributeExtractorExeption() { - super("Parse PVP2.1 assertion FAILED. Interfederation not possible", null); - } +public class AssertionAttributeExtractorExeption extends Pvp2Exception { + + private static final long serialVersionUID = -6459000942830951492L; + + public AssertionAttributeExtractorExeption(final String attributeName) { + super("Parse PVP2.1 assertion FAILED: Attribute " + attributeName + " can not extract.", null); + } + + public AssertionAttributeExtractorExeption(final String messageId, final Object[] parameters) { + super(messageId, parameters); + } + + public AssertionAttributeExtractorExeption() { + super("Parse PVP2.1 assertion FAILED. Interfederation not possible", null); + } } diff --git a/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/exception/AssertionValidationExeption.java b/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/exception/AssertionValidationExeption.java index 5766aab0..1096c535 100644 --- a/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/exception/AssertionValidationExeption.java +++ b/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/exception/AssertionValidationExeption.java @@ -1,53 +1,38 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.sp.exception; -import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; +import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2Exception; -/** - * @author tlenz - * - */ -public class AssertionValidationExeption extends PVP2Exception { - - private static final long serialVersionUID = -3987805399122286259L; - - public AssertionValidationExeption(String messageId, Object[] parameters) { - super(messageId, parameters); - } - - /** - * @param string - * @param object - * @param e - */ - public AssertionValidationExeption(String string, Object[] parameters, - Throwable e) { - super(string, parameters, e); - } + +public class AssertionValidationExeption extends Pvp2Exception { + + private static final long serialVersionUID = -3987805399122286259L; + + public AssertionValidationExeption(final String messageId, final Object[] parameters) { + super(messageId, parameters); + } + + public AssertionValidationExeption(final String string, final Object[] parameters, + final Throwable e) { + super(string, parameters, e); + } } diff --git a/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/exception/AuthnRequestBuildException.java b/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/exception/AuthnRequestBuildException.java index 9fdffaf4..5ad42fb7 100644 --- a/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/exception/AuthnRequestBuildException.java +++ b/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/exception/AuthnRequestBuildException.java @@ -1,53 +1,37 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. + */ + package at.gv.egiz.eaaf.modules.pvp2.sp.exception; -import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; +import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2Exception; -/** - * @author tlenz - * - */ -public class AuthnRequestBuildException extends PVP2Exception { - - /** - * - */ - private static final long serialVersionUID = -1375451065455859354L; - - /** - * @param messageId - * @param parameters - */ - public AuthnRequestBuildException(String messageId, Object[] parameters) { - super(messageId, parameters); - } - - public AuthnRequestBuildException(String messageId, Object[] parameters, Throwable e) { - super(messageId, parameters, e); - } + +public class AuthnRequestBuildException extends Pvp2Exception { + + + private static final long serialVersionUID = -1375451065455859354L; + + public AuthnRequestBuildException(final String messageId, final Object[] parameters) { + super(messageId, parameters); + } + + public AuthnRequestBuildException(final String messageId, final Object[] parameters, final Throwable e) { + super(messageId, parameters, e); + } } diff --git a/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/exception/AuthnResponseValidationException.java b/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/exception/AuthnResponseValidationException.java index 9d2ec046..d8d7683c 100644 --- a/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/exception/AuthnResponseValidationException.java +++ b/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/exception/AuthnResponseValidationException.java @@ -1,54 +1,39 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.sp.exception; -import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; +import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2Exception; -/** - * @author tlenz - * - */ -public class AuthnResponseValidationException extends PVP2Exception { - - /** - * - */ - private static final long serialVersionUID = 8023812861029406575L; - - /** - * @param messageId - * @param parameters - */ - public AuthnResponseValidationException(String messageId, Object[] parameters) { - super(messageId, parameters); - } - - public AuthnResponseValidationException(String messageId, Object[] parameters, Throwable e) { - super(messageId, parameters, e); - } + +public class AuthnResponseValidationException extends Pvp2Exception { + + + private static final long serialVersionUID = 8023812861029406575L; + + + public AuthnResponseValidationException(final String messageId, final Object[] parameters) { + super(messageId, parameters); + } + + public AuthnResponseValidationException(final String messageId, final Object[] parameters, final Throwable e) { + super(messageId, parameters, e); + } } diff --git a/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/impl/PVPAuthnRequestBuilder.java b/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/impl/PVPAuthnRequestBuilder.java deleted file mode 100644 index e8cdd1f7..00000000 --- a/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/impl/PVPAuthnRequestBuilder.java +++ /dev/null @@ -1,259 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.sp.impl; - -import java.security.NoSuchAlgorithmException; -import java.util.List; - -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang3.StringUtils; -import org.joda.time.DateTime; -import org.opensaml.common.impl.SecureRandomIdentifierGenerator; -import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.saml2.common.Extensions; -import org.opensaml.saml2.core.AuthnContextClassRef; -import org.opensaml.saml2.core.AuthnContextComparisonTypeEnumeration; -import org.opensaml.saml2.core.AuthnRequest; -import org.opensaml.saml2.core.Issuer; -import org.opensaml.saml2.core.NameID; -import org.opensaml.saml2.core.NameIDPolicy; -import org.opensaml.saml2.core.NameIDType; -import org.opensaml.saml2.core.RequestedAuthnContext; -import org.opensaml.saml2.core.RequesterID; -import org.opensaml.saml2.core.Scoping; -import org.opensaml.saml2.core.Subject; -import org.opensaml.saml2.core.SubjectConfirmation; -import org.opensaml.saml2.core.SubjectConfirmationData; -import org.opensaml.saml2.metadata.EntityDescriptor; -import org.opensaml.saml2.metadata.SingleSignOnService; -import org.opensaml.ws.message.encoder.MessageEncodingException; -import org.opensaml.xml.security.SecurityException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.stereotype.Service; - -import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.modules.pvp2.api.binding.IEncoder; -import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EAAFRequestedAttribute; -import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EAAFRequestedAttributes; -import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; -import at.gv.egiz.eaaf.modules.pvp2.impl.binding.PostBinding; -import at.gv.egiz.eaaf.modules.pvp2.impl.binding.RedirectBinding; -import at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr.EAAFRequestExtensionBuilder; -import at.gv.egiz.eaaf.modules.pvp2.impl.utils.SAML2Utils; -import at.gv.egiz.eaaf.modules.pvp2.sp.api.IPVPAuthnRequestBuilderConfiguruation; -import at.gv.egiz.eaaf.modules.pvp2.sp.exception.AuthnRequestBuildException; - -/** - * @author tlenz - * - */ -@Service("pvpAuthnRequestBuilder") -public class PVPAuthnRequestBuilder { - private static final Logger log = LoggerFactory.getLogger(PVPAuthnRequestBuilder.class); - - - @Autowired(required=true) ApplicationContext springContext; - - - /** - * Build a PVP2.x specific authentication request - * - * @param pendingReq Currently processed pendingRequest - * @param config AuthnRequest builder configuration, never null - * @param idpEntity SAML2 EntityDescriptor of the IDP, which receive this AuthnRequest, never null - * @param httpResp - * @throws NoSuchAlgorithmException - * @throws SecurityException - * @throws PVP2Exception - * @throws MessageEncodingException - */ - public void buildAuthnRequest(IRequest pendingReq, IPVPAuthnRequestBuilderConfiguruation config, - HttpServletResponse httpResp) throws NoSuchAlgorithmException, MessageEncodingException, PVP2Exception, SecurityException { - //get IDP Entity element from config - EntityDescriptor idpEntity = config.getIDPEntityDescriptor(); - - AuthnRequest authReq = SAML2Utils - .createSAMLObject(AuthnRequest.class); - - //select SingleSignOn Service endpoint from IDP metadata - SingleSignOnService endpoint = null; - for (SingleSignOnService sss : - idpEntity.getIDPSSODescriptor(SAMLConstants.SAML20P_NS).getSingleSignOnServices()) { - - // use POST binding as default if it exists - if (sss.getBinding().equals(SAMLConstants.SAML2_POST_BINDING_URI)) { - endpoint = sss; - - } else if ( sss.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI) - && endpoint == null ) - endpoint = sss; - - } - - if (endpoint == null) { - log.warn("Building AuthnRequest FAILED: > Requested IDP " + idpEntity.getEntityID() - + " does not support POST or Redirect Binding."); - throw new AuthnRequestBuildException("sp.pvp2.00", new Object[]{config.getSPNameForLogging(), idpEntity.getEntityID()}); - - } else - authReq.setDestination(endpoint.getLocation()); - - - //set basic AuthnRequest information - String reqID = config.getRequestID(); - if (StringUtils.isNotEmpty(reqID)) - authReq.setID(reqID); - - else { - SecureRandomIdentifierGenerator gen = new SecureRandomIdentifierGenerator(); - authReq.setID(gen.generateIdentifier()); - - } - - authReq.setIssueInstant(new DateTime()); - - //set isPassive flag - if (config.isPassivRequest() == null) - authReq.setIsPassive(false); - else - authReq.setIsPassive(config.isPassivRequest()); - - //set EntityID of the service provider - Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class); - issuer.setFormat(NameIDType.ENTITY); - issuer.setValue(config.getSPEntityID()); - authReq.setIssuer(issuer); - - //set AssertionConsumerService ID - if (config.getAssertionConsumerServiceId() != null) - authReq.setAssertionConsumerServiceIndex(config.getAssertionConsumerServiceId()); - - //set NameIDPolicy - if (config.getNameIDPolicyFormat() != null) { - NameIDPolicy policy = SAML2Utils.createSAMLObject(NameIDPolicy.class); - policy.setAllowCreate(config.getNameIDPolicyAllowCreation()); - policy.setFormat(config.getNameIDPolicyFormat()); - authReq.setNameIDPolicy(policy); - } - - //set requested QAA level - if (config.getAuthnContextClassRef() != null) { - RequestedAuthnContext reqAuthContext = SAML2Utils.createSAMLObject(RequestedAuthnContext.class); - AuthnContextClassRef authnClassRef = SAML2Utils.createSAMLObject(AuthnContextClassRef.class); - - authnClassRef.setAuthnContextClassRef(config.getAuthnContextClassRef()); - - if (config.getAuthnContextComparison() == null) - reqAuthContext.setComparison(AuthnContextComparisonTypeEnumeration.MINIMUM); - else - reqAuthContext.setComparison(config.getAuthnContextComparison()); - - reqAuthContext.getAuthnContextClassRefs().add(authnClassRef); - authReq.setRequestedAuthnContext(reqAuthContext); - } - - //set request Subject element - if (StringUtils.isNotEmpty(config.getSubjectNameID())) { - Subject reqSubject = SAML2Utils.createSAMLObject(Subject.class); - NameID subjectNameID = SAML2Utils.createSAMLObject(NameID.class); - - subjectNameID.setValue(config.getSubjectNameID()); - if (StringUtils.isNotEmpty(config.getSubjectNameIDQualifier())) - subjectNameID.setNameQualifier(config.getSubjectNameIDQualifier()); - - if (StringUtils.isNotEmpty(config.getSubjectNameIDFormat())) - subjectNameID.setFormat(config.getSubjectNameIDFormat()); - else - subjectNameID.setFormat(NameID.TRANSIENT); - - reqSubject.setNameID(subjectNameID); - - if (config.getSubjectConformationDate() != null) { - SubjectConfirmation subjectConformation = SAML2Utils.createSAMLObject(SubjectConfirmation.class); - SubjectConfirmationData subjectConformDate = SAML2Utils.createSAMLObject(SubjectConfirmationData.class); - subjectConformation.setSubjectConfirmationData(subjectConformDate); - reqSubject.getSubjectConfirmations().add(subjectConformation ); - - if (config.getSubjectConformationMethode() != null) - subjectConformation.setMethod(config.getSubjectConformationMethode()); - - subjectConformDate.setDOM(config.getSubjectConformationDate()); - - } - - authReq.setSubject(reqSubject ); - - } - - - //set ProviderName - if (StringUtils.isNotEmpty(config.getProviderName())) - authReq.setProviderName(config.getProviderName()); - - //set RequesterId in case of proxy mode - if (StringUtils.isNotEmpty(config.getScopeRequesterId())) { - Scoping scope = SAML2Utils.createSAMLObject(Scoping.class); - RequesterID requesterId = SAML2Utils.createSAMLObject(RequesterID.class); - requesterId.setRequesterID(config.getScopeRequesterId()); - scope.getRequesterIDs().add(requesterId ); - authReq.setScoping(scope ); - - } - - //add optional requested attributes - if (config.getRequestedAttributes() != null) { - List reqAttr = config.getRequestedAttributes(); - Extensions extenstions = new EAAFRequestExtensionBuilder().buildObject(); - EAAFRequestedAttributes reqAttributs = SAML2Utils.createSAMLObject(EAAFRequestedAttributes.class); - reqAttributs.getAttributes().addAll(reqAttr); - extenstions.getUnknownXMLObjects().add(reqAttributs); - authReq.setExtensions(extenstions ); - - } - - //select message encoder - IEncoder binding = null; - if (endpoint.getBinding().equals( - SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { - binding = springContext.getBean("PVPRedirectBinding", RedirectBinding.class); - - } else if (endpoint.getBinding().equals( - SAMLConstants.SAML2_POST_BINDING_URI)) { - binding = springContext.getBean("PVPPOSTBinding", PostBinding.class); - - } - - //encode message - binding.encodeRequest(null, httpResp, authReq, - endpoint.getLocation(), pendingReq.getPendingRequestId(), config.getAuthnRequestSigningCredential(), pendingReq); - } - -} diff --git a/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/impl/PvpAuthnRequestBuilder.java b/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/impl/PvpAuthnRequestBuilder.java new file mode 100644 index 00000000..36f43cc8 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/impl/PvpAuthnRequestBuilder.java @@ -0,0 +1,263 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.sp.impl; + +import java.security.NoSuchAlgorithmException; +import java.util.List; +import javax.servlet.http.HttpServletResponse; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.modules.pvp2.api.binding.IEncoder; +import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EaafRequestedAttribute; +import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EaafRequestedAttributes; +import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2Exception; +import at.gv.egiz.eaaf.modules.pvp2.impl.binding.PostBinding; +import at.gv.egiz.eaaf.modules.pvp2.impl.binding.RedirectBinding; +import at.gv.egiz.eaaf.modules.pvp2.impl.builder.reqattr.EaafRequestExtensionBuilder; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.Saml2Utils; +import at.gv.egiz.eaaf.modules.pvp2.sp.api.IPvpAuthnRequestBuilderConfiguruation; +import at.gv.egiz.eaaf.modules.pvp2.sp.exception.AuthnRequestBuildException; +import org.apache.commons.lang3.StringUtils; +import org.joda.time.DateTime; +import org.opensaml.common.impl.SecureRandomIdentifierGenerator; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.common.Extensions; +import org.opensaml.saml2.core.AuthnContextClassRef; +import org.opensaml.saml2.core.AuthnContextComparisonTypeEnumeration; +import org.opensaml.saml2.core.AuthnRequest; +import org.opensaml.saml2.core.Issuer; +import org.opensaml.saml2.core.NameID; +import org.opensaml.saml2.core.NameIDPolicy; +import org.opensaml.saml2.core.NameIDType; +import org.opensaml.saml2.core.RequestedAuthnContext; +import org.opensaml.saml2.core.RequesterID; +import org.opensaml.saml2.core.Scoping; +import org.opensaml.saml2.core.Subject; +import org.opensaml.saml2.core.SubjectConfirmation; +import org.opensaml.saml2.core.SubjectConfirmationData; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.SingleSignOnService; +import org.opensaml.ws.message.encoder.MessageEncodingException; +import org.opensaml.xml.security.SecurityException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.stereotype.Service; + +/** + * PVP2 S-Profil Authentication-Request builder-implementation. + * + * @author tlenz + * + */ +@Service("pvpAuthnRequestBuilder") +public class PvpAuthnRequestBuilder { + private static final Logger log = LoggerFactory.getLogger(PvpAuthnRequestBuilder.class); + + + @Autowired(required = true) + ApplicationContext springContext; + + + /** + * Build a PVP2.x specific authentication request + * + * @param pendingReq Currently processed pendingRequest + * @param config AuthnRequest builder configuration, never null + * @param httpResp http response object + * @throws NoSuchAlgorithmException In case of error + * @throws SecurityException In case of error + * @throws Pvp2Exception In case of error + * @throws MessageEncodingException In case of error + */ + public void buildAuthnRequest(final IRequest pendingReq, + final IPvpAuthnRequestBuilderConfiguruation config, final HttpServletResponse httpResp) + throws NoSuchAlgorithmException, MessageEncodingException, Pvp2Exception, SecurityException { + // get IDP Entity element from config + final EntityDescriptor idpEntity = config.getIdpEntityDescriptor(); + + final AuthnRequest authReq = Saml2Utils.createSamlObject(AuthnRequest.class); + + // select SingleSignOn Service endpoint from IDP metadata + SingleSignOnService endpoint = null; + for (final SingleSignOnService sss : idpEntity.getIDPSSODescriptor(SAMLConstants.SAML20P_NS) + .getSingleSignOnServices()) { + + // use POST binding as default if it exists + if (sss.getBinding().equals(SAMLConstants.SAML2_POST_BINDING_URI)) { + endpoint = sss; + + } else if (sss.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI) + && endpoint == null) { + endpoint = sss; + } + + } + + if (endpoint == null) { + log.warn("Building AuthnRequest FAILED: > Requested IDP " + idpEntity.getEntityID() + + " does not support POST or Redirect Binding."); + throw new AuthnRequestBuildException("sp.pvp2.00", + new Object[] {config.getSpNameForLogging(), idpEntity.getEntityID()}); + + } else { + authReq.setDestination(endpoint.getLocation()); + } + + + // set basic AuthnRequest information + final String reqID = config.getRequestID(); + if (StringUtils.isNotEmpty(reqID)) { + authReq.setID(reqID); + } else { + final SecureRandomIdentifierGenerator gen = new SecureRandomIdentifierGenerator(); + authReq.setID(gen.generateIdentifier()); + + } + + authReq.setIssueInstant(new DateTime()); + + // set isPassive flag + if (config.isPassivRequest() == null) { + authReq.setIsPassive(false); + } else { + authReq.setIsPassive(config.isPassivRequest()); + } + + // set EntityID of the service provider + final Issuer issuer = Saml2Utils.createSamlObject(Issuer.class); + issuer.setFormat(NameIDType.ENTITY); + issuer.setValue(config.getSpEntityID()); + authReq.setIssuer(issuer); + + // set AssertionConsumerService ID + if (config.getAssertionConsumerServiceId() != null) { + authReq.setAssertionConsumerServiceIndex(config.getAssertionConsumerServiceId()); + } + + // set NameIDPolicy + if (config.getNameIdPolicyFormat() != null) { + final NameIDPolicy policy = Saml2Utils.createSamlObject(NameIDPolicy.class); + policy.setAllowCreate(config.getNameIdPolicyAllowCreation()); + policy.setFormat(config.getNameIdPolicyFormat()); + authReq.setNameIDPolicy(policy); + } + + // set requested QAA level + if (config.getAuthnContextClassRef() != null) { + final RequestedAuthnContext reqAuthContext = + Saml2Utils.createSamlObject(RequestedAuthnContext.class); + final AuthnContextClassRef authnClassRef = + Saml2Utils.createSamlObject(AuthnContextClassRef.class); + + authnClassRef.setAuthnContextClassRef(config.getAuthnContextClassRef()); + + if (config.getAuthnContextComparison() == null) { + reqAuthContext.setComparison(AuthnContextComparisonTypeEnumeration.MINIMUM); + } else { + reqAuthContext.setComparison(config.getAuthnContextComparison()); + } + + reqAuthContext.getAuthnContextClassRefs().add(authnClassRef); + authReq.setRequestedAuthnContext(reqAuthContext); + } + + // set request Subject element + if (StringUtils.isNotEmpty(config.getSubjectNameID())) { + final Subject reqSubject = Saml2Utils.createSamlObject(Subject.class); + final NameID subjectNameID = Saml2Utils.createSamlObject(NameID.class); + + subjectNameID.setValue(config.getSubjectNameID()); + if (StringUtils.isNotEmpty(config.getSubjectNameIdQualifier())) { + subjectNameID.setNameQualifier(config.getSubjectNameIdQualifier()); + } + + if (StringUtils.isNotEmpty(config.getSubjectNameIdFormat())) { + subjectNameID.setFormat(config.getSubjectNameIdFormat()); + } else { + subjectNameID.setFormat(NameIDType.TRANSIENT); + } + + reqSubject.setNameID(subjectNameID); + + if (config.getSubjectConformationDate() != null) { + final SubjectConfirmation subjectConformation = + Saml2Utils.createSamlObject(SubjectConfirmation.class); + final SubjectConfirmationData subjectConformDate = + Saml2Utils.createSamlObject(SubjectConfirmationData.class); + subjectConformation.setSubjectConfirmationData(subjectConformDate); + reqSubject.getSubjectConfirmations().add(subjectConformation); + + if (config.getSubjectConformationMethode() != null) { + subjectConformation.setMethod(config.getSubjectConformationMethode()); + } + + subjectConformDate.setDOM(config.getSubjectConformationDate()); + + } + + authReq.setSubject(reqSubject); + + } + + + // set ProviderName + if (StringUtils.isNotEmpty(config.getProviderName())) { + authReq.setProviderName(config.getProviderName()); + } + + // set RequesterId in case of proxy mode + if (StringUtils.isNotEmpty(config.getScopeRequesterId())) { + final Scoping scope = Saml2Utils.createSamlObject(Scoping.class); + final RequesterID requesterId = Saml2Utils.createSamlObject(RequesterID.class); + requesterId.setRequesterID(config.getScopeRequesterId()); + scope.getRequesterIDs().add(requesterId); + authReq.setScoping(scope); + + } + + // add optional requested attributes + if (config.getRequestedAttributes() != null) { + final List reqAttr = config.getRequestedAttributes(); + final Extensions extenstions = new EaafRequestExtensionBuilder().buildObject(); + final EaafRequestedAttributes reqAttributs = + Saml2Utils.createSamlObject(EaafRequestedAttributes.class); + reqAttributs.getAttributes().addAll(reqAttr); + extenstions.getUnknownXMLObjects().add(reqAttributs); + authReq.setExtensions(extenstions); + + } + + // select message encoder + IEncoder binding = null; + if (endpoint.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { + binding = springContext.getBean("PVPRedirectBinding", RedirectBinding.class); + + } else if (endpoint.getBinding().equals(SAMLConstants.SAML2_POST_BINDING_URI)) { + binding = springContext.getBean("PVPPOSTBinding", PostBinding.class); + + } + + // encode message + binding.encodeRequest(null, httpResp, authReq, endpoint.getLocation(), + pendingReq.getPendingRequestId(), config.getAuthnRequestSigningCredential(), pendingReq); + } + +} diff --git a/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/impl/utils/AssertionAttributeExtractor.java b/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/impl/utils/AssertionAttributeExtractor.java index 22f1cb06..e0cad257 100644 --- a/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/impl/utils/AssertionAttributeExtractor.java +++ b/eaaf_modules/eaaf_module_pvp2_sp/src/main/java/at/gv/egiz/eaaf/modules/pvp2/sp/impl/utils/AssertionAttributeExtractor.java @@ -1,29 +1,22 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + package at.gv.egiz.eaaf.modules.pvp2.sp.impl.utils; import java.util.ArrayList; @@ -34,7 +27,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; - +import at.gv.egiz.eaaf.modules.pvp2.PvpConstants; +import at.gv.egiz.eaaf.modules.pvp2.sp.exception.AssertionAttributeExtractorExeption; import org.apache.commons.lang3.StringUtils; import org.opensaml.saml2.core.Assertion; import org.opensaml.saml2.core.Attribute; @@ -48,295 +42,316 @@ import org.opensaml.xml.XMLObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import at.gv.egiz.eaaf.modules.pvp2.PVPConstants; -import at.gv.egiz.eaaf.modules.pvp2.sp.exception.AssertionAttributeExtractorExeption; - public class AssertionAttributeExtractor { - - private static final Logger log = LoggerFactory.getLogger(AssertionAttributeExtractor.class); - - private Assertion assertion = null; - private Map> attributs = new HashMap>(); - //private PersonalAttributeList storkAttributes = new PersonalAttributeList(); - - private final List minimalMDSAttributeNamesList = Arrays.asList( - PVPConstants.PRINCIPAL_NAME_NAME, - PVPConstants.GIVEN_NAME_NAME, - PVPConstants.BIRTHDATE_NAME, - PVPConstants.BPK_NAME); - - private final List minimalIDLAttributeNamesList = Arrays.asList( - PVPConstants.EID_IDENTITY_LINK_NAME, - PVPConstants.EID_SOURCE_PIN_NAME, - PVPConstants.EID_SOURCE_PIN_TYPE_NAME); - - /** - * Parse the SAML2 Response element and extracts included information - *

    - * INFO: Actually, only the first SAML2 Assertion of the SAML2 Response is used! - * - * @param samlResponse SAML2 Response - * @throws AssertionAttributeExtractorExeption - */ - public AssertionAttributeExtractor(StatusResponseType samlResponse) throws AssertionAttributeExtractorExeption { - if (samlResponse != null && samlResponse instanceof Response) { - List assertions = ((Response) samlResponse).getAssertions(); - if (assertions.size() == 0) - throw new AssertionAttributeExtractorExeption("Assertion"); - - else if (assertions.size() > 1) - log.warn("Found more then ONE PVP2.1 assertions. Only the First is used."); - - assertion = assertions.get(0); - internalInitialize(); - - } else - throw new AssertionAttributeExtractorExeption(); - } - - /** - * Parse the SAML2 Assertion element and extracts included information - *

    - * - * @param assertion SAML2 Assertion - * @throws AssertionAttributeExtractorExeption - */ - public AssertionAttributeExtractor(Assertion assertion) throws AssertionAttributeExtractorExeption { - this.assertion = assertion; - internalInitialize(); - - } - - /** - * Get all SAML2 attributes from first SAML2 AttributeStatement element - * - * @return List of SAML2 Attributes - */ - public List getAllResponseAttributesFromFirstAttributeStatement() { - return assertion.getAttributeStatements().get(0).getAttributes(); - - } - - /** - * Get all SAML2 attributes of specific SAML2 AttributeStatement element - * - * @param attrStatementID List ID of the AttributeStatement element - * @return List of SAML2 Attributes - */ - public List getAllResponseAttributes(int attrStatementID) { - return assertion.getAttributeStatements().get(attrStatementID).getAttributes(); - - } - - /** - * check attributes from assertion with minimal required attribute list - * @return - */ - public boolean containsAllRequiredAttributes() { - return containsAllRequiredAttributes(minimalMDSAttributeNamesList) - || containsAllRequiredAttributes(minimalIDLAttributeNamesList); - - } - - /** - * check attributes from assertion with attributeNameList - * bPK or enc_bPK are always needed - * - * @param List of attributes which are required - * - * @return - */ - public boolean containsAllRequiredAttributes(Collection attributeNameList) { - - //first check if a bPK or an encrypted bPK is available - boolean flag = true; - for (String attr : attributeNameList) { - if (!attributs.containsKey(attr)) { - flag = false; - log.debug("Assertion contains no Attribute " + attr); - - } - - } - - if (flag) - return flag; - - else { - log.debug("Assertion contains no all minimum attributes from: " + attributeNameList.toString()); - return false; - - } - } - - public boolean containsAttribute(String attributeName) { - return attributs.containsKey(attributeName); - - } - - public String getSingleAttributeValue(String attributeName) { - if (attributs.containsKey(attributeName) && attributs.get(attributeName).size() > 0) - return attributs.get(attributeName).get(0); - else - return null; - - } - - public List getAttributeValues(String attributeName) { - return attributs.get(attributeName); - - } - - /** - * Return all include PVP attribute names - * - * @return - */ - public Set getAllIncludeAttributeNames() { - return attributs.keySet(); - - } - -// public PersonalAttributeList getSTORKAttributes() { -// return storkAttributes; -// } - - - public String getNameID() throws AssertionAttributeExtractorExeption { - if (assertion.getSubject() != null) { - Subject subject = assertion.getSubject(); - - if (subject.getNameID() != null) { - if (StringUtils.isNotEmpty(subject.getNameID().getValue())) - return subject.getNameID().getValue(); - - else - log.error("SAML2 NameID Element is empty."); - } - } - - throw new AssertionAttributeExtractorExeption("nameID"); - } - - /** - * Get the Id attribute from SAML2 assertion - * - * @return - */ - public String getAssertionID() { - return assertion.getID(); - - } - - public String getSessionIndex() throws AssertionAttributeExtractorExeption { - AuthnStatement authn = getAuthnStatement(); - - if (StringUtils.isNotEmpty(authn.getSessionIndex())) - return authn.getSessionIndex(); - - else - throw new AssertionAttributeExtractorExeption("SessionIndex"); - } - - /** - * @return - * @throws AssertionAttributeExtractorExeption - */ - public String getQAALevel() throws AssertionAttributeExtractorExeption { - AuthnStatement authn = getAuthnStatement(); - if (authn.getAuthnContext() != null && authn.getAuthnContext().getAuthnContextClassRef() != null) { - AuthnContextClassRef qaaClass = authn.getAuthnContext().getAuthnContextClassRef(); - - if (StringUtils.isNotEmpty(qaaClass.getAuthnContextClassRef())) - return qaaClass.getAuthnContextClassRef(); - - else - throw new AssertionAttributeExtractorExeption("AuthnContextClassRef (QAALevel)"); - } - - throw new AssertionAttributeExtractorExeption("AuthnContextClassRef"); - } - - public Assertion getFullAssertion() { - return assertion; - } - - - /** - * Get the Assertion validTo period - * - * Primarily, the 'SessionNotOnOrAfter' attribute in the SAML2 'AuthnStatment' element is used. - * If this is empty, this method returns value of SAML 'Conditions' element. - * - * @return Date, until this SAML2 assertion is valid - */ - public Date getAssertionNotOnOrAfter() { - if (getFullAssertion().getAuthnStatements() != null - && getFullAssertion().getAuthnStatements().size() > 0) { - for (AuthnStatement el : getFullAssertion().getAuthnStatements()) { - if (el.getSessionNotOnOrAfter() != null) - return (el.getSessionNotOnOrAfter().toDate()); - } - - } - - return getFullAssertion().getConditions().getNotOnOrAfter().toDate(); - - } - - /** - * Get the Assertion validFrom period - * - * This method returns value of SAML 'Conditions' element. - * - * @return Date, after this SAML2 assertion is valid, otherwise null - */ - public Date getAssertionNotBefore() { - try { - return getFullAssertion().getConditions().getNotBefore().toDate(); - - } catch (NullPointerException e) { - return null; - - } - - } - - private AuthnStatement getAuthnStatement() throws AssertionAttributeExtractorExeption { - List authnList = assertion.getAuthnStatements(); - if (authnList.size() == 0) - throw new AssertionAttributeExtractorExeption("AuthnStatement"); - - else if (authnList.size() > 1) - log.warn("Found more then ONE AuthnStatements in PVP2.1 assertions. Only the First is used."); - - return authnList.get(0); - } - - private void internalInitialize() { - if (assertion.getAttributeStatements() != null && - assertion.getAttributeStatements().size() > 0) { - AttributeStatement attrStat = assertion.getAttributeStatements().get(0); - for (Attribute attr : attrStat.getAttributes()) { - if (attr.getName().startsWith(PVPConstants.STORK_ATTRIBUTE_PREFIX)) { - List storkAttrValues = new ArrayList(); - for (XMLObject el : attr.getAttributeValues()) - storkAttrValues.add(el.getDOM().getTextContent()); - -// PersonalAttribute storkAttr = new PersonalAttribute(attr.getName(), -// false, storkAttrValues , "Available"); -// storkAttributes.put(attr.getName(), storkAttr ); - - } else { - List attrList = new ArrayList(); - for (XMLObject el : attr.getAttributeValues()) - attrList.add(el.getDOM().getTextContent()); - - attributs.put(attr.getName(), attrList); - - } - } - } - } + + private static final Logger log = LoggerFactory.getLogger(AssertionAttributeExtractor.class); + + private Assertion assertion = null; + private final Map> attributs = new HashMap<>(); + // private PersonalAttributeList storkAttributes = new PersonalAttributeList(); + + private final List minimalMdsAttributeNamesList = + Arrays.asList(PvpConstants.PRINCIPAL_NAME_NAME, PvpConstants.GIVEN_NAME_NAME, + PvpConstants.BIRTHDATE_NAME, PvpConstants.BPK_NAME); + + private final List minimalIdlAttributeNamesList = + Arrays.asList(PvpConstants.EID_IDENTITY_LINK_NAME, PvpConstants.EID_SOURCE_PIN_NAME, + PvpConstants.EID_SOURCE_PIN_TYPE_NAME); + + /** + * Parse the SAML2 Response element and extracts included information.
    + *
    + * INFO: Actually, only the first SAML2 Assertion of the SAML2 Response is used! + * + * @param samlResponse SAML2 Response + * @throws AssertionAttributeExtractorExeption In case of an error + */ + public AssertionAttributeExtractor(final StatusResponseType samlResponse) + throws AssertionAttributeExtractorExeption { + if (samlResponse != null && samlResponse instanceof Response) { + final List assertions = ((Response) samlResponse).getAssertions(); + if (assertions.size() == 0) { + throw new AssertionAttributeExtractorExeption("Assertion"); + } else if (assertions.size() > 1) { + log.warn("Found more then ONE PVP2.1 assertions. Only the First is used."); + } + + assertion = assertions.get(0); + internalInitialize(); + + } else { + throw new AssertionAttributeExtractorExeption(); + } + } + + /** + * Parse the SAML2 Assertion element and extracts included information.
    + *
    + * + * @param assertion SAML2 Assertion + * @throws AssertionAttributeExtractorExeption In case of an error + */ + public AssertionAttributeExtractor(final Assertion assertion) + throws AssertionAttributeExtractorExeption { + this.assertion = assertion; + internalInitialize(); + + } + + /** + * Get all SAML2 attributes from first SAML2 AttributeStatement element. + * + * @return List of SAML2 Attributes + */ + public List getAllResponseAttributesFromFirstAttributeStatement() { + return assertion.getAttributeStatements().get(0).getAttributes(); + + } + + /** + * Get all SAML2 attributes of specific SAML2 AttributeStatement element. + * + * @param attrStatementID List ID of the AttributeStatement element + * @return List of SAML2 Attributes + */ + public List getAllResponseAttributes(final int attrStatementID) { + return assertion.getAttributeStatements().get(attrStatementID).getAttributes(); + + } + + /** + * check attributes from assertion with minimal required attribute list. + * + * @return + */ + public boolean containsAllRequiredAttributes() { + return containsAllRequiredAttributes(minimalMdsAttributeNamesList) + || containsAllRequiredAttributes(minimalIdlAttributeNamesList); + + } + + /** + * check attributes from assertion with attributeNameList bPK or enc_bPK are always needed. + * + * @param attributeNameList List of attributes which are required + * + * @return + */ + public boolean containsAllRequiredAttributes(final Collection attributeNameList) { + + // first check if a bPK or an encrypted bPK is available + boolean flag = true; + for (final String attr : attributeNameList) { + if (!attributs.containsKey(attr)) { + flag = false; + log.debug("Assertion contains no Attribute " + attr); + + } + + } + + if (flag) { + return flag; + } else { + log.debug( + "Assertion contains no all minimum attributes from: " + attributeNameList.toString()); + return false; + + } + } + + public boolean containsAttribute(final String attributeName) { + return attributs.containsKey(attributeName); + + } + + /** + * Get single attribute with name. + * + * @param attributeName attribute Name + * @return Attribute value + */ + public String getSingleAttributeValue(final String attributeName) { + if (attributs.containsKey(attributeName) && attributs.get(attributeName).size() > 0) { + return attributs.get(attributeName).get(0); + } else { + return null; + } + + } + + public List getAttributeValues(final String attributeName) { + return attributs.get(attributeName); + + } + + /** + * Return all include PVP attribute names. + * + * @return + */ + public Set getAllIncludeAttributeNames() { + return attributs.keySet(); + + } + + /** + * Get User's nameId. + * + * @return nameId + * @throws AssertionAttributeExtractorExeption In case of an error + */ + public String getNameID() throws AssertionAttributeExtractorExeption { + if (assertion.getSubject() != null) { + final Subject subject = assertion.getSubject(); + + if (subject.getNameID() != null) { + if (StringUtils.isNotEmpty(subject.getNameID().getValue())) { + return subject.getNameID().getValue(); + } else { + log.error("SAML2 NameID Element is empty."); + } + } + } + + throw new AssertionAttributeExtractorExeption("nameID"); + } + + /** + * Get the Id attribute from SAML2 assertion. + * + * @return + */ + public String getAssertionID() { + return assertion.getID(); + + } + + /** + * Get SessionIndex from assertion. + * + * @return sessionIndex + * @throws AssertionAttributeExtractorExeption In case of an error + */ + public String getSessionIndex() throws AssertionAttributeExtractorExeption { + final AuthnStatement authn = getAuthnStatement(); + + if (StringUtils.isNotEmpty(authn.getSessionIndex())) { + return authn.getSessionIndex(); + } else { + throw new AssertionAttributeExtractorExeption("SessionIndex"); + } + } + + /** + * Get LoA from Assertion. + * + * @return LoA + * @throws AssertionAttributeExtractorExeption In case of an error + */ + public String getQaaLevel() throws AssertionAttributeExtractorExeption { + final AuthnStatement authn = getAuthnStatement(); + if (authn.getAuthnContext() != null + && authn.getAuthnContext().getAuthnContextClassRef() != null) { + final AuthnContextClassRef qaaClass = authn.getAuthnContext().getAuthnContextClassRef(); + + if (StringUtils.isNotEmpty(qaaClass.getAuthnContextClassRef())) { + return qaaClass.getAuthnContextClassRef(); + } else { + throw new AssertionAttributeExtractorExeption("AuthnContextClassRef (QAALevel)"); + } + } + + throw new AssertionAttributeExtractorExeption("AuthnContextClassRef"); + } + + public Assertion getFullAssertion() { + return assertion; + } + + + /** + * Get the Assertion validTo period. + * + *

    + * Primarily, the 'SessionNotOnOrAfter' attribute in the SAML2 'AuthnStatment' element is used. If + * this is empty, this method returns value of SAML 'Conditions' element. + *

    + * + * @return Date, until this SAML2 assertion is valid + */ + public Date getAssertionNotOnOrAfter() { + if (getFullAssertion().getAuthnStatements() != null + && getFullAssertion().getAuthnStatements().size() > 0) { + for (final AuthnStatement el : getFullAssertion().getAuthnStatements()) { + if (el.getSessionNotOnOrAfter() != null) { + return (el.getSessionNotOnOrAfter().toDate()); + } + } + + } + + return getFullAssertion().getConditions().getNotOnOrAfter().toDate(); + + } + + /** + * Get the Assertion validFrom period. + * + *

    + * This method returns value of SAML 'Conditions' element. + *

    + * + * @return Date, after this SAML2 assertion is valid, otherwise null + */ + public Date getAssertionNotBefore() { + try { + return getFullAssertion().getConditions().getNotBefore().toDate(); + + } catch (final NullPointerException e) { + return null; + + } + + } + + private AuthnStatement getAuthnStatement() throws AssertionAttributeExtractorExeption { + final List authnList = assertion.getAuthnStatements(); + if (authnList.size() == 0) { + throw new AssertionAttributeExtractorExeption("AuthnStatement"); + } else if (authnList.size() > 1) { + log.warn("Found more then ONE AuthnStatements in PVP2.1 assertions. Only the First is used."); + } + + return authnList.get(0); + } + + private void internalInitialize() { + if (assertion.getAttributeStatements() != null + && assertion.getAttributeStatements().size() > 0) { + final AttributeStatement attrStat = assertion.getAttributeStatements().get(0); + for (final Attribute attr : attrStat.getAttributes()) { + if (attr.getName().startsWith(PvpConstants.STORK_ATTRIBUTE_PREFIX)) { + final List storkAttrValues = new ArrayList<>(); + for (final XMLObject el : attr.getAttributeValues()) { + storkAttrValues.add(el.getDOM().getTextContent()); + } + + // PersonalAttribute storkAttr = new PersonalAttribute(attr.getName(), + // false, storkAttrValues , "Available"); + // storkAttributes.put(attr.getName(), storkAttr ); + + } else { + final List attrList = new ArrayList<>(); + for (final XMLObject el : attr.getAttributeValues()) { + attrList.add(el.getDOM().getTextContent()); + } + + attributs.put(attr.getName(), attrList); + + } + } + } + } } diff --git a/pom.xml b/pom.xml index e0a7ed6f..ee6b7d61 100644 --- a/pom.xml +++ b/pom.xml @@ -1,463 +1,631 @@ - - 4.0.0 - at.gv.egiz - eaaf - 1.1.0-SNAPSHOT - pom - - EGIZ EAAF components - - - - UTF-8 - 1.8 - - - ${project.version} - - - 0.4 - 0.3 - - 3.1.2 - 2.0.2 - - - 5.1 - 2.5.1_moa - 0.9_moa - 5.01 - 5.01 - 5.01 - 5.52_moa - 4.4 - 2.06 - 2.01_moa - 1.0.3_moa - 2.32_eval - 0.23 - 2.13_moa - 2.13_moa - - - - 5.1.5.RELEASE - 2.6.6 - 1.4.6 - 1.5.6 - 2.1.3 - 1.61 - 2.1.0.1 - 2.22.0 - 1.7.25 - 1.11 - 3.8.1 - 1.6 - 4.2 - 1.3.3 - 3.0.1 - 1.7 - 1.3.2 - 2.10.1 - 3.0.2 - - 4.5.7 - 4.4.11 - - 2.9.8 - 0.6.5 - - 1.1.6 - 2.11.0 - 2.7.1 - - - - - - default - - true - - default - - - - - egiz-commons - https://apps.egiz.gv.at/maven/ - - true - - - - shibboleth.internet2.edu - Internet2 - https://apps.egiz.gv.at/shibboleth_nexus/ - - - - - jenkinsDeploy - - - egizMaven - sftp://apps.egiz.gv.at/maven - - - egizMaven - sftp://apps.egiz.gv.at/maven-snapshot - - - - - egiz-commons - https://apps.egiz.gv.at/maven/ - - true - - - - shibboleth.internet2.edu - Internet2 - https://apps.egiz.gv.at/shibboleth_nexus/ - - - - - - org.apache.maven.plugins - maven-deploy-plugin - 2.8.2 - - true - - - - default-deploy - deploy - - deploy - - - - - - - - - - - eaaf_core_api - eaaf_core_utils - eaaf_core - eaaf_modules + + + 4.0.0 + at.gv.egiz + eaaf + 1.1.0-SNAPSHOT + pom + + EGIZ EAAF components + + + + UTF-8 + 1.8 + + + ${project.version} + + + 0.4 + 0.3 + + 3.1.2 + 2.0.2 + + + 5.1 + 2.5.1_moa + 0.9_moa + 5.01 + 5.01 + 5.01 + 5.52_moa + 4.4 + 2.06 + 2.01_moa + 1.0.3_moa + 2.32_eval + 0.23 + 2.13_moa + 2.13_moa + + + + 5.1.5.RELEASE + 2.6.6 + 1.4.6 + 1.5.6 + 2.1.3 + 1.61 + 2.1.0.1 + 2.22.0 + 1.7.25 + 1.11 + 3.8.1 + 1.6 + 4.2 + 1.3.3 + 3.0.1 + 1.7 + 1.3.2 + 2.10.1 + 3.0.2 + 28.1-jre + + 4.5.7 + 4.4.11 + + 2.9.8 + 0.6.5 + + 1.1.6 + 2.11.0 + 2.7.1 + + + + 3.1.0 + 3.12.0 + 3.1.12.2 + + ${project.build.directory}/thirdparty_licenses + ${maven.multiModuleProjectDirectory}/checks/egiz_pmd_checks.xml + + + + + + default + + true + + default + + + + + egiz-commons + https://apps.egiz.gv.at/maven/ + + true + + + + shibboleth.internet2.edu + Internet2 + https://apps.egiz.gv.at/shibboleth_nexus/ + + + + + jenkinsDeploy + + + egizMaven + sftp://apps.egiz.gv.at/maven + + + egizMaven + sftp://apps.egiz.gv.at/maven-snapshot + + + + + egiz-commons + https://apps.egiz.gv.at/maven/ + + true + + + + shibboleth.internet2.edu + Internet2 + https://apps.egiz.gv.at/shibboleth_nexus/ + + + + + + org.apache.maven.plugins + maven-deploy-plugin + 2.8.2 + + true + + + + default-deploy + deploy + + deploy + + + + + + + + + + + eaaf_core_api + eaaf_core_utils + eaaf_core + eaaf_modules - - - - - at.gv.egiz.eaaf - eaaf_core_api - ${egiz.eaaf.version} - - - at.gv.egiz.eaaf - eaaf_core_utils - ${egiz.eaaf.version} - - - at.gv.egiz.components - eventlog-api - ${at.gv.egiz.components.eventlog-api.version} - - - at.gv.egiz.components - egiz-spring-api - ${at.gv.egiz.components.egiz-spring-api} - - - - - MOA.spss.server - moa-sig-lib - ${MOA.spss.server.moa-sig-lib.version} - - - commons-logging - commons-logging - - - * - axis - - - - - MOA.spss - common - ${MOA.spss.server.moa-sig-lib.version} - - - MOA.spss - tsl_lib - ${MOA.spss.tsl_lib.version} - - - - - - iaik.prod - iaik_cms - ${iaik.prod.iaik_cms.version} - - - iaik.prod - iaik_cpades - ${iaik.prod.iaik_cpades.version} - - - iaik.prod - iaik_cpxlevel - ${iaik.prod.iaik_cpxlevel.version} - - - iaik.prod - iaik_eccelerate - ${iaik.prod.iaik_eccelerate.version} - - - iaik.prod - iaik_eccelerate_addon - ${iaik.prod.iaik_eccelerate_addon.version} - - - iaik.prod - iaik_eccelerate_cms - ${iaik.prod.iaik_eccelerate_cms.version} - - - iaik.prod - iaik_jce_full - ${iaik.prod.iaik_jce_full.version} - - - iaik.prod - iaik_jsse - ${iaik.prod.iaik_jsse.version} - - - iaik.prod - iaik_moa - ${iaik.prod.iaik_moa.version} - - - iaik.prod - iaik_pki_module - ${iaik.prod.iaik_pki_module.version} - - - iaik.prod - iaik_sva - ${iaik.prod.iaik_sva.version} - - - iaik.prod - iaik_tsp - ${iaik.prod.iaik_tsp.version} - - - iaik.prod - iaik_util - ${iaik.prod.iaik_util.version} - - - iaik.prod - iaik_xades - ${iaik.prod.iaik_xades.version} - - - iaik.prod - iaik_xsect - ${iaik.prod.iaik_xsect.version} - - - - - - - - - com.google.code.findbugs - jsr305 - ${jsr305.version} - - - - javax.annotation - javax.annotation-api - ${javax.annotation-api} - - - org.apache.commons - commons-collections4 - ${org.apache.commons-collections4} - - - org.springframework - spring-webmvc - ${org.springframework.version} - - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - org.slf4j - slf4j-log4j12 - ${org.slf4j.version} - - - commons-codec - commons-codec - ${commons-codec.version} - - - org.apache.commons - commons-lang3 - ${org.apache.commons-lang3.version} - - - org.apache.commons - commons-text - ${org.apache.commons-text.version} - - - commons-fileupload - commons-fileupload - ${commons-fileupload.version} - - - org.opensaml - opensaml - ${org.opensaml.version} - - - org.opensaml - xmltooling - ${org.opensaml.xmltooling.version} - - - org.opensaml - openws - ${org.opensaml.openws.version} - - - org.apache.santuario - xmlsec - ${org.apache.santuario.xmlsec.version} - - - org.bouncycastle - bcprov-jdk15on - ${org.bouncycastle.bcprov-jdk15on.version} - - - - org.owasp.esapi - esapi - ${org.owasp.esapi.version} - - - javax.servlet - javax.servlet-api - ${javax.servlet-api} - provided - - - org.apache.velocity - velocity - ${org.apache.velocity.version} - - - jaxen - jaxen - ${jaxen.jaxen.version} - - - xerces - xercesImpl - ${xerces.version} - - - xalan - xalan - ${xalan.version} - - - - org.apache.httpcomponents - httpclient - ${httpclient.version} - - - org.apache.httpcomponents - httpcore - ${httpcore.version} - - - - joda-time - joda-time - ${joda-time.version} - - - - com.fasterxml.jackson.core - jackson-databind - ${com.fasterxml.jackson.core.version} - - - org.bitbucket.b_c - jose4j - ${org.bitbucket.b_c.jose4j.version} - - - - - junit - junit - 4.12 - test - - - org.springframework - spring-test - ${org.springframework.version} - test - - - - - - - - org.apache.maven.wagon - wagon-ssh - 3.3.3 - - - - - - org.codehaus.mojo - versions-maven-plugin - 2.7 - - - - + + + + + at.gv.egiz.eaaf + eaaf_core_api + ${egiz.eaaf.version} + + + at.gv.egiz.eaaf + eaaf_core_utils + ${egiz.eaaf.version} + + + at.gv.egiz.components + eventlog-api + ${at.gv.egiz.components.eventlog-api.version} + + + at.gv.egiz.components + egiz-spring-api + ${at.gv.egiz.components.egiz-spring-api} + + + + + MOA.spss.server + moa-sig-lib + ${MOA.spss.server.moa-sig-lib.version} + + + commons-logging + commons-logging + + + * + axis + + + + + MOA.spss + common + ${MOA.spss.server.moa-sig-lib.version} + + + MOA.spss + tsl_lib + ${MOA.spss.tsl_lib.version} + + + + + + iaik.prod + iaik_cms + ${iaik.prod.iaik_cms.version} + + + iaik.prod + iaik_cpades + ${iaik.prod.iaik_cpades.version} + + + iaik.prod + iaik_cpxlevel + ${iaik.prod.iaik_cpxlevel.version} + + + iaik.prod + iaik_eccelerate + ${iaik.prod.iaik_eccelerate.version} + + + iaik.prod + iaik_eccelerate_addon + ${iaik.prod.iaik_eccelerate_addon.version} + + + iaik.prod + iaik_eccelerate_cms + ${iaik.prod.iaik_eccelerate_cms.version} + + + iaik.prod + iaik_jce_full + ${iaik.prod.iaik_jce_full.version} + + + iaik.prod + iaik_jsse + ${iaik.prod.iaik_jsse.version} + + + iaik.prod + iaik_moa + ${iaik.prod.iaik_moa.version} + + + iaik.prod + iaik_pki_module + ${iaik.prod.iaik_pki_module.version} + + + iaik.prod + iaik_sva + ${iaik.prod.iaik_sva.version} + + + iaik.prod + iaik_tsp + ${iaik.prod.iaik_tsp.version} + + + iaik.prod + iaik_util + ${iaik.prod.iaik_util.version} + + + iaik.prod + iaik_xades + ${iaik.prod.iaik_xades.version} + + + iaik.prod + iaik_xsect + ${iaik.prod.iaik_xsect.version} + + + + + + + + + com.google.code.findbugs + jsr305 + ${jsr305.version} + + + + javax.annotation + javax.annotation-api + ${javax.annotation-api} + + + org.apache.commons + commons-collections4 + ${org.apache.commons-collections4} + + + org.springframework + spring-webmvc + ${org.springframework.version} + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + org.slf4j + slf4j-log4j12 + ${org.slf4j.version} + + + commons-codec + commons-codec + ${commons-codec.version} + + + org.apache.commons + commons-lang3 + ${org.apache.commons-lang3.version} + + + org.apache.commons + commons-text + ${org.apache.commons-text.version} + + + commons-fileupload + commons-fileupload + ${commons-fileupload.version} + + + org.opensaml + opensaml + ${org.opensaml.version} + + + org.opensaml + xmltooling + ${org.opensaml.xmltooling.version} + + + org.opensaml + openws + ${org.opensaml.openws.version} + + + org.apache.santuario + xmlsec + ${org.apache.santuario.xmlsec.version} + + + org.bouncycastle + bcprov-jdk15on + ${org.bouncycastle.bcprov-jdk15on.version} + + + + org.owasp.esapi + esapi + ${org.owasp.esapi.version} + + + javax.servlet + javax.servlet-api + ${javax.servlet-api} + provided + + + org.apache.velocity + velocity + ${org.apache.velocity.version} + + + jaxen + jaxen + ${jaxen.jaxen.version} + + + xerces + xercesImpl + ${xerces.version} + + + xalan + xalan + ${xalan.version} + + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + org.apache.httpcomponents + httpcore + ${httpcore.version} + + + + joda-time + joda-time + ${joda-time.version} + + + + com.fasterxml.jackson.core + jackson-databind + ${com.fasterxml.jackson.core.version} + + + org.bitbucket.b_c + jose4j + ${org.bitbucket.b_c.jose4j.version} + + + + com.google.guava + guava + ${com.google.guava.version} + + + + + junit + junit + 4.12 + test + + + org.springframework + spring-test + ${org.springframework.version} + test + + + + + + + + org.apache.maven.wagon + wagon-ssh + 3.3.3 + + + + + + org.codehaus.mojo + versions-maven-plugin + 2.7 + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + ${maven-checkstyle-plugin.version} + + checks/egiz_checks.xml + checks/checkstyleSuppress.xml + false + false + warning + false + + + + + validate + test + + check + + + + + + com.puppycrawl.tools + checkstyle + 8.26 + + + + + + org.jacoco + jacoco-maven-plugin + + + pre-unit-test + + prepare-agent + + + + post-unit-report + test + + report + + + target/jacoco-report + + + + post-unit-check + test + + check + + + false + + + BUNDLE + + + INSTRUCTION + COVEREDRATIO + 0.70 + + + BRANCH + COVEREDRATIO + 0.70 + + + + + + + + + + + + org.apache.maven.plugins + maven-pmd-plugin + ${maven-pmd-plugin.version} + + + pmd_validate + test + + check + + + + + true + utf-8 + 100 + 1.8 + false + true + + ${pmw_rules_location} + + + + + + com.github.spotbugs + spotbugs-maven-plugin + ${spotbugs-maven-plugin.version} + + + spotbugs_validate + test + + check + + + + + false + + + + + + + + + + + org.jacoco + jacoco-maven-plugin + + + + report + + + + + + org.apache.maven.plugins + maven-pmd-plugin + ${maven-pmd-plugin.version} + + + + \ No newline at end of file -- cgit v1.2.3