From 578ad0d6bc408edf9e6c875156054374f5fd8337 Mon Sep 17 00:00:00 2001 From: Thomas <> Date: Mon, 22 Mar 2021 18:40:26 +0100 Subject: change to EGIZ codestyle --- moaSig/build.gradle | 9 + .../at/gv/egovernment/moaspss/logging/LogMsg.java | 26 +- .../at/gv/egovernment/moaspss/logging/Logger.java | 161 +- .../moaspss/logging/LoggingContext.java | 21 +- .../moaspss/logging/LoggingContextManager.java | 25 +- .../gv/egovernment/moaspss/util/Base64Utils.java | 92 +- .../at/gv/egovernment/moaspss/util/BoolUtils.java | 15 +- .../egovernment/moaspss/util/CollectionUtils.java | 29 +- .../at/gv/egovernment/moaspss/util/Constants.java | 649 +++---- .../at/gv/egovernment/moaspss/util/DOMUtils.java | 1153 ++++++------ .../gv/egovernment/moaspss/util/DateTimeUtils.java | 344 ++-- .../java/at/gv/egovernment/moaspss/util/Empty.java | 18 +- .../moaspss/util/EntityResolverChain.java | 33 +- .../at/gv/egovernment/moaspss/util/FileUtils.java | 160 +- .../gv/egovernment/moaspss/util/KeyStoreUtils.java | 243 +-- .../moaspss/util/MOADefaultHandler.java | 30 +- .../moaspss/util/MOAEntityResolver.java | 55 +- .../egovernment/moaspss/util/MOAErrorHandler.java | 73 +- .../at/gv/egovernment/moaspss/util/MOATimer.java | 46 +- .../egovernment/moaspss/util/MessageProvider.java | 29 +- .../at/gv/egovernment/moaspss/util/Messages.java | 55 +- .../at/gv/egovernment/moaspss/util/MiscUtil.java | 469 +++-- .../moaspss/util/NodeIteratorAdapter.java | 15 +- .../egovernment/moaspss/util/NodeListAdapter.java | 15 +- .../egovernment/moaspss/util/OutputXML2File.java | 116 +- .../moaspss/util/ResourceBundleChain.java | 27 +- .../at/gv/egovernment/moaspss/util/SSLUtils.java | 399 ++-- .../moaspss/util/StreamEntityResolver.java | 47 +- .../gv/egovernment/moaspss/util/StreamUtils.java | 118 +- .../gv/egovernment/moaspss/util/StringUtils.java | 159 +- .../at/gv/egovernment/moaspss/util/URLDecoder.java | 50 +- .../at/gv/egovernment/moaspss/util/URLEncoder.java | 55 +- .../egovernment/moaspss/util/XPathException.java | 29 +- .../at/gv/egovernment/moaspss/util/XPathUtils.java | 477 +++-- .../moaspss/util/ex/EgovUtilException.java | 32 +- moaSig/moa-asic/build.gradle | 9 +- .../src/main/java/at/gv/egiz/asic/api/ASiC.java | 16 +- .../java/at/gv/egiz/asic/api/ASiCConstants.java | 4 +- .../main/java/at/gv/egiz/asic/api/ASiCEntry.java | 56 +- .../main/java/at/gv/egiz/asic/api/ASiCFactory.java | 278 +-- .../main/java/at/gv/egiz/asic/api/ASiCFormat.java | 4 +- .../gv/egiz/asic/api/ASiCVerificationResult.java | 48 +- .../java/at/gv/egiz/asic/api/ASiCVerifier.java | 7 +- .../exceptions/ASiCContainerInvalidException.java | 6 +- .../gv/egiz/asic/impl/ASiCBaseFormatFactory.java | 202 +- .../java/at/gv/egiz/asic/impl/ASiCContainer.java | 27 +- .../egiz/asic/impl/ASiCExtendedFormatFactory.java | 62 +- .../main/java/at/gv/egiz/asic/impl/ASiCImpl.java | 107 +- .../java/at/gv/egiz/asic/impl/ASiCMOAVerifier.java | 101 +- .../gv/egiz/asic/impl/ASiCSimpleFormatFactory.java | 71 +- .../egiz/asic/impl/AsicSignedFilesContainer.java | 67 +- .../java/at/gv/egiz/asic/impl/EntryHandler.java | 9 +- .../main/java/at/gv/egiz/asic/impl/Verifier.java | 12 +- .../gv/egiz/asic/impl/ZipCommentReaderStream.java | 250 ++- .../gv/egiz/asic/impl/handler/AllDataHandler.java | 29 +- .../at/gv/egiz/asic/impl/handler/BaseHandler.java | 27 +- .../at/gv/egiz/asic/impl/handler/CAdESHandler.java | 11 +- .../impl/handler/EvidenceERSRecordHandler.java | 11 +- .../impl/handler/EvidenceXMLRecordHandler.java | 8 +- .../impl/handler/ExtendedASiCCAdESHandler.java | 11 +- .../impl/handler/ExtendedASiCXAdESHandler.java | 16 +- .../handler/ExtendedEvidenceERSRecordHandler.java | 9 +- .../handler/ExtendedEvidenceXMLRecordHandler.java | 9 +- .../gv/egiz/asic/impl/handler/HandlerSorter.java | 12 +- .../gv/egiz/asic/impl/handler/MetaInfHandler.java | 36 +- .../gv/egiz/asic/impl/handler/MimefileHandler.java | 41 +- .../egiz/asic/impl/handler/SignatureHandler.java | 39 +- .../asic/impl/handler/SimpleASiCCAdESHandler.java | 8 +- .../asic/impl/handler/SimpleASiCXAdESHandler.java | 8 +- .../handler/SimpleEvidenceERSRecordHandler.java | 8 +- .../handler/SimpleEvidenceXMLRecordHandler.java | 8 +- .../at/gv/egiz/asic/impl/handler/XAdESHandler.java | 8 +- .../gv/egiz/asic/impl/verifier/BaseVerifier.java | 82 +- .../gv/egiz/asic/impl/verifier/CAdESVerifier.java | 50 +- .../asic/impl/verifier/ExtendedCAdESVerifier.java | 293 +-- .../asic/impl/verifier/ExtendedXAdESVerifier.java | 345 ++-- .../asic/impl/verifier/SimpleCAdESVerifier.java | 47 +- .../asic/impl/verifier/SimpleXAdESVerifier.java | 209 ++- .../gv/egiz/asic/impl/verifier/XAdESVerifier.java | 66 +- .../xmlbind/VerifyASICSignatureRequestParser.java | 79 +- .../VerifyASICSignatureResponseBuilder.java | 206 ++- .../at/gv/egiz/asic/xmlbind/VerifyASiCRequest.java | 72 +- .../moa/spss/MOAApplicationException.java | 44 +- .../at/gv/egovernment/moa/spss/MOAException.java | 76 +- .../egovernment/moa/spss/MOARuntimeException.java | 84 +- .../egovernment/moa/spss/MOASystemException.java | 36 +- .../gv/egovernment/moa/spss/OutputConstants.java | 13 +- .../gv/egovernment/moa/spss/api/Configurator.java | 51 +- .../gv/egovernment/moa/spss/api/SPSSFactory.java | 1195 ++++++------ .../moa/spss/api/SignatureCreationService.java | 36 +- .../moa/spss/api/SignatureVerificationService.java | 43 +- .../moa/spss/api/cmssign/CMSSignatureResponse.java | 12 +- .../api/cmssign/CreateCMSSignatureRequest.java | 17 +- .../api/cmssign/CreateCMSSignatureResponse.java | 9 +- .../cmssign/CreateCMSSignatureResponseElement.java | 22 +- .../moa/spss/api/cmssign/DataObjectInfo.java | 17 +- .../moa/spss/api/cmssign/SingleSignatureInfo.java | 31 +- .../moa/spss/api/cmsverify/CMSContent.java | 17 +- .../spss/api/cmsverify/CMSContentExcplicit.java | 7 +- .../spss/api/cmsverify/CMSContentReference.java | 7 +- .../moa/spss/api/cmsverify/CMSDataObject.java | 25 +- .../api/cmsverify/VerifyCMSSignatureRequest.java | 51 +- .../api/cmsverify/VerifyCMSSignatureResponse.java | 13 +- .../VerifyCMSSignatureResponseElement.java | 41 +- .../moa/spss/api/common/Base64Transform.java | 7 +- .../spss/api/common/CanonicalizationTransform.java | 9 +- .../moa/spss/api/common/CheckResult.java | 12 +- .../egovernment/moa/spss/api/common/Content.java | 26 +- .../moa/spss/api/common/ContentBinary.java | 13 +- .../moa/spss/api/common/ContentLocRef.java | 13 +- .../moa/spss/api/common/ContentReference.java | 3 +- .../moa/spss/api/common/ContentXML.java | 7 +- .../moa/spss/api/common/ElementSelector.java | 16 +- .../api/common/EnvelopedSignatureTransform.java | 7 +- .../common/ExclusiveCanonicalizationTransform.java | 13 +- .../api/common/ExtendedCertificateCheckResult.java | 50 +- .../egovernment/moa/spss/api/common/InputData.java | 55 +- .../egovernment/moa/spss/api/common/MetaInfo.java | 24 +- .../moa/spss/api/common/SignerInfo.java | 76 +- .../moa/spss/api/common/TSLConfiguration.java | 65 +- .../egovernment/moa/spss/api/common/Transform.java | 7 +- .../egovernment/moa/spss/api/common/TslInfos.java | 78 +- .../moa/spss/api/common/X509IssuerSerial.java | 12 +- .../spss/api/common/XMLDataObjectAssociation.java | 13 +- .../moa/spss/api/common/XPathFilter.java | 29 +- .../moa/spss/api/common/XPathFilter2Transform.java | 15 +- .../moa/spss/api/common/XPathTransform.java | 22 +- .../moa/spss/api/common/XSLTTransform.java | 11 +- .../moa/spss/api/impl/AdESFormResultsImpl.java | 70 +- .../moa/spss/api/impl/Base64TransformImpl.java | 7 +- .../moa/spss/api/impl/CMSContentExplicitImpl.java | 11 +- .../moa/spss/api/impl/CMSContentReferenceImpl.java | 11 +- .../moa/spss/api/impl/CMSDataObjectImpl.java | 33 +- .../spss/api/impl/CMSSignatureResponseImpl.java | 15 +- .../api/impl/CanonicalizationTransformImpl.java | 15 +- .../moa/spss/api/impl/CheckResultImpl.java | 13 +- .../moa/spss/api/impl/ContentBinaryImpl.java | 11 +- .../egovernment/moa/spss/api/impl/ContentImpl.java | 6 +- .../moa/spss/api/impl/ContentLocRefImpl.java | 32 +- .../moa/spss/api/impl/ContentReferenceImpl.java | 10 +- .../moa/spss/api/impl/ContentXMLImpl.java | 11 +- .../api/impl/CreateCMSSignatureRequestImpl.java | 21 +- .../api/impl/CreateCMSSignatureResponseImpl.java | 14 +- ...ateSignatureEnvironmentProfileExplicitImpl.java | 29 +- .../CreateSignatureEnvironmentProfileIDImpl.java | 11 +- .../moa/spss/api/impl/CreateSignatureInfoImpl.java | 19 +- .../spss/api/impl/CreateSignatureLocationImpl.java | 10 +- .../spss/api/impl/CreateTransformsInfoImpl.java | 15 +- .../CreateTransformsInfoProfileExplicitImpl.java | 20 +- .../impl/CreateTransformsInfoProfileIDImpl.java | 10 +- .../api/impl/CreateXMLSignatureRequestImpl.java | 21 +- .../api/impl/CreateXMLSignatureResponseImpl.java | 14 +- .../moa/spss/api/impl/DataObjectInfoCMSImpl.java | 10 +- .../moa/spss/api/impl/DataObjectInfoImpl.java | 26 +- .../moa/spss/api/impl/ElementSelectorImpl.java | 13 +- .../api/impl/EnvelopedSignatureTransformImpl.java | 7 +- .../moa/spss/api/impl/ErrorResponseImpl.java | 14 +- .../ExclusiveCanonicalizationTransformImpl.java | 27 +- .../impl/ExtendedCertificateCheckResultImpl.java | 74 +- .../moa/spss/api/impl/InputDataBinaryImpl.java | 85 +- .../moa/spss/api/impl/InputDataXMLImpl.java | 80 +- .../spss/api/impl/ManifestRefsCheckResultImpl.java | 9 +- .../api/impl/ManifestRefsCheckResultInfoImpl.java | 19 +- .../moa/spss/api/impl/MetaInfoImpl.java | 17 +- .../moa/spss/api/impl/ReferenceInfoImpl.java | 20 +- .../spss/api/impl/ReferencesCheckResultImpl.java | 22 +- .../api/impl/ReferencesCheckResultInfoImpl.java | 14 +- .../moa/spss/api/impl/SPSSFactoryImpl.java | 1048 ++++++----- .../api/impl/SignatureEnvironmentResponseImpl.java | 13 +- .../api/impl/SignatureManifestCheckParamsImpl.java | 19 +- .../moa/spss/api/impl/SignerInfoImpl.java | 137 +- .../spss/api/impl/SingleSignatureInfoCMSImpl.java | 15 +- .../moa/spss/api/impl/SingleSignatureInfoImpl.java | 10 +- .../api/impl/SupplementProfileExplicitImpl.java | 11 +- .../moa/spss/api/impl/SupplementProfileIDImpl.java | 11 +- .../moa/spss/api/impl/TSLConfigurationImpl.java | 134 +- .../moa/spss/api/impl/TransformImpl.java | 4 +- .../api/impl/TransformParameterBinaryImpl.java | 15 +- .../moa/spss/api/impl/TransformParameterImpl.java | 4 +- .../spss/api/impl/TransformParameterURIImpl.java | 10 +- .../spss/api/impl/TransformPatameterHashImpl.java | 17 +- .../moa/spss/api/impl/TslInfosImpl.java | 100 +- .../api/impl/VerifyCMSSignatureRequestImpl.java | 43 +- .../VerifyCMSSignatureResponseElementImpl.java | 106 +- .../api/impl/VerifyCMSSinatureResponseImpl.java | 14 +- .../moa/spss/api/impl/VerifySignatureInfoImpl.java | 16 +- .../spss/api/impl/VerifySignatureLocationImpl.java | 7 +- .../spss/api/impl/VerifyTransformsDataImpl.java | 16 +- .../VerifyTransformsInfoProfileExplicitImpl.java | 20 +- .../impl/VerifyTransformsInfoProfileIDImpl.java | 9 +- .../api/impl/VerifyXMLSignatureRequestImpl.java | 220 +-- .../api/impl/VerifyXMLSignatureResponseImpl.java | 325 ++-- .../moa/spss/api/impl/X509IssuerSerialImpl.java | 9 +- .../api/impl/XMLDataObjectAssociationImpl.java | 8 +- .../spss/api/impl/XPathFilter2TransformImpl.java | 23 +- .../moa/spss/api/impl/XPathFilterImpl.java | 23 +- .../moa/spss/api/impl/XPathTransformImpl.java | 26 +- .../moa/spss/api/impl/XSLTransformImpl.java | 8 +- .../xmlbind/CreateCMSSignatureRequestParser.java | 214 ++- .../xmlbind/CreateCMSSignatureResponseBuilder.java | 113 +- .../xmlbind/CreateXMLSignatureRequestParser.java | 243 ++- .../xmlbind/CreateXMLSignatureResponseBuilder.java | 82 +- .../moa/spss/api/xmlbind/ProfileParser.java | 246 +-- .../moa/spss/api/xmlbind/RequestParserUtils.java | 310 ++-- .../moa/spss/api/xmlbind/ResponseBuilderUtils.java | 601 +++--- .../moa/spss/api/xmlbind/TransformParser.java | 149 +- .../xmlbind/VerifyCMSSignatureRequestParser.java | 216 +-- .../xmlbind/VerifyCMSSignatureResponseBuilder.java | 164 +- .../xmlbind/VerifyPDFSignatureResponseBuilder.java | 184 +- .../xmlbind/VerifyXMLSignatureRequestParser.java | 440 +++-- .../xmlbind/VerifyXMLSignatureResponseBuilder.java | 612 +++--- .../xmlsign/CreateSignatureEnvironmentProfile.java | 25 +- .../CreateSignatureEnvironmentProfileExplicit.java | 23 +- .../CreateSignatureEnvironmentProfileID.java | 11 +- .../moa/spss/api/xmlsign/CreateSignatureInfo.java | 8 +- .../spss/api/xmlsign/CreateSignatureLocation.java | 13 +- .../moa/spss/api/xmlsign/CreateTransformsInfo.java | 12 +- .../api/xmlsign/CreateTransformsInfoProfile.java | 17 +- .../CreateTransformsInfoProfileExplicit.java | 14 +- .../api/xmlsign/CreateTransformsInfoProfileID.java | 9 +- .../api/xmlsign/CreateXMLSignatureRequest.java | 15 +- .../api/xmlsign/CreateXMLSignatureResponse.java | 9 +- .../xmlsign/CreateXMLSignatureResponseElement.java | 22 +- .../moa/spss/api/xmlsign/DataObjectInfo.java | 32 +- .../moa/spss/api/xmlsign/ErrorResponse.java | 13 +- .../api/xmlsign/SignatureEnvironmentResponse.java | 11 +- .../moa/spss/api/xmlsign/SingleSignatureInfo.java | 21 +- .../moa/spss/api/xmlverify/AdESFormResults.java | 8 +- .../api/xmlverify/ManifestRefsCheckResult.java | 13 +- .../api/xmlverify/ManifestRefsCheckResultInfo.java | 12 +- .../moa/spss/api/xmlverify/ReferenceInfo.java | 7 +- .../spss/api/xmlverify/ReferencesCheckResult.java | 16 +- .../api/xmlverify/ReferencesCheckResultInfo.java | 14 +- .../xmlverify/SignatureManifestCheckParams.java | 14 +- .../moa/spss/api/xmlverify/SupplementProfile.java | 14 +- .../api/xmlverify/SupplementProfileExplicit.java | 7 +- .../spss/api/xmlverify/SupplementProfileID.java | 10 +- .../moa/spss/api/xmlverify/TransformParameter.java | 34 +- .../api/xmlverify/TransformParameterBinary.java | 11 +- .../spss/api/xmlverify/TransformParameterHash.java | 14 +- .../spss/api/xmlverify/TransformParameterURI.java | 3 +- .../spss/api/xmlverify/VerifySignatureInfo.java | 18 +- .../api/xmlverify/VerifySignatureLocation.java | 3 +- .../api/xmlverify/VerifyTransformsInfoProfile.java | 19 +- .../VerifyTransformsInfoProfileExplicit.java | 12 +- .../xmlverify/VerifyTransformsInfoProfileID.java | 7 +- .../api/xmlverify/VerifyXMLSignatureRequest.java | 57 +- .../api/xmlverify/VerifyXMLSignatureResponse.java | 59 +- .../spss/server/config/CRLDistributionPoint.java | 277 +-- .../spss/server/config/ConfigurationException.java | 23 +- .../server/config/ConfigurationPartsBuilder.java | 1943 ++++++++++---------- .../spss/server/config/ConfigurationProvider.java | 689 ++++--- .../moa/spss/server/config/DistributionPoint.java | 26 +- .../spss/server/config/HardwareCryptoModule.java | 30 +- .../moa/spss/server/config/HardwareKeyModule.java | 35 +- .../moa/spss/server/config/IssuerAndSerial.java | 57 +- .../moa/spss/server/config/KeyGroup.java | 37 +- .../moa/spss/server/config/KeyGroupEntry.java | 58 +- .../moa/spss/server/config/KeyModule.java | 12 +- .../spss/server/config/OCSPDistributionPoint.java | 19 +- .../moa/spss/server/config/SoftwareKeyModule.java | 22 +- .../moa/spss/server/config/TrustProfile.java | 233 +-- .../cmssign/CMSSignatureCreationProfileImpl.java | 288 ++- .../CMSSignatureVerificationProfileImpl.java | 46 +- .../PDFSignatureVerificationProfileImpl.java | 2 +- .../config/AbstractKeyModuleConfigurationImpl.java | 16 +- .../config/AbstractObservableConfiguration.java | 12 +- .../iaik/config/ArchiveConfigurationImpl.java | 87 +- .../moa/spss/server/iaik/config/CRLRetriever.java | 104 +- .../iaik/config/CertStoreConfigurationImpl.java | 92 +- .../server/iaik/config/ConfigurationDataImpl.java | 64 +- .../iaik/config/DataBaseArchiveParameterImpl.java | 8 +- .../config/DirectoryCertStoreParametersImpl.java | 49 +- .../HardwareCryptoModuleConfigurationImpl.java | 25 +- .../config/HardwareKeyModuleConfigurationImpl.java | 21 +- .../spss/server/iaik/config/IaikConfigurator.java | 185 +- .../spss/server/iaik/config/LoggerConfigImpl.java | 12 +- .../server/iaik/config/PKIConfigurationImpl.java | 131 +- .../iaik/config/RevocationConfigurationImpl.java | 143 +- .../config/SoftwareKeyModuleConfigurationImpl.java | 32 +- .../iaik/config/ValidationConfigurationImpl.java | 22 +- .../moa/spss/server/iaik/pki/PKIProfileImpl.java | 361 ++-- .../pki/pathvalidation/ValidationProfileImpl.java | 47 +- .../iaik/pki/revocation/RevocationProfileImpl.java | 33 +- .../store/truststore/TrustStoreProfileImpl.java | 93 +- .../server/iaik/xml/Base64TransformationImpl.java | 29 +- .../server/iaik/xml/ByteArrayDataObjectImpl.java | 27 +- .../server/iaik/xml/ByteStreamDataObjectImpl.java | 18 +- .../spss/server/iaik/xml/CanonicalizationImpl.java | 27 +- .../moa/spss/server/iaik/xml/DataObjectImpl.java | 25 +- .../xml/EnvelopedSignatureTransformationImpl.java | 22 +- .../iaik/xml/ExclusiveCanonicalizationImpl.java | 53 +- .../moa/spss/server/iaik/xml/SigningTimeImpl.java | 12 +- .../spss/server/iaik/xml/TransformationImpl.java | 15 +- .../spss/server/iaik/xml/XMLDataObjectImpl.java | 21 +- .../server/iaik/xml/XMLNodeListDataObjectImpl.java | 14 +- .../moa/spss/server/iaik/xml/XMLSignatureImpl.java | 14 +- .../moa/spss/server/iaik/xml/XPath2FilterImpl.java | 45 +- .../server/iaik/xml/XPath2TransformationImpl.java | 31 +- .../server/iaik/xml/XPathTransformationImpl.java | 43 +- .../server/iaik/xml/XSLTTransformationImpl.java | 350 ++-- .../iaik/xmlsign/DataObjectTreatmentImpl.java | 51 +- .../xmlsign/XMLSignatureCreationProfileImpl.java | 320 ++-- .../xmlsign/XMLSignatureInsertionLocationImpl.java | 18 +- .../XMLSignatureVerificationProfileImpl.java | 57 +- .../moa/spss/server/init/ConfiguratorImpl.java | 38 +- .../moa/spss/server/init/ExternalInitializer.java | 2 +- .../server/init/StartupConfigurationHolder.java | 62 +- .../moa/spss/server/init/SystemInitializer.java | 263 ++- .../server/invoke/CMSSignatureCreationInvoker.java | 529 +++--- .../invoke/CMSSignatureVerificationInvoker.java | 887 ++++----- .../CMSSignatureVerificationProfileFactory.java | 57 +- .../invoke/CreateCMSSignatureResponseBuilder.java | 50 +- .../invoke/CreateXMLSignatureResponseBuilder.java | 50 +- .../moa/spss/server/invoke/DataObjectFactory.java | 895 +++++---- .../spss/server/invoke/ExternalURIResolver.java | 83 +- .../spss/server/invoke/IaikExceptionMapper.java | 246 +-- .../moa/spss/server/invoke/InvokerUtils.java | 47 +- .../moa/spss/server/invoke/ProfileMapper.java | 187 +- .../spss/server/invoke/ServiceContextUtils.java | 32 +- .../invoke/SignatureCreationServiceImpl.java | 22 +- .../invoke/SignatureVerificationServiceImpl.java | 38 +- .../spss/server/invoke/TransformationFactory.java | 165 +- .../invoke/VerifyCMSSignatureResponseBuilder.java | 259 +-- .../invoke/VerifyXMLSignatureResponseBuilder.java | 546 +++--- .../server/invoke/XMLSignatureCreationInvoker.java | 532 +++--- .../invoke/XMLSignatureCreationProfileFactory.java | 479 ++--- .../invoke/XMLSignatureVerificationInvoker.java | 1310 +++++++------ .../XMLSignatureVerificationProfileFactory.java | 103 +- .../moa/spss/server/logging/IaikLog.java | 37 +- .../moa/spss/server/logging/IaikLogFactory.java | 27 +- .../moa/spss/server/logging/IaikLogMsg.java | 37 +- .../moa/spss/server/logging/TransactionId.java | 17 +- .../server/monitoring/ServiceStatusContainer.java | 67 +- .../server/service/RevocationArchiveCleaner.java | 52 +- .../server/transaction/DeleteableDataSource.java | 2 +- .../server/transaction/TransactionContext.java | 287 +-- .../transaction/TransactionContextManager.java | 21 +- .../server/transaction/TransactionIDGenerator.java | 27 +- .../moa/spss/server/util/IdGenerator.java | 43 +- .../moa/spss/tsl/TSLServiceFactory.java | 106 +- .../moa/spss/tsl/timer/TSLUpdaterTimerTask.java | 94 +- .../moa/spss/tsl/utils/CertificateReader.java | 198 +- .../egovernment/moa/spss/util/AdESResultUtils.java | 430 +++-- .../moa/spss/util/CertStoreConverter.java | 184 +- .../moa/spss/util/CertificateUtils.java | 720 ++++---- .../moa/spss/util/ExternalURIVerifier.java | 196 +- .../moa/spss/util/FilteredOutputStream.java | 126 +- .../moa/spss/util/MOASPSSEntityResolver.java | 64 +- .../egovernment/moa/spss/util/MessageProvider.java | 32 +- .../spss/util/NodeListToNodeSetDataAdapter.java | 24 +- .../gv/egovernment/moa/spss/util/QCSSCDResult.java | 92 +- .../moa/spss/util/ResetableInputStreamWrapper.java | 100 +- .../moa/spss/util/SecProviderUtils.java | 25 +- moaSig/moa-sig/build.gradle | 2 + .../spss/server/initializer/PDFASInitializer.java | 31 +- .../moa/spss/server/invoke/PDFASInvoker.java | 192 +- .../spss/server/pdfas/ExtendedVerifyResult.java | 94 +- .../spss/server/pdfas/InternalMoaConnector.java | 391 ++-- .../moa/spss/server/pdfas/InternalMoaVerifier.java | 224 +-- .../moa/spss/server/service/AxisHandler.java | 858 +++++---- .../server/service/CertificateProviderServlet.java | 295 ++- .../spss/server/service/ConfigurationServlet.java | 58 +- .../service/DeleteableDataSourceWrapper.java | 63 +- .../moa/spss/server/service/ServiceUtils.java | 51 +- .../server/service/SignatureCreationService.java | 435 +++-- .../service/SignatureVerificationService.java | 424 +++-- .../server/service/TSLClientStatusServlet.java | 126 +- .../webservice/CMSCreateSignatureBinding.java | 8 +- .../webservice/CMSVerifySignatureBinding.java | 22 +- .../webservice/PDFCreateSignatureBinding.java | 8 +- .../webservice/SignatureCreationService.java | 38 +- .../webservice/SignatureVerificationService.java | 36 +- .../webservice/XMLCreateSignatureBinding.java | 8 +- .../webservice/XMLVerifySignatureBinding.java | 8 +- .../moa/spss/server/xmlbind/CreatePDFRequest.java | 24 +- .../moa/spss/server/xmlbind/CreatePDFRespone.java | 16 +- .../xmlbind/CreatePDFSignatureRequestParser.java | 187 +- .../xmlbind/CreatePDFSignatureResponseBuilder.java | 215 ++- .../moa/spss/server/xmlbind/PDFSignatureInfo.java | 50 +- .../moa/spss/server/xmlbind/SignedPDFInfo.java | 98 +- .../moa/spss/server/xmlbind/VerifyPDFRequest.java | 60 +- .../server/xmlbind/VerifyPDFRequestParser.java | 86 +- .../moa/spss/server/xmlbind/VerifyPDFResponse.java | 25 +- .../server/xmlbind/VerifyPDFResponseBuilder.java | 167 +- 385 files changed, 19491 insertions(+), 19481 deletions(-) (limited to 'moaSig') diff --git a/moaSig/build.gradle b/moaSig/build.gradle index 7a30bcc..accdcad 100644 --- a/moaSig/build.gradle +++ b/moaSig/build.gradle @@ -18,6 +18,10 @@ subprojects { mavenCentral() } + tasks.withType(JavaCompile) { + options.compilerArgs << '-Xlint:-options' + } + dependencies { testCompile 'junit:junit:4.12' } @@ -25,6 +29,11 @@ subprojects { version = '3.1.4-RC1' jar { manifest.attributes provider: 'EGIZ', 'Specification-Version': getCheckedOutGitCommitHash(), 'Implementation-Version': project.version } + + compileJava { + sourceCompatibility = 1.7 + targetCompatibility = 1.7 + } publishing { diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/logging/LogMsg.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/logging/LogMsg.java index 9eb84fa..54ab102 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/logging/LogMsg.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/logging/LogMsg.java @@ -21,23 +21,22 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.logging; /** * A unified message type to log messages from inside the MOA subsystem. - * + * * @author Patrick Peck * @version $Id$ */ public class LogMsg { /** The message to log. */ - private Object message; + private final Object message; /** * Create a LogMsg object. - * - * @param message The actual message to log. May be null. + * + * @param message The actual message to log. May be null. */ public LogMsg(Object message) { this.message = message; @@ -45,16 +44,17 @@ public class LogMsg { /** * Convert this log message to a String. - * - * @return The String representation of this log message. + * + * @return The String representation of this log message. */ + @Override public String toString() { - StringBuffer msg = new StringBuffer(); - LoggingContext ctx = - LoggingContextManager.getInstance().getLoggingContext(); - String tid = ctx != null ? ctx.getTransactionID() : null; - String nodeId = ctx != null ? ctx.getNodeID() : null; - + final StringBuffer msg = new StringBuffer(); + final LoggingContext ctx = + LoggingContextManager.getInstance().getLoggingContext(); + final String tid = ctx != null ? ctx.getTransactionID() : null; + final String nodeId = ctx != null ? ctx.getNodeID() : null; + msg.append("TID="); msg.append(tid != null ? tid : ""); msg.append(" NID="); diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/logging/Logger.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/logging/Logger.java index 532a8be..23908ab 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/logging/Logger.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/logging/Logger.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.logging; import java.util.HashMap; @@ -29,28 +28,28 @@ import java.util.Map; /** * A utility class acting as a facade to the logging subsystem. - * + * * Configure the logging defaultHierarchy that the Logger uses by * calling setHierarchy once before calling any of the logging * output functions. - * + * * @author Patrick Peck * @version $Id$ */ public class Logger { - + /** * Set the default hierarchy to which the Logger should send its * logging output. + * * @param hierarchy The logging defaultHierarchy. */ public static void setHierarchy(String hierarchy) { - // there is no need for that anymore + // there is no need for that anymore } - /** The Constant instances. */ - private static final Map instances = new HashMap(); + private static final Map instances = new HashMap<>(); /** * Gets the logger. @@ -58,173 +57,177 @@ public class Logger { * @return the logger */ private static synchronized org.slf4j.Logger getLogger() { - StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace(); - - int i; - for(i = 2; i < stacktrace.length; i++) - if(!stacktrace[i].getClassName().equals(Logger.class.getName())) - break; + final StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace(); - String className = stacktrace[i].getClassName(); - - org.slf4j.Logger logger = instances.get(className); - if (logger != null) { - return logger; + int i; + for (i = 2; i < stacktrace.length; i++) { + if (!stacktrace[i].getClassName().equals(Logger.class.getName())) { + break; } + } - logger = org.slf4j.LoggerFactory.getLogger(className); - instances.put(className, logger); + final String className = stacktrace[i].getClassName(); + org.slf4j.Logger logger = instances.get(className); + if (logger != null) { return logger; + } + + logger = org.slf4j.LoggerFactory.getLogger(className); + instances.put(className, logger); + + return logger; } - + /** * Prepare the message for printing it as string. - *

Mainly introduce because the message might be null. + *

+ * Mainly introduce because the message might be null. * * @param message the message * @return the string */ private static String prepareMessage(Object message) { - if(null == message) - return "no message given"; - return message.toString(); + if (null == message) { + return "no message given"; + } + return message.toString(); } - + /** * Test, if the trace log level is enabled. - * + * * @return boolean true, if tracing output is enabled - * false otherwise. + * false otherwise. */ public static boolean isTraceEnabled() { - org.slf4j.Logger logger = getLogger(); - return logger.isTraceEnabled(); + final org.slf4j.Logger logger = getLogger(); + return logger.isTraceEnabled(); } - + /** * Test, if the trace log level is enabled for a given hierarchy. - * + * * @param hierarchy requested log hierarchy * @return boolean true, if tracing output is enabled - * false otherwise. + * false otherwise. */ public static boolean isTraceEnabled(String hierarchy) { - org.slf4j.Logger logger = getLogger(); - return logger.isTraceEnabled(); + final org.slf4j.Logger logger = getLogger(); + return logger.isTraceEnabled(); } - + /** * Trace a message. - * + * * @param message The message to trace. */ public static void trace(Object message) { - org.slf4j.Logger logger = getLogger(); - logger.trace(prepareMessage(message)); + final org.slf4j.Logger logger = getLogger(); + logger.trace(prepareMessage(message)); } - + /** * Test, if the debug log level is enabled. - * + * * @return boolean true, if debug output is enabled - * false otherwise. + * false otherwise. */ public static boolean isDebugEnabled() { - org.slf4j.Logger logger = getLogger(); - return logger.isDebugEnabled(); + final org.slf4j.Logger logger = getLogger(); + return logger.isDebugEnabled(); } - + /** * Test, if the debug log level is enabled for a given hierarchy. - * + * * @param hierarchy requested log hierarchy * @return boolean true, if debug output is enabled - * false otherwise. + * false otherwise. */ public static boolean isDebugEnabled(String hierarchy) { - org.slf4j.Logger logger = getLogger(); - return logger.isDebugEnabled(); + final org.slf4j.Logger logger = getLogger(); + return logger.isDebugEnabled(); } - + /** * Log a debug message. - * + * * @param message The message to log. */ public static void debug(Object message) { - org.slf4j.Logger logger = getLogger(); - logger.debug(prepareMessage(message)); + final org.slf4j.Logger logger = getLogger(); + logger.debug(prepareMessage(message)); } -/** + /** * Log an info message. - * + * * @param message The message to log. */ public static void info(Object message) { - org.slf4j.Logger logger = getLogger(); - logger.info(prepareMessage(message)); + final org.slf4j.Logger logger = getLogger(); + logger.info(prepareMessage(message)); } - + /** * Log a warning message. - * + * * @param message The message to log. */ public static void warn(Object message) { - org.slf4j.Logger logger = getLogger(); - logger.warn(prepareMessage(message)); + final org.slf4j.Logger logger = getLogger(); + logger.warn(prepareMessage(message)); } /** * Log a warning message. - * + * * @param message The message to log. - * @param t An exception that may be the cause of the warning. + * @param t An exception that may be the cause of the warning. */ public static void warn(Object message, Throwable t) { - org.slf4j.Logger logger = getLogger(); - logger.warn(prepareMessage(message), t); + final org.slf4j.Logger logger = getLogger(); + logger.warn(prepareMessage(message), t); } - + /** * Log an error message. - * + * * @param message The message to log. */ public static void error(Object message) { - org.slf4j.Logger logger = getLogger(); - logger.error(prepareMessage(message)); + final org.slf4j.Logger logger = getLogger(); + logger.error(prepareMessage(message)); } /** * Log an error message. - * + * * @param message The message to log. - * @param t An exception that may be the cause of the error. + * @param t An exception that may be the cause of the error. */ public static void error(Object message, Throwable t) { - org.slf4j.Logger logger = getLogger(); - logger.error(prepareMessage(message), t); + final org.slf4j.Logger logger = getLogger(); + logger.error(prepareMessage(message), t); } - + /** * Log a fatal error message. - * + * * @param message The message to log. */ public static void fatal(Object message) { - error(message); + error(message); } /** * Log a fatal error message. - * + * * @param message The message to log. - * @param t An exception that may be the cause of the error. + * @param t An exception that may be the cause of the error. */ public static void fatal(Object message, Throwable t) { - error(message, t); + error(message, t); } } diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/logging/LoggingContext.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/logging/LoggingContext.java index 0fb0e7d..d8f03a6 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/logging/LoggingContext.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/logging/LoggingContext.java @@ -21,47 +21,46 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.logging; /** * Encapsulates contextual information (i.e. per request information) for * logging purposes. - * + * * @author Patrick Peck * @version $Id$ */ public class LoggingContext { /** The name of the node ID system property. */ public static final String NODE_ID_PROPERTY = "moa.node-id"; - + /** The current transaction ID. */ - private String transactionID; + private final String transactionID; /** The node ID. */ - private String nodeID; - + private final String nodeID; + /** * Create a new LoggingContext. - * + * * @param transactionID The transaction ID. May be null. */ public LoggingContext(String transactionID) { this.transactionID = transactionID; this.nodeID = System.getProperty(NODE_ID_PROPERTY); } - + /** * Return the transaction ID. - * + * * @return The transaction ID. */ public String getTransactionID() { return transactionID; } - + /** * Return the node ID. - * + * * @return The node ID. */ public String getNodeID() { diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/logging/LoggingContextManager.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/logging/LoggingContextManager.java index b4cd294..aa4bfe8 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/logging/LoggingContextManager.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/logging/LoggingContextManager.java @@ -21,25 +21,24 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.logging; /** * Provides each thread with a single instance of LoggingContext. - * + * * @author Patrick Peck * @version $Id$ */ public class LoggingContextManager { /** The single instance of this class. */ private static LoggingContextManager instance = null; - + /** The LoggingContext for each thread. */ - private ThreadLocal context; - + private final ThreadLocal context; + /** * Get the single instance of the LoggingContextManager class. - * + * * @return LoggingContextManager The single instance. */ public static synchronized LoggingContextManager getInstance() { @@ -48,30 +47,30 @@ public class LoggingContextManager { } return instance; } - + /** * Creates a new LoggingContextManager. - * + * * Protected to disallow direct instantiation. */ protected LoggingContextManager() { context = new ThreadLocal(); } - + /** * Set the LoggingContext context for the current thread. - * + * * @param ctx The LoggingContext for the current thread. */ public void setLoggingContext(LoggingContext ctx) { context.set(ctx); } - + /** * Return the LoggingContext for the current thread. - * + * * @return LoggingContext The LoggingContext for the current - * thread, or null if none has been set. + * thread, or null if none has been set. */ public LoggingContext getLoggingContext() { return (LoggingContext) context.get(); diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/Base64Utils.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/Base64Utils.java index 25a19bc..2c9b4c0 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/Base64Utils.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/Base64Utils.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.util; import java.io.ByteArrayInputStream; @@ -35,81 +34,81 @@ import iaik.utils.Base64OutputStream; /** * Utitility functions for encoding/decoding Base64 strings. - * + * * @author Patrick Peck * @version $Id$ */ public class Base64Utils { /** - * Read the bytes encoded in a Base64 encoded String. - * - * @param base64String The String containing the Base64 encoded - * bytes. + * Read the bytes encoded in a Base64 encoded String. + * + * @param base64String The String containing the Base64 + * encoded bytes. * @param ignoreInvalidChars Whether to ignore invalid Base64 characters. * @return byte[] The raw bytes contained in the base64String. * @throws IOException Failed to read the Base64 data. */ public static byte[] decode(String base64String, boolean ignoreInvalidChars, String encoding) - throws IOException { - - Base64InputStream in = - new Base64InputStream( - new ByteArrayInputStream(base64String.getBytes(encoding)), - ignoreInvalidChars); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - byte[] bytes = new byte[256]; + throws IOException { + + final Base64InputStream in = + new Base64InputStream( + new ByteArrayInputStream(base64String.getBytes(encoding)), + ignoreInvalidChars); + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + final byte[] bytes = new byte[256]; int bytesRead; while ((bytesRead = in.read(bytes)) > 0) { out.write(bytes, 0, bytesRead); } in.close(); - + return out.toByteArray(); } public static byte[] decode(String base64String, boolean ignoreInvalidChars) throws IOException { - return decode(base64String, ignoreInvalidChars, "UTF-8"); + return decode(base64String, ignoreInvalidChars, "UTF-8"); } - + /** * Read the bytes encoded in a Base64 encoded String and provide * them via an InputStream. - * - * @param base64String The String containing the Base64 encoded - * bytes. + * + * @param base64String The String containing the Base64 + * encoded bytes. * @param ignoreInvalidChars Whether to ignore invalid Base64 characters. * @return The InputStream from which the binary content of the - * base64String can be read. + * base64String can be read. */ public static InputStream decodeToStream( - String base64String, - boolean ignoreInvalidChars, - String encoding) { + String base64String, + boolean ignoreInvalidChars, + String encoding) { try { - ByteArrayInputStream bin = - new ByteArrayInputStream(base64String.getBytes(encoding)); - Base64InputStream in = new Base64InputStream(bin, ignoreInvalidChars); - + final ByteArrayInputStream bin = + new ByteArrayInputStream(base64String.getBytes(encoding)); + final Base64InputStream in = new Base64InputStream(bin, ignoreInvalidChars); + return in; - } catch (UnsupportedEncodingException e) { + } catch (final UnsupportedEncodingException e) { // cannot occur, since UTF-8 is required to be supported by every JRE - return null; + return null; } } public static InputStream decodeToStream( - String base64String, - boolean ignoreInvalidChars) { - return decodeToStream(base64String, ignoreInvalidChars, "UTF-8"); - + String base64String, + boolean ignoreInvalidChars) { + return decodeToStream(base64String, ignoreInvalidChars, "UTF-8"); + } - + /** * Convert a byte array to a Base64 encoded String. - * + * * @param bytes The bytes to encode. * @return String The Base64 encoded representation of the bytes. * @throws IOException Failed to write the bytes as Base64 data. @@ -119,25 +118,26 @@ public class Base64Utils { } public static String encode(byte[] bytes, String encoding) throws IOException { - return encode(new ByteArrayInputStream(bytes), encoding); - } - + return encode(new ByteArrayInputStream(bytes), encoding); + } + public static String encode(InputStream inputStream) throws IOException { - return encode(inputStream, "UTF-8"); + return encode(inputStream, "UTF-8"); } + /** * Convert the data contained in the given stream to a Base64 encoded * String. - * + * * @param inputStream The stream containing the data to encode. - * @return The Base64 encoded data of inputStream, as a - * String. + * @return The Base64 encoded data of inputStream, as a + * String. * @throws IOException Failed to convert the data in the stream. */ public static String encode(InputStream inputStream, String encoding) throws IOException { - ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); - Base64OutputStream base64Stream = new Base64OutputStream(byteStream, "\n".getBytes()); - byte[] bytes = new byte[256]; + final ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); + final Base64OutputStream base64Stream = new Base64OutputStream(byteStream, "\n".getBytes()); + final byte[] bytes = new byte[256]; int bytesRead; while ((bytesRead = inputStream.read(bytes)) > 0) { diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/BoolUtils.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/BoolUtils.java index 56eab08..42f98bc 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/BoolUtils.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/BoolUtils.java @@ -21,25 +21,24 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.util; /** * Utility class for parsing XML schema boolean values. - * + * * @author Patrick Peck * @version $Id$ */ public class BoolUtils { - + /** - * Return the boolean value of an xsd:boolean type of DOM + * Return the boolean value of an xsd:boolean type of DOM * element/attribute. - * + * * @param boolStr The value of the xsd:boolean element/attribute. - * @return true, if boolStr equals - * "true" or "1;". Otherwise, - * false is returned. + * @return true, if boolStr equals + * "true" or "1;". + * Otherwise, false is returned. */ public static boolean valueOf(String boolStr) { return "true".equals(boolStr) || "1".equals(boolStr); diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/CollectionUtils.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/CollectionUtils.java index 01a80ea..dcca377 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/CollectionUtils.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/CollectionUtils.java @@ -21,40 +21,39 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.util; import java.util.Iterator; import java.util.List; /** - * Various utility methods for dealing with java.util.Collection - * classes. - * + * Various utility methods for dealing with java.util.Collection + * classes. + * * @author Patrick Peck * @version $Id$ */ public class CollectionUtils { - + /** - * Convert a List of Number objects to an + * Convert a List of Number objects to an * int array. - * - * @param nums The List containing the numbers whose integer - * value to put into the result. - * @return The int values of the Numbers contained - * in nums. + * + * @param nums The List containing the numbers whose integer value + * to put into the result. + * @return The int values of the Numbers contained in + * nums. */ public static int[] toIntArray(List nums) { - int[] result = new int[nums.size()]; + final int[] result = new int[nums.size()]; Iterator iter; int i; - + for (i = 0, iter = nums.iterator(); iter.hasNext(); i++) { - Number num = (Number) iter.next(); + final Number num = (Number) iter.next(); result[i] = num.intValue(); } - + return result; } } diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/Constants.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/Constants.java index 54caf3e..1102975 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/Constants.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/Constants.java @@ -21,556 +21,557 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.util; import java.util.HashMap; /** * Contains various constants used throughout the system. - * + * * @author Patrick Peck * @version $Id$ */ public interface Constants { /** Root location of the schema files. */ - public static final String SCHEMA_ROOT = "/resources/schemas/"; + String SCHEMA_ROOT = "/resources/schemas/"; /** URI of the Widerrufregister XML namespace. */ - public static final String WRR_NS_URI = - "http://reference.e-government.gv.at/namespace/moavv/20041223"; + String WRR_NS_URI = + "http://reference.e-government.gv.at/namespace/moavv/20041223"; /** Prefix used for the Widerrufregister XML namespace */ - public static final String WRR_PREFIX = "wrr"; + 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#"; + String STB_NS_URI = + "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"; + 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#"; + String MOA_NS_URI = + "http://reference.e-government.gv.at/namespace/moa/20020822#"; /** Name of the mandates infobox */ - public static final String INFOBOXIDENTIFIER_MANDATES = "Mandates"; + String INFOBOXIDENTIFIER_MANDATES = "Mandates"; /** Prefix used for the Mandate XML namespace */ - public static final String MD_PREFIX = "md"; + String MD_PREFIX = "md"; /** URI of the Mandate XML namespace. */ - public static final String MD_NS_URI = - "http://reference.e-government.gv.at/namespace/mandates/20040701#"; + String MD_NS_URI = + "http://reference.e-government.gv.at/namespace/mandates/20040701#"; /** Prefix used for the Mandate XML namespace */ - public static final String MVV_PREFIX = "mvv"; + 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"; + String MVV_NS_URI = + "http://reference.e-government.gv.at/namespace/moavv/app2mvv/20041125"; /** Prefix used for the MandateCheckProfile XML namespace */ - public static final String MDP_PREFIX = "mdp"; + 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#"; + String MDP_NS_URI = + "http://reference.e-government.gv.at/namespace/mandateprofile/20041105#"; /** Prefix used for the MOA XML namespace */ - public static final String MOA_PREFIX = "moa"; + String MOA_PREFIX = "moa"; /** Local location of the MOA XML schema definition. */ - public static final String MOA_SCHEMA_LOCATION = - SCHEMA_ROOT + "MOA-SPSS-3.1.2.xsd"; + String MOA_SCHEMA_LOCATION = + SCHEMA_ROOT + "MOA-SPSS-3.1.2.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#"; + String MOA_CONFIG_NS_URI = + "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#"; + String MOA_ID_CONFIG_NS_URI = + "http://www.buergerkarte.at/namespaces/moaconfig#"; /** Prefix used for the MOA configuration XML namespace */ - public static final String MOA_CONFIG_PREFIX = "conf"; + String MOA_CONFIG_PREFIX = "conf"; /** Prefix used for the MOA configuration XML namespace */ - public static final String MOA_ID_CONFIG_PREFIX = "confID"; + 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-3.0.0.xsd"; + String MOA_CONFIG_SCHEMA_LOCATION = + SCHEMA_ROOT + "MOA-SPSS-config-3.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"; + String MOA_ID_CONFIG_SCHEMA_LOCATION = + 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#"; + String SL10_NS_URI = + "http://www.buergerkarte.at/namespaces/securitylayer/20020225#"; /** Prefix used for the Security Layer 1.0 XML namespace */ - public static final String SL10_PREFIX = "sl10"; + 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"; + 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#"; + String SL11_NS_URI = + "http://www.buergerkarte.at/namespaces/securitylayer/20020831#"; /** Prefix used for the Security Layer 1.1 XML namespace */ - public static final String SL11_PREFIX = "sl11"; + 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"; - + 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#"; + String SL12_NS_URI = + "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"; + 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"; - + 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#"; - + String ECDSA_NS_URI = + "http://www.w3.org/2001/04/xmldsig-more#"; + /** Prefix used for ECDSA namespace */ - public static final String ECDSA_PREFIX = "ecdsa"; + String ECDSA_PREFIX = "ecdsa"; /** Local location of ECDSA XML schema definition */ - public static final String ECDSA_SCHEMA_LOCATION = - SCHEMA_ROOT + "ECDSAKeyValue.xsd"; + 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#"; + String PD_NS_URI = + "http://reference.e-government.gv.at/namespace/persondata/20020228#"; /** Prefix used for the PersonData XML namespace */ - public static final String PD_PREFIX = "pr"; + 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_20_en_moaWID.xsd"; + 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"; + 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"; + 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"; + 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"; + 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"; + 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"; + 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"; + String XML_NS_URI = + "http://www.w3.org/XML/1998/namespace"; /** Prefix used for the XML namespace */ - public static final String XML_PREFIX = "xml"; + String XML_PREFIX = "xml"; /** Local location of the XML schema definition. */ - public static final String XML_SCHEMA_LOCATION = SCHEMA_ROOT + "xml.xsd"; + String XML_SCHEMA_LOCATION = SCHEMA_ROOT + "xml.xsd"; /** URI of the XMLNS namespace */ - public static final String XMLNS_NS_URI = "http://www.w3.org/2000/xmlns/"; + String XMLNS_NS_URI = "http://www.w3.org/2000/xmlns/"; /** Prefix used for the XSI namespace */ - public static final String XSI_PREFIX = "xsi"; + String XSI_PREFIX = "xsi"; /** Local location of the XSI schema definition. */ - public static final String XSI_SCHEMA_LOCATION = - SCHEMA_ROOT + "XMLSchema-instance.xsd"; + 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"; + 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"; + 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"; + String XSLT_PREFIX = "xsl"; /** URI of the XMLDSig XML namespace. */ - public static final String DSIG_NS_URI = "http://www.w3.org/2000/09/xmldsig#"; + String DSIG_NS_URI = "http://www.w3.org/2000/09/xmldsig#"; /** Prefix used for the XMLDSig XML namespace */ - public static final String DSIG_PREFIX = "dsig"; + String DSIG_PREFIX = "dsig"; /** Local location of the XMLDSig XML schema. */ - public static final String DSIG_SCHEMA_LOCATION = - SCHEMA_ROOT + "xmldsig-core-schema.xsd"; + 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"; + 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"; + 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"; + 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#"; - + 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"; + 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"; + String DSIG_EC_SCHEMA_LOCATION = + SCHEMA_ROOT + "exclusive-canonicalization.xsd"; + + /** URI of the XMLLoginParameterResolver Configuration XML namespace */ + 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 + */ + 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 */ + 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"; + String XADES_1_1_1_NS_URI = "http://uri.etsi.org/01903/v1.1.1#"; + + String XADES_1_1_1_NS_PREFIX = "xades111"; + + /** Local location of the XAdES v1.2.2 schema definition */ + 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"; + String XADES_1_2_2_NS_URI = "http://uri.etsi.org/01903/v1.2.2#"; - /** Local location of the XAdES v1.1.1 schema definition */ - public static final String XADES_1_3_2_SCHEMA_LOCATION = - SCHEMA_ROOT + "XAdES01903v132-201601.xsd"; + String XADES_1_2_2_NS_PREFIX = "xades122"; + + /** Local location of the XAdES v1.1.1 schema definition */ + String XADES_1_3_2_SCHEMA_LOCATION = + SCHEMA_ROOT + "XAdES01903v132-201601.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"; + String XADES_1_3_2_NS_URI = "http://uri.etsi.org/01903/v1.3.2#"; + + 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 + "XAdES01903v141-201601.xsd"; + /** Local location of the XAdES v1.4.1 schema definition */ + String XADES_1_4_1_SCHEMA_LOCATION = + SCHEMA_ROOT + "XAdES01903v141-201601.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"; + String XADES_1_4_1_NS_URI = "http://uri.etsi.org/01903/v1.4.1#"; + + 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"; + 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"; + 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"; - + 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"; + 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"; + 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"; - + 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"; + 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"; + 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"; - + 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"; + 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"; + 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"; - + 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#"; + String TSL_NS_URI = + "http://uri.etsi.org/02231/v2#"; /** Prefix used for the TSL namespace */ - public static final String TSL_PREFIX = "tsl1"; + String TSL_PREFIX = "tsl1"; /** Local location of the TSL schema definition. */ - public static final String TSL_SCHEMA_LOCATION = - SCHEMA_ROOT + "ts_119612v010201_xsd.xsd"; + 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/#"; + String TSL_SIE_NS_URI = + "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"; + 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"; - + 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#"; + 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"; + 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"; - + String TSL_ADDTYPES_SCHEMA_LOCATION = + 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#"; + 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"; + 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"; + 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"; - + 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"; + 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"; + String SAML2_METADATA_SCHEMA_LOCATION = + SCHEMA_ROOT + "saml-schema-metadata-2.0.xsd"; /** Prefix used for the XML Encryption XML namespace */ - public static final String ASIC_PREFIX = "asic"; + String ASIC_PREFIX = "asic"; /* Prefix used for the XML Encryption XML namespace */ - public static final String ASIC_URI = "http://uri.etsi.org/02918/v1.2.1#"; + String ASIC_URI = "http://uri.etsi.org/02918/v1.2.1#"; /** Local location of the XML Encryption XML schema definition. */ - public static final String ASIC_SCHEMA_LOCATION = - SCHEMA_ROOT + "asic.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 eDELIVERY20_PREFIX = "zu"; - public static final String eDELIVERY20 = "http://reference.e-government.gv.at/namespace/zustellung/msg/phase2/20181206#"; - public static final String eDELIVERY20_SCHEMA_LOCATION = SCHEMA_ROOT + "zuse_p2.xsd"; - - public static final String eDELIVERY_PERSON_20_PREFIX = "zup"; - public static final String eDELIVERY_PERSON_20 = "http://reference.e-government.gv.at/namespace/persondata/phase2/20181206#"; - public static final String eDELIVERY_PERSON_20_SCHEMA_LOCATION = SCHEMA_ROOT + "zuse_mypersondata_en_p2.xsd"; - - - public static final String ONLY_MOASIG_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 + " ") - + (SL11_NS_URI + " " + SL11_SCHEMA_LOCATION + " ") - + (SL12_NS_URI + " " + SL12_SCHEMA_LOCATION + " ") - + (ECDSA_NS_URI + " " + ECDSA_SCHEMA_LOCATION + " ") - //+ (PD_NS_URI + " " + PD_SCHEMA_LOCATION + " ") - + (SAML_NS_URI + " " + SAML_SCHEMA_LOCATION + " ") - + (SAMLP_NS_URI + " " + SAMLP_SCHEMA_LOCATION + " ") - + (XML_NS_URI + " " + XML_SCHEMA_LOCATION + " ") - + (XSI_NS_URI + " " + XSI_SCHEMA_LOCATION + " ") - + (DSIG_NS_URI + " " + DSIG_SCHEMA_LOCATION + " ") - + (DSIG_FILTER2_NS_URI + " " + DSIG_FILTER2_SCHEMA_LOCATION + " ") - + (DSIG_EC_NS_URI + " " + DSIG_EC_SCHEMA_LOCATION + " ") - + (XMLLPR_NS_URI + " " + XMLLPR_SCHEMA_LOCATION + " ") - + (XADES_1_1_1_NS_URI + " " + XADES_1_1_1_SCHEMA_LOCATION + " ") - + (XADES_1_2_2_NS_URI + " " + XADES_1_2_2_SCHEMA_LOCATION + " ") - + (XADES_1_3_2_NS_URI + " " + XADES_1_3_2_SCHEMA_LOCATION + " ") - + (XADES_1_4_1_NS_URI + " " + XADES_1_4_1_SCHEMA_LOCATION + " ") - + (TSL_NS_URI + " " + TSL_SCHEMA_LOCATION + " ") - + (TSL_SIE_NS_URI + " " + TSL_SIE_SCHEMA_LOCATION + " ") - + (TSL_ADDTYPES_NS_URI + " " + TSL_ADDTYPES_SCHEMA_LOCATION + " ") - + (SAML2_NS_URI + " " + SAML2_SCHEMA_LOCATION + " ") - + (SAML2P_NS_URI + " " + SAML2P_SCHEMA_LOCATION + " ") - + (STORK_NS_URI + " " + STORK_SCHEMA_LOCATION + " ") - + (STORKP_NS_URI + " " + STORKP_SCHEMA_LOCATION + " ") - + (XENC_NS_URI + " " + XENC_SCHEMA_LOCATION + " ") - + (SAML2_METADATA_URI + " " + SAML2_METADATA_SCHEMA_LOCATION + " ") - + (ASIC_URI + " " + ASIC_SCHEMA_LOCATION + " ") - + (SAML2_eIDAS_EXTENSIONS + " " + SAML2_eIDAS_EXTENSIONS_SCHEMA_LOCATION); - + String ASIC_SCHEMA_LOCATION = + SCHEMA_ROOT + "asic.xsd"; + + /* Prefix and Schema definition for eIDAS specific SAML2 extensions */ + String SAML2_eIDAS_EXTENSIONS_PREFIX = "eidas"; + String SAML2_eIDAS_EXTENSIONS = "http://eidas.europa.eu/saml-extensions"; + String SAML2_eIDAS_EXTENSIONS_SCHEMA_LOCATION = SCHEMA_ROOT + "eIDAS_saml_extensions.xsd"; + + String eDELIVERY20_PREFIX = "zu"; + String eDELIVERY20 = "http://reference.e-government.gv.at/namespace/zustellung/msg/phase2/20181206#"; + String eDELIVERY20_SCHEMA_LOCATION = SCHEMA_ROOT + "zuse_p2.xsd"; + + String eDELIVERY_PERSON_20_PREFIX = "zup"; + String eDELIVERY_PERSON_20 = "http://reference.e-government.gv.at/namespace/persondata/phase2/20181206#"; + String eDELIVERY_PERSON_20_SCHEMA_LOCATION = SCHEMA_ROOT + "zuse_mypersondata_en_p2.xsd"; + + String ONLY_MOASIG_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 + " " + + SL11_NS_URI + " " + SL11_SCHEMA_LOCATION + " " + + SL12_NS_URI + " " + SL12_SCHEMA_LOCATION + " " + + ECDSA_NS_URI + " " + ECDSA_SCHEMA_LOCATION + " " + // + (PD_NS_URI + " " + PD_SCHEMA_LOCATION + " ") + + SAML_NS_URI + " " + SAML_SCHEMA_LOCATION + " " + + SAMLP_NS_URI + " " + SAMLP_SCHEMA_LOCATION + " " + + XML_NS_URI + " " + XML_SCHEMA_LOCATION + " " + + XSI_NS_URI + " " + XSI_SCHEMA_LOCATION + " " + + DSIG_NS_URI + " " + DSIG_SCHEMA_LOCATION + " " + + DSIG_FILTER2_NS_URI + " " + DSIG_FILTER2_SCHEMA_LOCATION + " " + + DSIG_EC_NS_URI + " " + DSIG_EC_SCHEMA_LOCATION + " " + + XMLLPR_NS_URI + " " + XMLLPR_SCHEMA_LOCATION + " " + + XADES_1_1_1_NS_URI + " " + XADES_1_1_1_SCHEMA_LOCATION + " " + + XADES_1_2_2_NS_URI + " " + XADES_1_2_2_SCHEMA_LOCATION + " " + + XADES_1_3_2_NS_URI + " " + XADES_1_3_2_SCHEMA_LOCATION + " " + + XADES_1_4_1_NS_URI + " " + XADES_1_4_1_SCHEMA_LOCATION + " " + + TSL_NS_URI + " " + TSL_SCHEMA_LOCATION + " " + + TSL_SIE_NS_URI + " " + TSL_SIE_SCHEMA_LOCATION + " " + + TSL_ADDTYPES_NS_URI + " " + TSL_ADDTYPES_SCHEMA_LOCATION + " " + + SAML2_NS_URI + " " + SAML2_SCHEMA_LOCATION + " " + + SAML2P_NS_URI + " " + SAML2P_SCHEMA_LOCATION + " " + + STORK_NS_URI + " " + STORK_SCHEMA_LOCATION + " " + + STORKP_NS_URI + " " + STORKP_SCHEMA_LOCATION + " " + + XENC_NS_URI + " " + XENC_SCHEMA_LOCATION + " " + + SAML2_METADATA_URI + " " + SAML2_METADATA_SCHEMA_LOCATION + " " + + ASIC_URI + " " + ASIC_SCHEMA_LOCATION + " " + + SAML2_eIDAS_EXTENSIONS + " " + SAML2_eIDAS_EXTENSIONS_SCHEMA_LOCATION; + /** - * 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 + " ") - + (MOA_CONFIG_NS_URI + " " + MOA_CONFIG_SCHEMA_LOCATION + " ") - + (MOA_ID_CONFIG_NS_URI + " " + MOA_ID_CONFIG_SCHEMA_LOCATION + " ") - + (SL10_NS_URI + " " + SL10_SCHEMA_LOCATION + " ") - + (SL11_NS_URI + " " + SL11_SCHEMA_LOCATION + " ") - + (SL12_NS_URI + " " + SL12_SCHEMA_LOCATION + " ") - + (ECDSA_NS_URI + " " + ECDSA_SCHEMA_LOCATION + " ") - + (PD_NS_URI + " " + PD_SCHEMA_LOCATION + " ") - + (SAML_NS_URI + " " + SAML_SCHEMA_LOCATION + " ") - + (SAMLP_NS_URI + " " + SAMLP_SCHEMA_LOCATION + " ") - + (XML_NS_URI + " " + XML_SCHEMA_LOCATION + " ") - + (XSI_NS_URI + " " + XSI_SCHEMA_LOCATION + " ") - + (DSIG_NS_URI + " " + DSIG_SCHEMA_LOCATION + " ") - + (DSIG_FILTER2_NS_URI + " " + DSIG_FILTER2_SCHEMA_LOCATION + " ") - + (DSIG_EC_NS_URI + " " + DSIG_EC_SCHEMA_LOCATION + " ") - + (XMLLPR_NS_URI + " " + XMLLPR_SCHEMA_LOCATION + " ") - + (XADES_1_1_1_NS_URI + " " + XADES_1_1_1_SCHEMA_LOCATION + " ") - + (XADES_1_2_2_NS_URI + " " + XADES_1_2_2_SCHEMA_LOCATION + " ") - + (XADES_1_3_2_NS_URI + " " + XADES_1_3_2_SCHEMA_LOCATION + " ") - + (XADES_1_4_1_NS_URI + " " + XADES_1_4_1_SCHEMA_LOCATION + " ") - + (TSL_NS_URI + " " + TSL_SCHEMA_LOCATION + " ") - + (TSL_SIE_NS_URI + " " + TSL_SIE_SCHEMA_LOCATION + " ") - + (TSL_ADDTYPES_NS_URI + " " + TSL_ADDTYPES_SCHEMA_LOCATION + " ") - + (SAML2_NS_URI + " " + SAML2_SCHEMA_LOCATION + " ") - + (SAML2P_NS_URI + " " + SAML2P_SCHEMA_LOCATION + " ") - + (STORK_NS_URI + " " + STORK_SCHEMA_LOCATION + " ") - + (STORKP_NS_URI + " " + STORKP_SCHEMA_LOCATION + " ") - + (XENC_NS_URI + " " + XENC_SCHEMA_LOCATION + " ") - + (SAML2_METADATA_URI + " " + SAML2_METADATA_SCHEMA_LOCATION + " ") - + (ASIC_URI + " " + ASIC_SCHEMA_LOCATION + " ") - + (SAML2_eIDAS_EXTENSIONS + " " + SAML2_eIDAS_EXTENSIONS_SCHEMA_LOCATION + " ") - + (eDELIVERY20 + " " + eDELIVERY20_SCHEMA_LOCATION + " ") - + (eDELIVERY_PERSON_20 + " " + eDELIVERY_PERSON_20_SCHEMA_LOCATION); + 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 + " " + + SL11_NS_URI + " " + SL11_SCHEMA_LOCATION + " " + + SL12_NS_URI + " " + SL12_SCHEMA_LOCATION + " " + + ECDSA_NS_URI + " " + ECDSA_SCHEMA_LOCATION + " " + + PD_NS_URI + " " + PD_SCHEMA_LOCATION + " " + + SAML_NS_URI + " " + SAML_SCHEMA_LOCATION + " " + + SAMLP_NS_URI + " " + SAMLP_SCHEMA_LOCATION + " " + + XML_NS_URI + " " + XML_SCHEMA_LOCATION + " " + + XSI_NS_URI + " " + XSI_SCHEMA_LOCATION + " " + + DSIG_NS_URI + " " + DSIG_SCHEMA_LOCATION + " " + + DSIG_FILTER2_NS_URI + " " + DSIG_FILTER2_SCHEMA_LOCATION + " " + + DSIG_EC_NS_URI + " " + DSIG_EC_SCHEMA_LOCATION + " " + + XMLLPR_NS_URI + " " + XMLLPR_SCHEMA_LOCATION + " " + + XADES_1_1_1_NS_URI + " " + XADES_1_1_1_SCHEMA_LOCATION + " " + + XADES_1_2_2_NS_URI + " " + XADES_1_2_2_SCHEMA_LOCATION + " " + + XADES_1_3_2_NS_URI + " " + XADES_1_3_2_SCHEMA_LOCATION + " " + + XADES_1_4_1_NS_URI + " " + XADES_1_4_1_SCHEMA_LOCATION + " " + + TSL_NS_URI + " " + TSL_SCHEMA_LOCATION + " " + + TSL_SIE_NS_URI + " " + TSL_SIE_SCHEMA_LOCATION + " " + + TSL_ADDTYPES_NS_URI + " " + TSL_ADDTYPES_SCHEMA_LOCATION + " " + + SAML2_NS_URI + " " + SAML2_SCHEMA_LOCATION + " " + + SAML2P_NS_URI + " " + SAML2P_SCHEMA_LOCATION + " " + + STORK_NS_URI + " " + STORK_SCHEMA_LOCATION + " " + + STORKP_NS_URI + " " + STORKP_SCHEMA_LOCATION + " " + + XENC_NS_URI + " " + XENC_SCHEMA_LOCATION + " " + + SAML2_METADATA_URI + " " + SAML2_METADATA_SCHEMA_LOCATION + " " + + ASIC_URI + " " + ASIC_SCHEMA_LOCATION + " " + + SAML2_eIDAS_EXTENSIONS + " " + SAML2_eIDAS_EXTENSIONS_SCHEMA_LOCATION + " " + + eDELIVERY20 + " " + eDELIVERY20_SCHEMA_LOCATION + " " + + eDELIVERY_PERSON_20 + " " + eDELIVERY_PERSON_20_SCHEMA_LOCATION; /** URN prefix for bPK and wbPK. */ - public static final String URN_PREFIX = "urn:publicid:gv.at"; - + String URN_PREFIX = "urn:publicid:gv.at"; + /** URN prefix for context dependent id. */ - public static final String URN_PREFIX_CDID = URN_PREFIX + ":cdid"; - + String URN_PREFIX_CDID = URN_PREFIX + ":cdid"; + /** URN prefix for context dependent id (bPK). */ - public static final String URN_PREFIX_BPK = URN_PREFIX_CDID + "+bpk"; + String URN_PREFIX_BPK = URN_PREFIX_CDID + "+bpk"; /** URN prefix for context dependent id (HPI). */ - public static final String URN_PREFIX_HPI = URN_PREFIX_CDID + "+EHSP"; - + String URN_PREFIX_HPI = URN_PREFIX_CDID + "+EHSP"; + /** URN prefix for context dependent id (wbPK). */ - public static final String URN_PREFIX_WBPK = URN_PREFIX + ":wbpk"; + String URN_PREFIX_WBPK = URN_PREFIX + ":wbpk"; /** URN prefix for context dependent id (stork). */ - public static final String URN_PREFIX_STORK = URN_PREFIX + ":storkid"; + String URN_PREFIX_STORK = URN_PREFIX + ":storkid"; /** URN prefix for context dependent id. */ - public static final String URN_PREFIX_BASEID = URN_PREFIX + ":baseid"; - + String URN_PREFIX_BASEID = URN_PREFIX + ":baseid"; + /** Security Layer manifest type URI. */ - public static final String SL_MANIFEST_TYPE_URI = - "http://www.buergerkarte.at/specifications/Security-Layer/20020225#SignatureManifest"; + String SL_MANIFEST_TYPE_URI = + "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"; - + 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"; - + 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"; - + 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"; - + String SHA512_URI = + "http://www.w3.org/2000/09/xmldsig#sha512"; + /** URI of the Canonical XML algorithm */ - public static final String C14N_URI = - "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; + 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"; + String C14N_WITH_COMMENTS_URI = + "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#"; - + 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"; - + String EXC_C14N_WITH_COMMENTS_URI = + "http://www.w3.org/2001/10/xml-exc-c14n#WithComments"; + // // Local names for elements of the MOA SPSS schema // - - /** + + /** * Local name of request for creating an XML signature. */ - public static final String MOA_SPSS_CREATE_XML_REQUEST = "CreateXMLSignatureRequest"; - - /** + String MOA_SPSS_CREATE_XML_REQUEST = "CreateXMLSignatureRequest"; + + /** * Local name of request for creating a CMS signature. */ - public static final String MOA_SPSS_CREATE_CMS_REQUEST = "CreateCMSSignatureRequest"; - - /** + String MOA_SPSS_CREATE_CMS_REQUEST = "CreateCMSSignatureRequest"; + + /** * Local name of request for creating a CMS signature. */ - public static final String MOA_SPSS_CREATE_PDF_REQUEST = "CreatePDFSignatureRequest"; - - /** + String MOA_SPSS_CREATE_PDF_REQUEST = "CreatePDFSignatureRequest"; + + /** * Local name of request for verifying an XML signature. */ - public static final String MOA_SPSS_VERIFY_XML_REQUEST = "VerifiyXMLSignatureRequest"; - - /** - * A map used to map namespace prefixes to namespace URIs - */ - public static HashMap nSMap = new HashMap(5); - + String MOA_SPSS_VERIFY_XML_REQUEST = "VerifiyXMLSignatureRequest"; + + /** + * A map used to map namespace prefixes to namespace URIs + */ + HashMap nSMap = new HashMap<>(5); + } diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/DOMUtils.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/DOMUtils.java index 44eba5a..2f96196 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/DOMUtils.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/DOMUtils.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.util; import java.io.ByteArrayInputStream; @@ -73,12 +72,12 @@ import at.gv.egovernment.moaspss.logging.Logger; /** * 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. - * + * 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. + * * @author Patrick Peck * @version $Id$ */ @@ -86,57 +85,61 @@ public class DOMUtils { /** Feature URI for namespace aware parsing. */ private static final String NAMESPACES_FEATURE = - "http://xml.org/sax/features/namespaces"; + "http://xml.org/sax/features/namespaces"; /** Feature URI for validating parsing. */ private static final String VALIDATION_FEATURE = - "http://xml.org/sax/features/validation"; + "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"; + "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"; + "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"; + "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"; + "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. */ + "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"; - + "http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation"; + private static final String EXTERNAL_GENERAL_ENTITIES_FEATURE = - "http://xml.org/sax/features/external-general-entities"; - + "http://xml.org/sax/features/external-general-entities"; + private static final String EXTERNAL_PARAMETER_ENTITIES_FEATURE = - "http://xml.org/sax/features/external-parameter-entities"; - + "http://xml.org/sax/features/external-parameter-entities"; + private static final String DISALLOW_DOCTYPE_FEATURE = - "http://apache.org/xml/features/disallow-doctype-decl"; - - //Security Manager feature for XERCES XML parser + "http://apache.org/xml/features/disallow-doctype-decl"; + + // Security Manager feature for XERCES XML parser private static final String SECURITY_MANAGER = - org.apache.xerces.impl.Constants.XERCES_PROPERTY_PREFIX + org.apache.xerces.impl.Constants.SECURITY_MANAGER_PROPERTY; - - + org.apache.xerces.impl.Constants.XERCES_PROPERTY_PREFIX + + org.apache.xerces.impl.Constants.SECURITY_MANAGER_PROPERTY; + /** 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; + 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; + /** + * Set holding the NamespaceURIs of the grammarPool, to prevent multiple entries + * of same grammars to the pool + */ + private static Set grammarNamespaces; static { grammarPool.lockPool(); @@ -144,38 +147,38 @@ public class DOMUtils { } /** - * 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. + * 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 { + throws IOException { XMLGrammarPreparser preparser; - if (!grammarNamespaces.contains(systemId)) { + 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)); - + XMLGrammarDescription.XML_SCHEMA, + new XMLInputSource(null, systemId, null, inputStream, null)); + // lock the pool again so that schemas are not added automatically grammarPool.lockPool(); } @@ -183,34 +186,43 @@ public class DOMUtils { /** * 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. + * + * @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 SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document. * @throws ParserConfigurationException An error occurred configuring the XML - * parser. + * parser. */ public static Document parseDocument( - InputStream inputStream, - boolean validating, - String externalSchemaLocations, - String externalNoNamespaceSchemaLocation, - EntityResolver entityResolver, - ErrorHandler errorHandler) - throws SAXException, IOException, ParserConfigurationException { + InputStream inputStream, + boolean validating, + String externalSchemaLocations, + String externalNoNamespaceSchemaLocation, + EntityResolver entityResolver, + ErrorHandler errorHandler) + throws SAXException, IOException, ParserConfigurationException { DOMParser parser; @@ -222,77 +234,77 @@ public class DOMUtils { // } // } + // 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 == Logger.isDebugEnabled()) { + final int len = inputStream.available(); + buffer = new byte[len]; + inputStream.read(buffer); + baStream = new ByteArrayInputStream(buffer); + } - //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 == Logger.isDebugEnabled()) { - int len = inputStream.available(); - buffer = new byte[len]; - inputStream.read(buffer); - 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); - - SecurityManager xmlParserSecManager = new org.apache.xerces.util.SecurityManager(); - parser.setProperty(SECURITY_MANAGER, xmlParserSecManager); - - //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 == Logger.isDebugEnabled() && null != buffer) { - String xmlContent = new String(buffer); - Logger.debug("SAXException in:\n" + xmlContent); - } - throw(e); + 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); + + final SecurityManager xmlParserSecManager = new org.apache.xerces.util.SecurityManager(); + parser.setProperty(SECURITY_MANAGER, xmlParserSecManager); + + // 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 == Logger.isDebugEnabled() && null != buffer) { + final String xmlContent = new String(buffer); + Logger.debug("SAXException in:\n" + xmlContent); + } + throw e; } return parser.getDocument(); @@ -300,31 +312,40 @@ public class DOMUtils { /** * 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. + * + * @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 SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document. * @throws ParserConfigurationException An error occurred configuring the XML - * parser. + * parser. */ public static Document parseDocumentSimple(InputStream inputStream) - throws SAXException, IOException, ParserConfigurationException { + throws SAXException, IOException, ParserConfigurationException { DOMParser parser; - + parser = new DOMParser(); // set parser features and properties parser.setFeature(NAMESPACES_FEATURE, true); @@ -333,184 +354,200 @@ public class DOMUtils { parser.setFeature(NORMALIZED_VALUE_FEATURE, false); parser.setFeature(INCLUDE_IGNORABLE_WHITESPACE_FEATURE, true); parser.setFeature(CREATE_ENTITY_REF_NODES_FEATURE, false); - - SecurityManager xmlParserSecManager = new org.apache.xerces.util.SecurityManager(); + + final SecurityManager xmlParserSecManager = new org.apache.xerces.util.SecurityManager(); parser.setProperty(SECURITY_MANAGER, xmlParserSecManager); - + 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 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. * @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 SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document. * @throws ParserConfigurationException An error occurred configuring the XML - * parser. + * parser. */ public static Document parseDocument( - InputStream inputStream, - boolean validating, - String externalSchemaLocations, - String externalNoNamespaceSchemaLocation) - throws SAXException, IOException, ParserConfigurationException { - - - + InputStream inputStream, + boolean validating, + String externalSchemaLocations, + String externalNoNamespaceSchemaLocation) + throws SAXException, IOException, ParserConfigurationException { + return parseDocument( - inputStream, - validating, - externalSchemaLocations, - externalNoNamespaceSchemaLocation, - new MOAEntityResolver(), - new MOAErrorHandler()); + inputStream, + validating, + externalSchemaLocations, + externalNoNamespaceSchemaLocation, + new MOAEntityResolver(), + new MOAErrorHandler()); } /** * 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. + * + * @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 SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document. * @throws ParserConfigurationException An error occurred configuring the XML - * parser. + * 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)); + String xmlString, + String encoding, + boolean validating, + String externalSchemaLocations, + String externalNoNamespaceSchemaLocation) + throws SAXException, IOException, ParserConfigurationException { + + final InputStream in = new ByteArrayInputStream(xmlString.getBytes(encoding)); return parseDocument( - in, - validating, - externalSchemaLocations, - externalNoNamespaceSchemaLocation); + in, + validating, + externalSchemaLocations, + externalNoNamespaceSchemaLocation); } /** * 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. + * + * @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 SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document. * @throws ParserConfigurationException An error occurred configuring the XML - * parser. + * parser. */ public static Document parseDocument( - String xmlString, - boolean validating, - String externalSchemaLocations, - String externalNoNamespaceSchemaLocation) - throws SAXException, IOException, ParserConfigurationException { + String xmlString, + boolean validating, + String externalSchemaLocations, + String externalNoNamespaceSchemaLocation) + throws SAXException, IOException, ParserConfigurationException { return parseDocument( - xmlString, - "UTF-8", - validating, - externalSchemaLocations, - externalNoNamespaceSchemaLocation); + xmlString, + "UTF-8", + validating, + externalSchemaLocations, + externalNoNamespaceSchemaLocation); } /** * A convenience method to parse an XML document validating. - * - * @param inputStream The InputStream containing the XML - * document. + * + * @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 SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document. * @throws ParserConfigurationException An error occurred configuring the XML - * parser. + * parser. */ public static Element parseXmlValidating(InputStream inputStream) - throws ParserConfigurationException, SAXException, IOException { + throws ParserConfigurationException, SAXException, IOException { return DOMUtils - .parseDocument(inputStream, true, Constants.ALL_SCHEMA_LOCATIONS, null) - .getDocumentElement(); + .parseDocument(inputStream, true, Constants.ALL_SCHEMA_LOCATIONS, null) + .getDocumentElement(); } - + /** * A convenience method to parse an XML document non validating. - * - * @param inputStream The InputStream containing the XML - * document. + * + * @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 SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document. * @throws ParserConfigurationException An error occurred configuring the XML - * parser. + * parser. */ public static Element parseXmlNonValidating(InputStream inputStream) - throws ParserConfigurationException, SAXException, IOException { + throws ParserConfigurationException, SAXException, IOException { return DOMUtils - .parseDocument(inputStream, false, Constants.ALL_SCHEMA_LOCATIONS, null) - .getDocumentElement(); + .parseDocument(inputStream, false, Constants.ALL_SCHEMA_LOCATIONS, null) + .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. + * + * @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. + * @throws TransformerException An error occurred serializing the + * element. */ public static boolean validateElement( - Element element, - String externalSchemaLocations, - String externalNoNamespaceSchemaLocation) - throws - ParserConfigurationException, + Element element, + String externalSchemaLocations, + String externalNoNamespaceSchemaLocation) + throws ParserConfigurationException, IOException, SAXException, TransformerException { @@ -534,16 +571,16 @@ public class DOMUtils { 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); + EXTERNAL_SCHEMA_LOCATION_PROPERTY, + externalSchemaLocations); } if (externalNoNamespaceSchemaLocation != null) { parser.setProperty( - EXTERNAL_NO_NAMESPACE_SCHEMA_LOCATION_PROPERTY, - "externalNoNamespaceSchemaLocation"); + EXTERNAL_NO_NAMESPACE_SCHEMA_LOCATION_PROPERTY, + "externalNoNamespaceSchemaLocation"); } // set up entity resolver and error handler @@ -555,32 +592,35 @@ public class DOMUtils { 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. + * + * @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. + * @throws TransformerException An error occurred serializing the + * element. */ public static boolean validateElement( - Element element, - String externalSchemaLocations, - String externalNoNamespaceSchemaLocation, - EntityResolver entityResolver) - throws - ParserConfigurationException, + Element element, + String externalSchemaLocations, + String externalNoNamespaceSchemaLocation, + EntityResolver entityResolver) + throws ParserConfigurationException, IOException, SAXException, TransformerException { @@ -602,19 +642,19 @@ public class DOMUtils { parser.setFeature(NAMESPACES_FEATURE, true); parser.setFeature(VALIDATION_FEATURE, true); parser.setFeature(SCHEMA_VALIDATION_FEATURE, true); - - SecurityManager xmlParserSecManager = new org.apache.xerces.util.SecurityManager(); + + final SecurityManager xmlParserSecManager = new org.apache.xerces.util.SecurityManager(); parser.setProperty(SECURITY_MANAGER, xmlParserSecManager); - + if (externalSchemaLocations != null) { parser.setProperty( - EXTERNAL_SCHEMA_LOCATION_PROPERTY, - externalSchemaLocations); + EXTERNAL_SCHEMA_LOCATION_PROPERTY, + externalSchemaLocations); } if (externalNoNamespaceSchemaLocation != null) { parser.setProperty( - EXTERNAL_NO_NAMESPACE_SCHEMA_LOCATION_PROPERTY, - "externalNoNamespaceSchemaLocation"); + EXTERNAL_NO_NAMESPACE_SCHEMA_LOCATION_PROPERTY, + "externalNoNamespaceSchemaLocation"); } // set up entity resolver and error handler @@ -625,122 +665,127 @@ public class DOMUtils { 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. + * @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 { + 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 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. + * @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 { + 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 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. + * @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 { + 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 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. + * 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 { + 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 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. + * 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 { + 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 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 + * @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. + * 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 { + 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); + 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); - String omit = omitDeclaration ? "yes" : "no"; + 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 + 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)); @@ -751,30 +796,30 @@ public class DOMUtils { } /** - * 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. - */ + * 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(); + final StringBuffer result = new StringBuffer(); + final NodeList list = node.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { - Node subnode = list.item(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) { @@ -791,28 +836,28 @@ public class DOMUtils { /** * 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). + * @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(); + final Map nsDecls = new HashMap(); int i; do { if (node.hasAttributes()) { - NamedNodeMap attrs = node.getAttributes(); + final NamedNodeMap attrs = node.getAttributes(); for (i = 0; i < attrs.getLength(); i++) { - Attr attr = (Attr) attrs.item(i); + final Attr attr = (Attr) attrs.item(i); // add prefix mapping if none exists if ("xmlns".equals(attr.getPrefix()) - || "xmlns".equals(attr.getName())) { + || "xmlns".equals(attr.getName())) { - String nsPrefix = - attr.getPrefix() != null ? attr.getLocalName() : ""; + final String nsPrefix = + attr.getPrefix() != null ? attr.getLocalName() : ""; if (nsDecls.get(nsPrefix) == null) { nsDecls.put(nsPrefix, attr.getValue()); @@ -826,26 +871,26 @@ public class DOMUtils { } /** - * 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. - * + * 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(); + final Node parent = context.getParentNode(); if (parent != null) { - Map namespaces = getNamespaceDeclarations(context.getParentNode()); - Set nsUris = collectNamespaceURIs(context); + final Map namespaces = getNamespaceDeclarations(context.getParentNode()); + final Set nsUris = collectNamespaceURIs(context); Iterator iter; for (iter = namespaces.entrySet().iterator(); iter.hasNext();) { - Map.Entry e = (Map.Entry) iter.next(); + final 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; + final String prefix = (String) e.getKey(); + final String nsUri = (String) e.getValue(); + final String nsAttrName = "".equals(prefix) ? "xmlns" : "xmlns:" + prefix; context.setAttributeNS(Constants.XMLNS_NS_URI, nsAttrName, nsUri); } @@ -855,13 +900,13 @@ public class DOMUtils { /** * 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. + * including the ones used in context itself. */ public static Set collectNamespaceURIs(Element context) { - Set result = new HashSet(); + final Set result = new HashSet(); collectNamespaceURIsImpl(context, result); return result; @@ -869,14 +914,14 @@ public class DOMUtils { /** * 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. + * @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(); + final NamedNodeMap attrs = context.getAttributes(); + final NodeList childNodes = context.getChildNodes(); String nsUri; int i; @@ -896,7 +941,7 @@ public class DOMUtils { // add all namespaces from subelements for (i = 0; i < childNodes.getLength(); i++) { - Node node = childNodes.item(i); + final Node node = childNodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { collectNamespaceURIsImpl((Element) node, result); @@ -907,13 +952,13 @@ public class DOMUtils { /** * 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. + * @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(); + final Set nodeSet = new HashSet(); int i; // put the nodes into the nodeSet @@ -923,11 +968,11 @@ public class DOMUtils { // check that each attribute node's parent is in the node list for (i = 0; i < nodes.getLength(); i++) { - Node n = nodes.item(i); + final Node n = nodes.item(i); if (n.getNodeType() == Node.ATTRIBUTE_NODE) { - Attr attr = (Attr) n; - Element owner = attr.getOwnerElement(); + final Attr attr = (Attr) n; + final Element owner = attr.getOwnerElement(); if (owner == null) { if (!isNamespaceDeclaration(attr)) { @@ -945,29 +990,28 @@ public class DOMUtils { } /** - * Convert an unstructured NodeList into a + * 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. + * @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. + * 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. + * @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 { + throws ParserConfigurationException { - DocumentBuilder builder = - DocumentBuilderFactory.newInstance().newDocumentBuilder(); - Document doc = builder.newDocument(); - DocumentFragment result = doc.createDocumentFragment(); + final DocumentBuilder builder = + DocumentBuilderFactory.newInstance().newDocumentBuilder(); + final Document doc = builder.newDocument(); + final DocumentFragment result = doc.createDocumentFragment(); if (null == nodeList || nodeList.getLength() == 0) { return result; @@ -975,116 +1019,114 @@ public class DOMUtils { int currPos = 0; currPos = - nodeList2DocumentFragment(nodeList, currPos, result, null, null) + 1; + nodeList2DocumentFragment(nodeList, currPos, result, null, null) + 1; while (currPos < nodeList.getLength()) { currPos = - nodeList2DocumentFragment(nodeList, currPos, result, null, null) + 1; + 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 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) { + NodeList nodeList, + int currPos, + DocumentFragment result, + Element currOrgElem, + Element currClonedElem) { while (currPos < nodeList.getLength()) { - Node currentNode = nodeList.item(currPos); + 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( + 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; } - break; + + currClonedElem.appendChild( + result.getOwnerDocument().importNode(currentNode, false)); } + break; + } - case Node.ELEMENT_NODE : - { - Element nextCurrOrgElem = (Element) currentNode; - Element nextCurrClonedElem = + 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); + 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; } - // Process current Node (of type Element) recursively - currPos = + currClonedElem.appendChild(nextCurrClonedElem); + } + + // Process current Node (of type Element) recursively + currPos = nodeList2DocumentFragment( - nodeList, - ++currPos, - result, - nextCurrOrgElem, - nextCurrClonedElem); + nodeList, + ++currPos, + result, + nextCurrOrgElem, + nextCurrClonedElem); - break; - } + break; + } - case Node.ATTRIBUTE_NODE : - { - Attr currAttr = (Attr) currentNode; + 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; + // 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( + // currClonedElem must be the owner Element of currAttr if + // preconditions are met + currClonedElem.setAttributeNS( currAttr.getNamespaceURI(), currAttr.getNodeName(), currAttr.getValue()); - break; - } + break; + } - default : - { - // All other nodes will be ignored - } + default: { + // All other nodes will be ignored + } } currPos++; @@ -1095,10 +1137,10 @@ public class DOMUtils { /** * 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. + * false otherwise. */ private static boolean isNamespaceDeclaration(Attr attr) { return Constants.XMLNS_NS_URI.equals(attr.getNamespaceURI()); @@ -1106,81 +1148,82 @@ public class DOMUtils { /** * 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. + * @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) + 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. + * + * @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)) { + public static Element getElementFromNodeList(NodeList nl) { + if (nl == null || nl.getLength() == 0) { return null; } - for (int i=0; idateTime, - * according to ISO 8601. - * + * Utility for parsing and building XML type dateTime, according to + * ISO 8601. + * * @author Patrick Peck * @version $Id$ * @see http://www.w3.org/2001/XMLSchema-datatypes" @@ -55,7 +54,7 @@ public class DateTimeUtils { // * @return the dateTime value // */ // public static String buildDateTime(Calendar cal, boolean useUTC) { -// +// // if (useUTC) // return buildDateTimeUTC(cal); // else { @@ -92,41 +91,46 @@ public class DateTimeUtils { // return out.toString(); // } // } - + /** - * Builds a dateTime value in UTC from a Calendar value. + * Builds a dateTime value in UTC from a Calendar + * value. + * * @param cal the Calendar value * @return the dateTime value */ public static String buildDateTimeUTC(Calendar cal) { - - SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); - f.setTimeZone(TimeZone.getTimeZone("UTC")); - - return f.format(cal.getTime()); + + final SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); + f.setTimeZone(TimeZone.getTimeZone("UTC")); + + return f.format(cal.getTime()); } - + /** - * Builds a dateTime value in UTC from a Calendar value. + * Builds a dateTime value in UTC from a Calendar + * value. + * * @param cal the Calendar value * @return the dateTime value */ public static String buildDateTimeUTC(Date cal) { - - SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); - f.setTimeZone(TimeZone.getTimeZone("UTC")); - - return f.format(cal); - + + final SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); + f.setTimeZone(TimeZone.getTimeZone("UTC")); + + return f.format(cal); + } - + /** * Builds a dateTime value from a Calendar value. + * * @param cal the Calendar value * @return the dateTime value */ public static String buildDate(Calendar cal) { - StringWriter out = new StringWriter(); + final StringWriter out = new StringWriter(); out.write("" + cal.get(Calendar.YEAR)); out.write("-"); out.write(to2DigitString(cal.get(Calendar.MONTH) + 1)); @@ -134,43 +138,45 @@ public class DateTimeUtils { out.write(to2DigitString(cal.get(Calendar.DAY_OF_MONTH))); return out.toString(); } - + /** * Builds a dateTime value from a Calendar value. + * * @param cal the Calendar value * @return the dateTime value */ public static String buildTime(Calendar cal) { - StringWriter out = new StringWriter(); - out.write(to2DigitString(cal.get(Calendar.HOUR_OF_DAY))); - out.write(":"); - out.write(to2DigitString(cal.get(Calendar.MINUTE))); - out.write(":"); - out.write(to2DigitString(cal.get(Calendar.SECOND))); - - return out.toString(); + final StringWriter out = new StringWriter(); + out.write(to2DigitString(cal.get(Calendar.HOUR_OF_DAY))); + out.write(":"); + out.write(to2DigitString(cal.get(Calendar.MINUTE))); + out.write(":"); + out.write(to2DigitString(cal.get(Calendar.SECOND))); + + return out.toString(); } - + /** - * Converts month, day, hour, minute, or second value - * to a 2 digit String. + * Converts month, day, hour, minute, or second value to a 2 digit String. + * * @param number the month, day, hour, minute, or second value * @return 2 digit String */ private static String to2DigitString(int number) { - if (number < 10) + if (number < 10) { return "0" + number; - else + } else { return "" + number; + } } /** - * Parse a String containing a date and time instant, given in - * ISO 8601 format. - * + * Parse a String containing a date and time instant, given in ISO + * 8601 format. + * * @param dateTime The String to parse. * @return The Date representation of the contents of - * dateTime. + * dateTime. * @throws ParseException Parsing the dateTime failed. */ public static Date parseDateTime(String dateTime) throws ParseException { @@ -247,8 +253,7 @@ public class DateTimeUtils { curPos++; ensureDigits(dateTime, curPos, 1); fractStr = "0."; - fractStr - += dateTime.substring(curPos, curPos + countDigits(dateTime, curPos)); + fractStr += dateTime.substring(curPos, curPos + countDigits(dateTime, curPos)); fraction = Double.parseDouble(fractStr); curPos += countDigits(dateTime, curPos); } @@ -294,12 +299,12 @@ public class DateTimeUtils { calendar.set(Calendar.MILLISECOND, 0); time = calendar.getTime().getTime(); time += (long) (fraction * 1000.0); - time -= tzSign * ((tzHour * 60) + tzMinute) * 60 * 1000; + time -= tzSign * (tzHour * 60 + tzMinute) * 60 * 1000; if (localTime) { - time -= TimeZone.getDefault().getRawOffset(); + time -= TimeZone.getDefault().getRawOffset(); } return new Date(time); - } catch (IllegalArgumentException e) { + } catch (final IllegalArgumentException e) { throw new ParseException(msg.getMessage("datetime.00", null), curPos); } @@ -307,16 +312,16 @@ public class DateTimeUtils { /** * Parse an integer value. - * - * @param str The String containing the digits. + * + * @param str The String containing the digits. * @param curPos The starting position. * @param digits The number of digist making up the integer value. * @return int The integer representation of the digits contained in - * str. + * str. * @throws ParseException Parsing the integer value failed. */ private static int parseInt(String str, int curPos, int digits) - throws ParseException { + throws ParseException { ensureDigits(str, curPos, digits); return Integer.parseInt(str.substring(curPos, curPos + digits)); @@ -324,31 +329,33 @@ public class DateTimeUtils { /** * Count the number of digits following curPos. - * - * @param str The String in which to count digits. + * + * @param str The String in which to count digits. * @param curPos The starting position. * @return int The number of digits. */ private static int countDigits(String str, int curPos) { int i; - for (i = curPos; i < str.length() && Character.isDigit(str.charAt(i)); i++); + for (i = curPos; i < str.length() && Character.isDigit(str.charAt(i)); i++) { + ; + } return i - curPos; } /** * Ensure that a value falls in a given min/max range. - * - * @param value The value to check. - * @param min The minimum allowed value. - * @param max The maximum allowed value. + * + * @param value The value to check. + * @param min The minimum allowed value. + * @param max The maximum allowed value. * @param curPos To indicate the parsing position in the - * ParseException. + * ParseException. * @throws ParseException Thrown, if value < min || value > * max */ private static void ensureValue(int value, int min, int max, int curPos) - throws ParseException { + throws ParseException { if (value < min || value > max) { throw new ParseException(msg.getMessage("datetime.00", null), curPos); @@ -357,16 +364,16 @@ public class DateTimeUtils { /** * Ensure that the given String has a number of characters left. - * - * @param str The String to check for its length. + * + * @param str The String to check for its length. * @param curPos The starting position. - * @param count The minimum number of characters that str must - * contain, starting at from curPos. - * @throws ParseException Thrown, if - * curPos + count > str.length(). + * @param count The minimum number of characters that str must + * contain, starting at from curPos. + * @throws ParseException Thrown, if + * curPos + count > str.length(). */ private static void ensureChars(String str, int curPos, int count) - throws ParseException { + throws ParseException { if (curPos + count > str.length()) { throw new ParseException(msg.getMessage("datetime.00", null), curPos); } @@ -375,17 +382,17 @@ public class DateTimeUtils { /** * Ensure that a given String contains a certain character at a * certain position. - * - * @param str The String in which to look up the character. + * + * @param str The String in which to look up the character. * @param curPos The position in str that must contain the - * character. - * @param c The character value that must be contained at position - * curPos. + * character. + * @param c The character value that must be contained at position + * curPos. * @throws ParseException Thrown, if the characters do not match or - * curPos is out of range. + * curPos is out of range. */ private static void ensureChar(String str, int curPos, char c) - throws ParseException { + throws ParseException { ensureChars(str, curPos, 1); if (str.charAt(curPos) != c) { @@ -394,19 +401,19 @@ public class DateTimeUtils { } /** - * Ensure that a given String contains a number of digits, - * starting at a given position. - * - * @param str The String to scan for digits. + * Ensure that a given String contains a number of digits, starting + * at a given position. + * + * @param str The String to scan for digits. * @param curPos The starting postion. - * @param count The number of digits that must be contained in - * str, starting at curPos. - * @throws ParseException Thrown, if str is not long enough, or - * one of the characters following curPos in str is - * not a digit. + * @param count The number of digits that must be contained in + * str, starting at curPos. + * @throws ParseException Thrown, if str is not long enough, or one + * of the characters following curPos in + * str is not a digit. */ private static void ensureDigits(String str, int curPos, int count) - throws ParseException { + throws ParseException { ensureChars(str, curPos, count); for (int i = curPos; i < curPos + count; i++) { @@ -415,101 +422,108 @@ public class DateTimeUtils { } } } - + /** * Calculates the age if date of birth is given (for a calendar time stamp) + * * @param dateOfBirth Date of Birth - * @param now Calendar time stamp at which the age needs to be calculated for + * @param now Calendar time stamp at which the age needs to be + * calculated for * @return Age of a person */ public static int calcAge(Calendar dateOfBirth, Calendar now) { - int age = now.get(Calendar.YEAR) - dateOfBirth.get(Calendar.YEAR); - - int nowM = now.get(Calendar.MONTH); - int dobM = dateOfBirth.get(Calendar.MONTH); - int nowDOM = now.get(Calendar.DAY_OF_MONTH); - int dobDOM = dateOfBirth.get(Calendar.DAY_OF_MONTH); - - if ((nowM < dobM) || ((nowM == dobM) && (nowDOM < dobDOM))) { - age--; - } - - if (age < 0) { - throw new IllegalArgumentException("Calculated age results in negative value."); - } - return age; - } + int age = now.get(Calendar.YEAR) - dateOfBirth.get(Calendar.YEAR); + + final int nowM = now.get(Calendar.MONTH); + final int dobM = dateOfBirth.get(Calendar.MONTH); + final int nowDOM = now.get(Calendar.DAY_OF_MONTH); + final int dobDOM = dateOfBirth.get(Calendar.DAY_OF_MONTH); + + if (nowM < dobM || nowM == dobM && nowDOM < dobDOM) { + age--; + } + + if (age < 0) { + throw new IllegalArgumentException("Calculated age results in negative value."); + } + return age; + } /** * Calculates the age if date of birth is given as Calendar object + * * @param dateOfBirth Date of Birth as Calendar object * @return Age of a person */ - public static int calcAge(Calendar dateOfBirth) { - return calcAge(dateOfBirth, Calendar.getInstance()); - } - - /** - * Calculates the age if date of birth is given (for a date time stamp) - * @param dateOfBirth Date of Birth - * @param now Date time stamp at which the age needs to be calculated for - * @return Age of a person - */ - public static int calcAge(Date dateOfBirth, Date now) { - Calendar dob = Calendar.getInstance(); - dob.setTime(dateOfBirth); - Calendar nowCal = Calendar.getInstance(); - nowCal.setTime(now); - return calcAge(dob, nowCal); - } - - /** - * Calculates the age if date of birth is given as Date object - * @param dateOfBirth Date of Birth as Date object - * @return Age of a person - */ - public static int calcAge(Date dateOfBirth) { - return calcAge(dateOfBirth, new Date()); - } - - public static String formatPEPSDateToMOADate(String pepsDate) { - - if (StringUtils.isEmpty(pepsDate)) { - return null; - } - - DateTimeFormatter fmt = null; - - switch (pepsDate.length()) { - case 4: - fmt = DateTimeFormat.forPattern("yyyy"); - break; - case 6: - fmt = DateTimeFormat.forPattern("yyyyMM"); - break; - case 8: - fmt = DateTimeFormat.forPattern("yyyyMMdd"); - break; - default: - fmt = DateTimeFormat.forPattern("yyyy-MM-dd"); - break; - } - - DateTime dt = fmt.parseDateTime(pepsDate); - DateTimeFormatter fmt2 = DateTimeFormat.forPattern("yyyy-MM-dd"); - return fmt2.print(dt); - - } - - /** - * Returns a date as String using a provided format - * @param format Format the date/time should be returned - * @return Date/Time as String formatted according the provided format - */ - public static String getDateTimeWithFormat(String format) { - DateFormat dateFormat = new SimpleDateFormat(format); - Date date = new Date(); - return dateFormat.format(date); + public static int calcAge(Calendar dateOfBirth) { + return calcAge(dateOfBirth, Calendar.getInstance()); + } + + /** + * Calculates the age if date of birth is given (for a date time stamp) + * + * @param dateOfBirth Date of Birth + * @param now Date time stamp at which the age needs to be calculated + * for + * @return Age of a person + */ + public static int calcAge(Date dateOfBirth, Date now) { + final Calendar dob = Calendar.getInstance(); + dob.setTime(dateOfBirth); + final Calendar nowCal = Calendar.getInstance(); + nowCal.setTime(now); + return calcAge(dob, nowCal); + } + + /** + * Calculates the age if date of birth is given as Date object + * + * @param dateOfBirth Date of Birth as Date object + * @return Age of a person + */ + public static int calcAge(Date dateOfBirth) { + return calcAge(dateOfBirth, new Date()); + } + + public static String formatPEPSDateToMOADate(String pepsDate) { + + if (StringUtils.isEmpty(pepsDate)) { + return null; } + DateTimeFormatter fmt = null; + + switch (pepsDate.length()) { + case 4: + fmt = DateTimeFormat.forPattern("yyyy"); + break; + case 6: + fmt = DateTimeFormat.forPattern("yyyyMM"); + break; + case 8: + fmt = DateTimeFormat.forPattern("yyyyMMdd"); + break; + default: + fmt = DateTimeFormat.forPattern("yyyy-MM-dd"); + break; + } + + final DateTime dt = fmt.parseDateTime(pepsDate); + final DateTimeFormatter fmt2 = DateTimeFormat.forPattern("yyyy-MM-dd"); + return fmt2.print(dt); + + } + + /** + * Returns a date as String using a provided format + * + * @param format Format the date/time should be returned + * @return Date/Time as String formatted according the provided format + */ + public static String getDateTimeWithFormat(String format) { + final DateFormat dateFormat = new SimpleDateFormat(format); + final Date date = new Date(); + return dateFormat.format(date); + } + } diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/Empty.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/Empty.java index 9c678d4..8b16a97 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/Empty.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/Empty.java @@ -1,13 +1,13 @@ /* * Copyright 2011 Federal Chancellery Austria and * Graz University of Technology - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,11 +21,11 @@ package at.gv.egovernment.moaspss.util; */ public interface Empty { - /** - * Returns {@code true} if underlying object is empty. - * - * @return {@code true} if empty, {@code false} if not empty. - */ - boolean isEmpty(); + /** + * Returns {@code true} if underlying object is empty. + * + * @return {@code true} if empty, {@code false} if not empty. + */ + boolean isEmpty(); } diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/EntityResolverChain.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/EntityResolverChain.java index 487c6a4..6f61517 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/EntityResolverChain.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/EntityResolverChain.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.util; import java.io.IOException; @@ -34,39 +33,41 @@ import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** - * Implementation of the org.xml.sax.EntityResolver, - * for use by a org.apache.xerces.parsers.DOMParser. - * + * Implementation of the org.xml.sax.EntityResolver, for use by a + * org.apache.xerces.parsers.DOMParser. + * * @author Patrick Peck * @version $Id$ */ public class EntityResolverChain implements EntityResolver { /** The EntityResolvers in the chain. */ - private List resolvers = new ArrayList(); + private final List resolvers = new ArrayList(); /** - * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String) + * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, + * java.lang.String) */ + @Override public InputSource resolveEntity(String publicId, String systemId) - throws SAXException, IOException { - + throws SAXException, IOException { + Iterator iter; - - for (iter = resolvers.iterator(); iter.hasNext(); ) { - EntityResolver resolver = (EntityResolver) iter.next(); - InputSource is = resolver.resolveEntity(publicId, systemId); - + + for (iter = resolvers.iterator(); iter.hasNext();) { + final EntityResolver resolver = (EntityResolver) iter.next(); + final InputSource is = resolver.resolveEntity(publicId, systemId); + if (is != null) { return is; } } - + return null; } - + /** * Add an EntityResolver to the chain. - * + * * @param entityResolver The EntityResolver to add. */ public void addEntityResolver(EntityResolver entityResolver) { diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/FileUtils.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/FileUtils.java index 309e01a..d64cda0 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/FileUtils.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/FileUtils.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.util; import java.io.BufferedInputStream; @@ -34,146 +33,167 @@ import java.io.OutputStream; import java.net.URL; /** - * Utility for accessing files on the file system, and for reading from input streams. + * Utility for accessing files on the file system, and for reading from input + * streams. + * * @author Paul Ivancsics * @version $Id$ */ public class FileUtils { - + /** * 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 { - URL url = new URL(urlString); - InputStream in = new BufferedInputStream(url.openStream()); - byte[] content = StreamUtils.readStream(in); + public static byte[] readURL(String urlString) throws IOException { + final URL url = new URL(urlString); + final InputStream in = new BufferedInputStream(url.openStream()); + final byte[] content = StreamUtils.readStream(in); in.close(); return content; } + /** * Reads a file, given by URL, into a String. + * * @param urlString file URL - * @param encoding character encoding + * @param encoding character encoding * @return file content * @throws IOException on any exception thrown */ public static String readURL(String urlString, String encoding) throws IOException { - byte[] content = readURL(urlString); + final byte[] content = readURL(urlString); return new String(content, encoding); } + /** * Reads a file, given by filename, into a byte array. + * * @param filename filename * @return file content * @throws IOException on any exception thrown */ public static byte[] readFile(String filename) throws IOException { - BufferedInputStream in = new BufferedInputStream(new FileInputStream(filename)); - byte[] content = StreamUtils.readStream(in); + final BufferedInputStream in = new BufferedInputStream(new FileInputStream(filename)); + final byte[] content = StreamUtils.readStream(in); in.close(); return content; } + /** * Reads a file, given by filename, into a String. + * * @param filename filename * @param encoding character encoding * @return file content * @throws IOException on any exception thrown */ public static String readFile(String filename, String encoding) throws IOException { - byte[] content = readFile(filename); + final byte[] content = readFile(filename); return new String(content, encoding); } + /** * 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 { - ClassLoader cl = FileUtils.class.getClassLoader(); - BufferedInputStream in = new BufferedInputStream(cl.getResourceAsStream(name)); - byte[] content = StreamUtils.readStream(in); + 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 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 { - byte[] content = readResource(name); + 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 - */ - public static String makeAbsoluteURL(String url, String root) { - //if url is relative to rootConfigFileDirName make it absolute - + + /** + * 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 + File keyFile; String newURL = url; - if(null == url) return null; - - if (url.startsWith("http:/") || url.startsWith("https:/") || url.startsWith("file:/") || url.startsWith("ftp:/")) { - return url; + if (null == url) { + return null; + } + + if (url.startsWith("http:/") || url.startsWith("https:/") || url.startsWith("file:/") || url.startsWith( + "ftp:/")) { + 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(); - + if (keyFile.toString().startsWith("file:")) { + newURL = keyFile.toString(); + } else { + newURL = keyFile.toURI().toString(); + } + } return newURL; } - } - - - private static void copy( InputStream fis, OutputStream fos ) - { - try - { - byte[] buffer = new byte[ 0xFFFF ]; - for ( int len; (len = fis.read(buffer)) != -1; ) - fos.write( buffer, 0, len ); - } - catch( IOException e ) { - System.err.println( e ); - } - finally { - if ( fis != null ) - try { fis.close(); } catch ( IOException e ) { e.printStackTrace(); } - if ( fos != null ) - try { fos.close(); } catch ( IOException e ) { e.printStackTrace(); } - } - } - - public static void copyFile(File src, File dest) - { - try - { - copy( new FileInputStream( src ), new FileOutputStream( dest ) ); - } - catch( IOException e ) { - e.printStackTrace(); - } - } - + } + + 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(); + } + } + } diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/KeyStoreUtils.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/KeyStoreUtils.java index b4d7b02..f62b82a 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/KeyStoreUtils.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/KeyStoreUtils.java @@ -21,11 +21,8 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.util; -import iaik.x509.X509Certificate; - import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; @@ -38,116 +35,125 @@ import java.security.KeyStore; import java.security.KeyStoreException; import java.security.cert.Certificate; +import iaik.x509.X509Certificate; + /** * 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 + * @param urlString URL of key store + * @param password password protecting the key store * @return key store loaded - * @throws IOException thrown while reading the key store from file + * @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 { + String keystoreType, + String urlString, + String password) + throws IOException, GeneralSecurityException { - URL keystoreURL = new URL(urlString); - InputStream in = keystoreURL.openStream(); + 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. - * + * 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 + * @param in input stream + * @param password password protecting the key store * @return key store loaded - * @throws IOException thrown while reading the key store from the stream + * @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 { + String keystoreType, + InputStream in, + 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". - * - * @param keyStoreType key store type + * 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 IOException thrown while reading the certificates from + * file * @throws GeneralSecurityException thrown while creating the key store */ public static KeyStore createKeyStore( - String keyStoreType, - String[] certFilenames) - throws IOException, GeneralSecurityException { + String keyStoreType, + String[] certFilenames) + throws IOException, GeneralSecurityException { - 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; } + /** - * Creates a key store from a directory containg X509 certificate files, - * aliasing them with the index in the String[], starting with "0". - * All the files in the directory are considered to be certificates. - * - * @param keyStoreType key store type - * @param certDirURLString file URL of directory containing certificate filenames + * Creates a key store from a directory containg X509 certificate files, + * aliasing them with the index in the String[], starting with + * "0". All the files in the directory are considered to be + * certificates. + * + * @param keyStoreType key store type + * @param certDirURLString file URL of directory containing certificate + * filenames * @return key store created - * @throws IOException thrown while reading the certificates from file + * @throws IOException thrown while reading the certificates from + * file * @throws GeneralSecurityException thrown while creating the key store */ public static KeyStore createKeyStoreFromCertificateDirectory( - String keyStoreType, - String certDirURLString) - throws IOException, GeneralSecurityException { - - URL certDirURL = new URL(certDirURLString); - String certDirname = certDirURL.getFile(); - File certDir = new File(certDirname); - String[] certFilenames = certDir.list(); - String separator = - (certDirname.endsWith(File.separator) ? "" : File.separator); + String keyStoreType, + String certDirURLString) + throws IOException, GeneralSecurityException { + + final URL certDirURL = new URL(certDirURLString); + final String certDirname = certDirURL.getFile(); + final File certDir = new File(certDirname); + final String[] certFilenames = certDir.list(); + final String separator = + certDirname.endsWith(File.separator) ? "" : File.separator; for (int i = 0; i < certFilenames.length; i++) { certFilenames[i] = certDirname + separator + certFilenames[i]; } @@ -156,68 +162,69 @@ 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 IOException thrown while reading the certificate from + * file * @throws GeneralSecurityException thrown while creating the certificate */ private static Certificate loadCertificate(String certFilename) - throws IOException, GeneralSecurityException { + throws IOException, GeneralSecurityException { - FileInputStream in = new FileInputStream(certFilename); - Certificate cert = new X509Certificate(in); + final FileInputStream in = new FileInputStream(certFilename); + final Certificate cert = new X509Certificate(in); in.close(); return cert; } - - - /** - * 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(); - //throw new KeyStoreException(e); - } - return ks; - - } - - + /** + * 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); + final URL keystoreURL = new URL(keyStorePath); + final InputStream in = keystoreURL.openStream(); + final 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 (final IOException e2) { + is.reset(); + ks = loadKeyStore(KEYSTORE_TYPE_JKS, is, password); + } + } catch (final Exception e) { + e.printStackTrace(); + // throw new KeyStoreException(e); + } + return ks; + + } } diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/MOADefaultHandler.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/MOADefaultHandler.java index 3dde827..9d1f01f 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/MOADefaultHandler.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/MOADefaultHandler.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.util; import java.io.IOException; @@ -36,15 +35,15 @@ import org.xml.sax.helpers.DefaultHandler; /** * A DefaultHandler that uses a MOAEntityResolver and * a MOAErrorHandler. - * + * * @author Patrick Peck * @version $Id$ */ public class MOADefaultHandler extends DefaultHandler { /** The EntityResolver to use. */ - private EntityResolver entityResolver; + private final EntityResolver entityResolver; /** The ErrorHandler to use. */ - private ErrorHandler errorHandler; + private final ErrorHandler errorHandler; /** * Create a new MOADefaultHandler. @@ -56,28 +55,30 @@ public class MOADefaultHandler extends DefaultHandler { /** * Create a new MOADefaultHandler. - * + * * @param entityResolver The EntityResolver to use for resolving - * external entities. - * @param errorHandler The ErrorHandler to use for reporting - * parsing errors. + * external entities. + * @param errorHandler The ErrorHandler to use for reporting + * parsing errors. */ public MOADefaultHandler( - EntityResolver entityResolver, - ErrorHandler errorHandler) { + EntityResolver entityResolver, + ErrorHandler errorHandler) { this.entityResolver = entityResolver; this.errorHandler = errorHandler; } /** - * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String) + * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, + * java.lang.String) */ + @Override public InputSource resolveEntity(String publicId, String systemId) - throws SAXException { + throws SAXException { try { return entityResolver.resolveEntity(publicId, systemId); - } catch (IOException e) { + } catch (final IOException e) { return null; } } @@ -85,6 +86,7 @@ public class MOADefaultHandler extends DefaultHandler { /** * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException) */ + @Override public void warning(SAXParseException exception) throws SAXException { errorHandler.warning(exception); } @@ -92,6 +94,7 @@ public class MOADefaultHandler extends DefaultHandler { /** * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException) */ + @Override public void error(SAXParseException exception) throws SAXException { errorHandler.error(exception); } @@ -99,6 +102,7 @@ public class MOADefaultHandler extends DefaultHandler { /** * @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException) */ + @Override public void fatalError(SAXParseException exception) throws SAXException { errorHandler.fatalError(exception); } diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/MOAEntityResolver.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/MOAEntityResolver.java index 7f529ca..d7c6a5b 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/MOAEntityResolver.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/MOAEntityResolver.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.util; import java.io.InputStream; @@ -35,18 +34,20 @@ import at.gv.egovernment.moaspss.logging.LogMsg; import at.gv.egovernment.moaspss.logging.Logger; /** - * An EntityResolver that looks up entities stored as - * local resources. - * - *

The following DTDs are mapped to local resources: + * 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, + *

+ * For all other resources, an attempt is made to resolve them as resources, * either absolute or relative to Constants.SCHEMA_ROOT. - * + * * @author Patrick Peck * @author Sven Aigner */ @@ -54,56 +55,58 @@ public class MOAEntityResolver implements EntityResolver { /** * 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 + * 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) + * null, if the entity could not be found. + * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, + * java.lang.String) */ + @Override public InputSource resolveEntity(String publicId, String systemId) { InputStream stream; int slashPos; if (Logger.isDebugEnabled()) { Logger.debug( - new LogMsg("resolveEntity: p=" + publicId + " s=" + systemId)); + new LogMsg("resolveEntity: p=" + publicId + " s=" + systemId)); } 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( - Constants.SCHEMA_ROOT + "XMLSchema.dtd")); + getClass().getResourceAsStream( + Constants.SCHEMA_ROOT + "XMLSchema.dtd")); } else if (publicId.equalsIgnoreCase("datatypes")) { return new InputSource( - getClass().getResourceAsStream( - Constants.SCHEMA_ROOT + "datatypes.dtd")); + getClass().getResourceAsStream( + Constants.SCHEMA_ROOT + "datatypes.dtd")); } } else if (systemId != null) { // get the URI path try { - URI uri = new URI(systemId); + final URI uri = new URI(systemId); systemId = uri.getPath(); - + if (!"file".equals(uri.getScheme()) || "".equals(systemId.trim())) { return null; } - - } catch (MalformedURIException e) { + + } catch (final 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); + final InputSource source = new InputSource(stream); source.setSystemId(systemId); return source; @@ -114,9 +117,9 @@ public class MOAEntityResolver implements EntityResolver { if (slashPos >= 0 && systemId.length() > slashPos) { systemId = systemId.substring(slashPos + 1, systemId.length()); stream = - getClass().getResourceAsStream(Constants.SCHEMA_ROOT + systemId); + getClass().getResourceAsStream(Constants.SCHEMA_ROOT + systemId); if (stream != null) { - InputSource source = new InputSource(stream); + final InputSource source = new InputSource(stream); source.setSystemId(systemId); return source; diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/MOAErrorHandler.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/MOAErrorHandler.java index 1842d03..f4acabf 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/MOAErrorHandler.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/MOAErrorHandler.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.util; import org.apache.xml.utils.DefaultErrorHandler; @@ -35,42 +34,48 @@ import at.gv.egovernment.moaspss.logging.Logger; * An ErrorHandler that logs a message and throws a * SAXException upon error and fatal * parsing errors. - * + * * @author Patrick Peck * @author Sven Aigner */ public class MOAErrorHandler extends DefaultErrorHandler { - /** * Logs a warning message. - * + * * @see org.xml.sax.ErrorHandler#warning(SAXParseException) */ + @Override public void warning(SAXParseException exception) throws SAXException { warn("parser.00", messageParams(exception), null); } /** * Logs a warning and rethrows the exception. - * + * * @see org.xml.sax.ErrorHandler#error(SAXParseException) */ + @Override public void error(SAXParseException exception) throws SAXException { - warn("parser.01", messageParams(exception), null); - - // if Target attribute is missing in QualifyingProperties - don't throw exception (bug fix for old MOCCA signatures) - if (exception.getMessage().startsWith("cvc-complex-type.4: Attribute 'Target' must appear on element")) - warn("parser.04", new Object[] {"Attribute 'Target' must appear on element 'QualifyingProperties' - ignored for compatibility reasons."}, null); - else - throw exception; + warn("parser.01", messageParams(exception), null); + + // if Target attribute is missing in QualifyingProperties - don't throw + // exception (bug fix for old MOCCA signatures) + if (exception.getMessage().startsWith("cvc-complex-type.4: Attribute 'Target' must appear on element")) { + warn("parser.04", new Object[] { + "Attribute 'Target' must appear on element 'QualifyingProperties' - ignored for compatibility reasons." }, + null); + } else { + throw exception; + } } /** * Logs a warning and rethrows the exception. - * + * * @see org.xml.sax.ErrorHandler#fatalError(SAXParseException) */ + @Override public void fatalError(SAXParseException exception) throws SAXException { warn("parser.02", messageParams(exception), null); throw exception; @@ -78,38 +83,38 @@ public class MOAErrorHandler extends DefaultErrorHandler { /** * Log a warning message. - * - * @param messageId The message ID to log. + * + * @param messageId The message ID to log. * @param parameters Additional message parameters. - * @param t The Throwable to log; usually the cause of this - * warning. + * @param t The Throwable to log; usually the cause of + * this warning. */ private static void warn( - String messageId, - Object[] parameters, - Throwable t) { + String messageId, + Object[] parameters, + Throwable t) { - MessageProvider msg = MessageProvider.getInstance(); + final MessageProvider msg = MessageProvider.getInstance(); Logger.warn(new LogMsg(msg.getMessage(messageId, parameters)), t); } /** - * Put the system id, line and column number information from the exception - * into an Object array, to provide it as a - * MessageFormat parameter. - * - * @param e The SAXParseException containing the - * source system id and line/column numbers. - * @return An array containing the system id (a String) as well - * as line/column numbers (2 Integer objects) from the - * SAXParseException. + * Put the system id, line and column number information from the exception into + * an Object array, to provide it as a MessageFormat + * parameter. + * + * @param e The SAXParseException containing the source system id + * and line/column numbers. + * @return An array containing the system id (a String) as well as + * line/column numbers (2 Integer objects) from the + * SAXParseException. */ private static Object[] messageParams(SAXParseException e) { return new Object[] { - e.getMessage(), - e.getSystemId(), - new Integer(e.getLineNumber()), - new Integer(e.getColumnNumber())}; + e.getMessage(), + e.getSystemId(), + new Integer(e.getLineNumber()), + new Integer(e.getColumnNumber()) }; } } \ No newline at end of file diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/MOATimer.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/MOATimer.java index 8542b58..591495a 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/MOATimer.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/MOATimer.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.util; import java.util.Map; @@ -29,7 +28,7 @@ import java.util.WeakHashMap; /** * A timer utility for named timers. - * + * * @author Sven Aigner */ public class MOATimer { @@ -43,7 +42,7 @@ public class MOATimer { /** * Return the single instance of this class. - * + * * @return The single instance of this class. */ public static MOATimer getInstance() { @@ -55,7 +54,7 @@ public class MOATimer { /** * Create a new MOATimer. - * + * * Protected to disallow multiple instances. */ protected MOATimer() { @@ -64,10 +63,10 @@ public class MOATimer { /** * Start timing a certain action. - * + * * The timing belonging to the action ID is garbage collected as soon as there * exists no other reference to the action ID. - * + * * @param id The action ID. */ public void startTiming(Object id) { @@ -76,7 +75,7 @@ public class MOATimer { /** * Stop timing an action. - * + * * @param id The action ID. */ public void stopTiming(Object id) { @@ -85,50 +84,53 @@ public class MOATimer { /** * Get the duration of an action. - * + * * @param id The action ID for which to compute the duration. * @return long The duration in milliseconds between calls to - * startTiming() and stopTiming(). If - * only startTiming() has been called for the action, then - * current difference to the system time is returned. If no timing exists for - * the action, - 1 is returned. + * startTiming() and stopTiming(). If only + * startTiming() has been called for the action, then + * current difference to the system time is returned. If no timing + * exists for the action, - 1 is returned. */ public long duration(Object id) { if (timemapstart.containsKey(id)) { - long start = ((Long) timemapstart.get(id)).longValue(); + final long start = ((Long) timemapstart.get(id)).longValue(); if (timemapend.containsKey(id)) { - long end = ((Long) timemapend.get(id)).longValue(); + final long end = ((Long) timemapend.get(id)).longValue(); return end - start; } else { return System.currentTimeMillis() - start; } - } else + } else { return -1; + } } /** * Get the duration of an action, as a nicely formatted String. - * + * * @param id The action ID. * @return String The duration() as a String. */ public String durationAsString(Object id) { - long dur = duration(id); - long second = dur / 1000; - long mil = (dur) - (second * 1000); + final long dur = duration(id); + final long second = dur / 1000; + final long mil = dur - second * 1000; return "Duration: " + second + "." + mil + " seconds"; } /** * Remove a timing. - * + * * @param id The action ID. */ public void clearTiming(String id) { - if (timemapstart.containsKey(id)) + if (timemapstart.containsKey(id)) { timemapstart.remove(id); - if (timemapend.containsKey(id)) + } + if (timemapend.containsKey(id)) { timemapend.remove(id); + } } } diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/MessageProvider.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/MessageProvider.java index da97ea1..163e903 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/MessageProvider.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/MessageProvider.java @@ -21,53 +21,52 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.util; import java.util.Locale; /** * A singleton wrapper around a Message object. - * + * * Provides the messages used in the common project. - * + * * @author Patrick Peck * @version $Id$ */ public class MessageProvider { /** The location of the default message resources. */ private static final String[] DEFAULT_MESSAGE_RESOURCES = - { "resources/properties/common_messages" }; + { "resources/properties/common_messages" }; /** The locale of the default message resources. */ private static final Locale[] DEFAULT_MESSAGE_LOCALES = - new Locale[] { new Locale("de", "AT") }; + new Locale[] { new Locale("de", "AT") }; /** The single instance of this class. */ private static MessageProvider instance; - + /** The messages provided by this MessageProvider. */ - private Messages messages; - + private final Messages messages; + /** * Return the single instance of the MessageProvider. - * + * * Intialilizes the MessageProvider with the default message * locations: /resources/properties/common_messages. - * + * * @return The single MessageProvider. */ public static synchronized MessageProvider getInstance() { if (instance == null) { instance = - new MessageProvider(DEFAULT_MESSAGE_RESOURCES, DEFAULT_MESSAGE_LOCALES); + new MessageProvider(DEFAULT_MESSAGE_RESOURCES, DEFAULT_MESSAGE_LOCALES); } return instance; } /** * Create a MessageProvider. - * + * * @param resourceNames The names of the resources containing the messages. - * @param locales The corresponding locales. + * @param locales The corresponding locales. */ protected MessageProvider(String[] resourceNames, Locale[] locales) { this.messages = new Messages(resourceNames, locales); @@ -76,9 +75,9 @@ public class MessageProvider { /** * Get the message corresponding to a given message ID. * - * @param messageId The ID of the message. + * @param messageId The ID of the message. * @param parameters The parameters to fill in into the message arguments. - * @return The formatted message. + * @return The formatted message. */ public String getMessage(String messageId, Object[] parameters) { return messages.getMessage(messageId, parameters); diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/Messages.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/Messages.java index 6e324b7..61d9b65 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/Messages.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/Messages.java @@ -21,47 +21,46 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.util; import java.text.MessageFormat; import java.util.Locale; import java.util.MissingResourceException; -import java.util.PropertyResourceBundle; +import java.util.ResourceBundle; import at.gv.egovernment.moaspss.logging.Logger; /** * Provides access to the system messages resource used for exception handling * and logging messages. - * + * * Messages must be provided as a resource bundle at the path. - * + * * @author Patrick Peck * @version $Id$ */ public class Messages { /** Error message indicating that no messages are avaiable. */ private static final String ERROR_MESSAGES_UNAVAILABLE = - "Fehler in der Server-Konfiguration. " - + "Die Fehlertexte konnten nicht geladen werden."; + "Fehler in der Server-Konfiguration. " + + "Die Fehlertexte konnten nicht geladen werden."; /** Error message indicating that the message is not available. */ private static final String ERROR_NO_MESSAGE = - "No errormesseage for error with number.={0}"; + "No errormesseage for error with number.={0}"; /** The names of the resources containing the messages. */ - private String[] resourceNames; + private final String[] resourceNames; /** The corresponding Locales of the resources. */ - private Locale[] locales; + private final Locale[] locales; /** The ResourceBundles containing the messages. */ private ResourceBundleChain messages; /** - * Create a new Message object containing the messages - * in the given resources. - * + * Create a new Message object containing the messages in the given + * resources. + * * @param resourceNames The names of the resources containing the messages. - * @param locales The corresponding locales. + * @param locales The corresponding locales. */ public Messages(String[] resourceNames, Locale[] locales) { this.resourceNames = resourceNames; @@ -72,9 +71,9 @@ public class Messages { /** * Get the message corresponding to a given message ID. * - * @param messageId The ID of the message. + * @param messageId The ID of the message. * @param parameters The parameters to fill in into the message arguments. - * @return The formatted message. + * @return The formatted message. */ public String getMessage(String messageId, Object[] parameters) { // initialize messages @@ -87,20 +86,20 @@ public class Messages { return ERROR_MESSAGES_UNAVAILABLE; } else { try { - String rawMessage = messages.getString(messageId); + final String rawMessage = messages.getString(messageId); return MessageFormat.format(rawMessage, parameters); - } catch (MissingResourceException e2) { - // couldn't find any message -> set to default error message + } catch (final MissingResourceException e2) { + // couldn't find any message -> set to default error message return MessageFormat.format( - ERROR_NO_MESSAGE, - new Object[] { messageId }); + ERROR_NO_MESSAGE, + new Object[] { messageId }); } } } /** * Return the names of the resources containing the messages. - * + * * @return String[] The names of the resource bundles containing the messages. */ private String[] getResourceNames() { @@ -109,9 +108,9 @@ public class Messages { /** * Return the Locales of the resources containing the messages. - * - * @return Locale[] The Locales of the resource bundles - * containing the messages. + * + * @return Locale[] The Locales of the resource bundles containing + * the messages. */ private Locale[] getLocales() { return locales; @@ -129,10 +128,10 @@ public class Messages { for (i = 0; i < resourceNames.length; i++) { try { messages.addResourceBundle( - PropertyResourceBundle.getBundle( - getResourceNames()[i], - getLocales()[i])); - } catch (MissingResourceException e) { + ResourceBundle.getBundle( + getResourceNames()[i], + getLocales()[i])); + } catch (final MissingResourceException e) { Logger.error(ERROR_MESSAGES_UNAVAILABLE, e); } } diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/MiscUtil.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/MiscUtil.java index 5510ac8..d2431e4 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/MiscUtil.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/MiscUtil.java @@ -1,13 +1,13 @@ /* * Copyright 2011 Federal Chancellery Austria and * Graz University of Technology - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,6 +25,7 @@ import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.text.ParseException; import java.text.SimpleDateFormat; +import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.GregorianCalendar; @@ -44,91 +45,89 @@ import javax.xml.transform.stream.StreamResult; import at.gv.egovernment.moaspss.logging.Logger; import at.gv.egovernment.moaspss.util.ex.EgovUtilException; - - /** * Class providing several utility methods. - * + * * @author Arne Tauber - * + * */ public class MiscUtil { - public static final String DEFAULT_SLASH = "/"; - - private static final int IO_BUFFER_SIZE = 4 * 1024; - - public static void copyStream(InputStream is, OutputStream os) throws IOException { - byte[] b = new byte[IO_BUFFER_SIZE]; - int read; - while ((read = is.read(b)) != -1) { - os.write(b, 0, read); - } - } - - public static void assertNotNull(Object param, String name) { - if (param == null) { - throw new NullPointerException(name + " must not be null."); - } - } - - public static boolean areAllNull(Object... objects) { - for (Object o : objects) { - if (o != null) { - return false; - } - } - return true; - } - - public static String extractContentType(String contentTypeString) { - if (contentTypeString == null) { - return ""; - } - if (contentTypeString.indexOf(";") != -1) { - return contentTypeString.substring(0, contentTypeString.indexOf(";")); - } - return contentTypeString; - } - - public static XMLGregorianCalendar getXMLGregorianCalendar(Date date) - throws DatatypeConfigurationException { - GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance(); - cal.setTime(date); - return DatatypeFactory.newInstance().newXMLGregorianCalendar(cal); - } - - public static XMLGregorianCalendar getXMLGregorianCalendar(String str) - throws DatatypeConfigurationException { - return DatatypeFactory.newInstance().newXMLGregorianCalendar(str); - } - - public static X509Certificate readCertificate(InputStream certStream) - throws CertificateException { - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - return (X509Certificate) cf.generateCertificate(certStream); - } - - public static boolean isEmpty(String str) { - return str == null || "".equals(str); - } - - public static boolean isNotEmpty(String str) { - return str != null && !"".equals(str); - } - - public static byte[] sourceToByteArray(Source result) - throws TransformerException { - TransformerFactory factory = TransformerFactory.newInstance(); - Transformer transformer = factory.newTransformer(); - transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); - transformer.setOutputProperty(OutputKeys.METHOD, "xml"); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - StreamResult streamResult = new StreamResult(); - streamResult.setOutputStream(out); - transformer.transform(result, streamResult); - return out.toByteArray(); - } + public static final String DEFAULT_SLASH = "/"; + + private static final int IO_BUFFER_SIZE = 4 * 1024; + + public static void copyStream(InputStream is, OutputStream os) throws IOException { + final byte[] b = new byte[IO_BUFFER_SIZE]; + int read; + while ((read = is.read(b)) != -1) { + os.write(b, 0, read); + } + } + + public static void assertNotNull(Object param, String name) { + if (param == null) { + throw new NullPointerException(name + " must not be null."); + } + } + + public static boolean areAllNull(Object... objects) { + for (final Object o : objects) { + if (o != null) { + return false; + } + } + return true; + } + + public static String extractContentType(String contentTypeString) { + if (contentTypeString == null) { + return ""; + } + if (contentTypeString.indexOf(";") != -1) { + return contentTypeString.substring(0, contentTypeString.indexOf(";")); + } + return contentTypeString; + } + + public static XMLGregorianCalendar getXMLGregorianCalendar(Date date) + throws DatatypeConfigurationException { + final GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance(); + cal.setTime(date); + return DatatypeFactory.newInstance().newXMLGregorianCalendar(cal); + } + + public static XMLGregorianCalendar getXMLGregorianCalendar(String str) + throws DatatypeConfigurationException { + return DatatypeFactory.newInstance().newXMLGregorianCalendar(str); + } + + public static X509Certificate readCertificate(InputStream certStream) + throws CertificateException { + final CertificateFactory cf = CertificateFactory.getInstance("X.509"); + return (X509Certificate) cf.generateCertificate(certStream); + } + + public static boolean isEmpty(String str) { + return str == null || "".equals(str); + } + + public static boolean isNotEmpty(String str) { + return str != null && !"".equals(str); + } + + public static byte[] sourceToByteArray(Source result) + throws TransformerException { + final TransformerFactory factory = TransformerFactory.newInstance(); + final Transformer transformer = factory.newTransformer(); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + transformer.setOutputProperty(OutputKeys.METHOD, "xml"); + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + final StreamResult streamResult = new StreamResult(); + streamResult.setOutputStream(out); + transformer.transform(result, streamResult); + return out.toByteArray(); + } // public static Document parseDocument(InputStream inputStream) // throws IOException { @@ -145,159 +144,159 @@ public class MiscUtil { // } // } - public static String removePrecedingSlash(String path, String slash) { - assertNotEmpty(slash, "Shash"); - if (!isEmpty(path)) { - while (path.startsWith(slash)) { - path = path.substring(slash.length(), path.length()); - } - } - return path; - } - - public static String removePrecedingSlash(String path) { - return removePrecedingSlash(path, DEFAULT_SLASH); - } - - public static void assertNotEmpty(String param, String name) { - if (param == null) { - throw new NullPointerException(name + " must not be null."); - } - if (param.length() == 0) { - throw new IllegalArgumentException(name + " must not be empty."); - } - } - - @SuppressWarnings("rawtypes") + public static String removePrecedingSlash(String path, String slash) { + assertNotEmpty(slash, "Shash"); + if (!isEmpty(path)) { + while (path.startsWith(slash)) { + path = path.substring(slash.length(), path.length()); + } + } + return path; + } + + public static String removePrecedingSlash(String path) { + return removePrecedingSlash(path, DEFAULT_SLASH); + } + + public static void assertNotEmpty(String param, String name) { + if (param == null) { + throw new NullPointerException(name + " must not be null."); + } + if (param.length() == 0) { + throw new IllegalArgumentException(name + " must not be empty."); + } + } + + @SuppressWarnings("rawtypes") public static boolean isEmpty(Properties props) { - if (props == null || props.isEmpty()) { - return true; - } - Iterator it = props.values().iterator(); - while (it.hasNext()) { - if (MiscUtil.isNotEmpty((String) it.next())) { - return false; - } - } - return true; - } - - public static boolean isEmpty(Empty empty) { - return empty == null || empty.isEmpty(); - } - - public static boolean isNotEmpty(Empty empty) { - return !isEmpty(empty); - } - - public static boolean isEmpty(byte[] data) { - return data == null || data.length == 0; - } - - public static boolean isNotEmpty(byte[] data) { - return !isEmpty(data); - } - - public static boolean isEmpty(Collection c) { - return c == null || c.isEmpty(); - } - - public static boolean isNotEmpty(Collection c) { - return !isEmpty(c); - } - - public static boolean areAllEmpty(String... strings) { - for (String s : strings) { - if (s != null && s.trim().length() != 0) { - return false; - } - } - return true; - } - - public static boolean areAllEmpty(Empty... empties) { - if (empties != null) { - for (Empty e : empties) { - if (e != null && !e.isEmpty()) { - return false; - } - } - } - return true; - } - - public static void assertNotEmpty(T[] param, String name) { - if (param == null) { - throw new NullPointerException(name + " must not be null."); - } - if (param.length == 0) { - throw new IllegalArgumentException(name + " must not be empty."); - } - } - - public static void assertNotEmpty(Empty empty, String name) { - if (empty == null) { - throw new NullPointerException(name + " must not be null."); - } - if (empty.isEmpty()) { - throw new IllegalArgumentException(name + " must not be empty."); - } - } - - public static void assertNotEmpty(byte[] param, String name) { - if (param == null) { - throw new NullPointerException(name + " must not be null."); - } - if (param.length == 0) { - throw new IllegalArgumentException(name + " must not be empty."); - } - } - - public static Date parseXMLDate(String xmlDate) throws EgovUtilException { - if (xmlDate == null) { - return null; - } - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - try { - return sdf.parse(xmlDate); - } catch (ParseException e) { - throw new EgovUtilException(e); - } - } - - public static boolean isEmpty(T[] array) { - return array == null || array.length == 0; - } - - public static boolean isNotEmpty(T[] array) { - return !isEmpty(array); - } - - public static String convertDateFromStandardToXML(String dateString) { - MiscUtil.assertNotNull(dateString, "dateString"); - Date date = parseDate(dateString); - return formatDate(date, "yyyy-MM-dd"); - } - - public static Date parseDate(String dateString) { - return parseDate(dateString, "dd.MM.yyyy"); - } - - public static Date parseDate(String dateString, String pattern) { - MiscUtil.assertNotNull(dateString, "dateString"); - MiscUtil.assertNotNull(pattern, "pattern"); - SimpleDateFormat sdf = new SimpleDateFormat(pattern); - try { - return sdf.parse(dateString); - } catch (ParseException e) { - Logger.warn("Error parsing date.", e); - return null; + if (props == null || props.isEmpty()) { + return true; } - } - - public static String formatDate(Date date, String format) { - SimpleDateFormat sdf = new SimpleDateFormat(format); - return sdf.format(date); - } - + final Iterator it = props.values().iterator(); + while (it.hasNext()) { + if (MiscUtil.isNotEmpty((String) it.next())) { + return false; + } + } + return true; + } + + public static boolean isEmpty(Empty empty) { + return empty == null || empty.isEmpty(); + } + + public static boolean isNotEmpty(Empty empty) { + return !isEmpty(empty); + } + + public static boolean isEmpty(byte[] data) { + return data == null || data.length == 0; + } + + public static boolean isNotEmpty(byte[] data) { + return !isEmpty(data); + } + + public static boolean isEmpty(Collection c) { + return c == null || c.isEmpty(); + } + + public static boolean isNotEmpty(Collection c) { + return !isEmpty(c); + } + + public static boolean areAllEmpty(String... strings) { + for (final String s : strings) { + if (s != null && s.trim().length() != 0) { + return false; + } + } + return true; + } + + public static boolean areAllEmpty(Empty... empties) { + if (empties != null) { + for (final Empty e : empties) { + if (e != null && !e.isEmpty()) { + return false; + } + } + } + return true; + } + + public static void assertNotEmpty(T[] param, String name) { + if (param == null) { + throw new NullPointerException(name + " must not be null."); + } + if (param.length == 0) { + throw new IllegalArgumentException(name + " must not be empty."); + } + } + + public static void assertNotEmpty(Empty empty, String name) { + if (empty == null) { + throw new NullPointerException(name + " must not be null."); + } + if (empty.isEmpty()) { + throw new IllegalArgumentException(name + " must not be empty."); + } + } + + public static void assertNotEmpty(byte[] param, String name) { + if (param == null) { + throw new NullPointerException(name + " must not be null."); + } + if (param.length == 0) { + throw new IllegalArgumentException(name + " must not be empty."); + } + } + + public static Date parseXMLDate(String xmlDate) throws EgovUtilException { + if (xmlDate == null) { + return null; + } + final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + try { + return sdf.parse(xmlDate); + } catch (final ParseException e) { + throw new EgovUtilException(e); + } + } + + public static boolean isEmpty(T[] array) { + return array == null || array.length == 0; + } + + public static boolean isNotEmpty(T[] array) { + return !isEmpty(array); + } + + public static String convertDateFromStandardToXML(String dateString) { + MiscUtil.assertNotNull(dateString, "dateString"); + final Date date = parseDate(dateString); + return formatDate(date, "yyyy-MM-dd"); + } + + public static Date parseDate(String dateString) { + return parseDate(dateString, "dd.MM.yyyy"); + } + + public static Date parseDate(String dateString, String pattern) { + MiscUtil.assertNotNull(dateString, "dateString"); + MiscUtil.assertNotNull(pattern, "pattern"); + final SimpleDateFormat sdf = new SimpleDateFormat(pattern); + try { + return sdf.parse(dateString); + } catch (final ParseException e) { + Logger.warn("Error parsing date.", e); + return null; + } + } + + public static String formatDate(Date date, String format) { + final SimpleDateFormat sdf = new SimpleDateFormat(format); + return sdf.format(date); + } + } diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/NodeIteratorAdapter.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/NodeIteratorAdapter.java index 998edb4..66907d2 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/NodeIteratorAdapter.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/NodeIteratorAdapter.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.util; import java.util.ListIterator; @@ -34,20 +33,21 @@ import org.w3c.dom.traversal.NodeIterator; /** * A NodeIterator implementation based on a * ListIterator. - * + * * @see java.util.ListIterator * @see org.w3c.dom.traversal.NodeIterator - * + * * @author Patrick Peck * @version $Id$ */ 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) { @@ -57,6 +57,7 @@ public class NodeIteratorAdapter implements NodeIterator { /** * @see org.w3c.dom.traversal.NodeIterator#getRoot() */ + @Override public Node getRoot() { return null; } @@ -64,6 +65,7 @@ public class NodeIteratorAdapter implements NodeIterator { /** * @see org.w3c.dom.traversal.NodeIterator#getWhatToShow() */ + @Override public int getWhatToShow() { return NodeFilter.SHOW_ALL; } @@ -71,6 +73,7 @@ public class NodeIteratorAdapter implements NodeIterator { /** * @see org.w3c.dom.traversal.NodeIterator#getFilter() */ + @Override public NodeFilter getFilter() { return null; } @@ -78,6 +81,7 @@ public class NodeIteratorAdapter implements NodeIterator { /** * @see org.w3c.dom.traversal.NodeIterator#getExpandEntityReferences() */ + @Override public boolean getExpandEntityReferences() { return false; } @@ -85,6 +89,7 @@ public class NodeIteratorAdapter implements NodeIterator { /** * @see org.w3c.dom.traversal.NodeIterator#nextNode() */ + @Override public Node nextNode() throws DOMException { if (nodeIterator.hasNext()) { return (Node) nodeIterator.next(); @@ -95,6 +100,7 @@ public class NodeIteratorAdapter implements NodeIterator { /** * @see org.w3c.dom.traversal.NodeIterator#previousNode() */ + @Override public Node previousNode() throws DOMException { if (nodeIterator.hasPrevious()) { return (Node) nodeIterator.previous(); @@ -105,6 +111,7 @@ public class NodeIteratorAdapter implements NodeIterator { /** * @see org.w3c.dom.traversal.NodeIterator#detach() */ + @Override public void detach() { } diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/NodeListAdapter.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/NodeListAdapter.java index d88ef4b..d569516 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/NodeListAdapter.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/NodeListAdapter.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.util; import java.util.List; @@ -31,21 +30,21 @@ import org.w3c.dom.NodeList; /** * A NodeList implementation based on a List. - * + * * @see java.util.List * @see org.w3c.dom.NodeList - * + * * @author Patrick Peck * @version $Id$ */ 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) { this.nodeList = nodeList; @@ -54,6 +53,7 @@ public class NodeListAdapter implements NodeList { /** * @see org.w3c.dom.NodeList#item(int) */ + @Override public Node item(int index) { return (Node) nodeList.get(index); } @@ -61,6 +61,7 @@ public class NodeListAdapter implements NodeList { /** * @see org.w3c.dom.NodeList#getLength() */ + @Override public int getLength() { return nodeList.size(); } diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/OutputXML2File.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/OutputXML2File.java index e4e6cc5..6ce951d 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/OutputXML2File.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/OutputXML2File.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - /* * Created on 26.04.2004 * @@ -36,67 +35,70 @@ import at.gv.egovernment.moaspss.logging.Logger; /** * utility functions to write XML data to files + * * @author rschamberger * @version $Id$ */ public class OutputXML2File { - /** - * writes an XML structure to file if debug is enabled in hierarchy (Encoding: UTF-8) - * - * @param filename file name - * @param rootElem root element in DOM tree - * @param hierarchy of the Logger - */ - public static void debugOutputXML2File(String filename, Element rootElem, String hierarchy) { - if (Logger.isDebugEnabled(hierarchy)) { - outputXML2File(filename, rootElem); - } - } - - /** - * writes an XML structure to file if debug is enabled in hierarchy (Encoding: UTF-8) - * - * @param filename file name - * @param xmlString XML string - * @param hierarchy of the Logger - */ - public static void debugOutputXML2File(String filename, String xmlString, String hierarchy) { - if (Logger.isDebugEnabled(hierarchy)) { - outputXML2File(filename, xmlString); - } - } + /** + * writes an XML structure to file if debug is enabled in hierarchy (Encoding: + * UTF-8) + * + * @param filename file name + * @param rootElem root element in DOM tree + * @param hierarchy of the Logger + */ + public static void debugOutputXML2File(String filename, Element rootElem, String hierarchy) { + if (Logger.isDebugEnabled(hierarchy)) { + outputXML2File(filename, rootElem); + } + } + + /** + * writes an XML structure to file if debug is enabled in hierarchy (Encoding: + * UTF-8) + * + * @param filename file name + * @param xmlString XML string + * @param hierarchy of the Logger + */ + public static void debugOutputXML2File(String filename, String xmlString, String hierarchy) { + if (Logger.isDebugEnabled(hierarchy)) { + outputXML2File(filename, xmlString); + } + } + + /** + * writes an XML structure to file (Encoding: UTF-8) + * + * @param filename file name + * @param rootElem root element in DOM tree + */ + public static void outputXML2File(String filename, Element rootElem) { + try { + final String xmlString = new String(DOMUtils.serializeNode(rootElem)); + outputXML2File(filename, xmlString); + } catch (final Exception ex) { + ex.printStackTrace(); + } + } - /** - * writes an XML structure to file (Encoding: UTF-8) - * - * @param filename file name - * @param rootElem root element in DOM tree - */ - public static void outputXML2File(String filename, Element rootElem) { - try { - String xmlString = new String(DOMUtils.serializeNode(rootElem)); - outputXML2File(filename, xmlString); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - /** - * writes an XML structure to file (Encoding: UTF-8) - * - * @param filename file name - * @param xmlString XML string - */ - public static void outputXML2File(String filename, String xmlString) { - try { - java.io.OutputStream fout = new java.io.FileOutputStream(filename); - byte[] xmlData = xmlString.getBytes("UTF-8"); - fout.write(xmlData); - fout.close(); - } catch (Exception ex) { - ex.printStackTrace(); - } - } + /** + * writes an XML structure to file (Encoding: UTF-8) + * + * @param filename file name + * @param xmlString XML string + */ + public static void outputXML2File(String filename, String xmlString) { + try { + final java.io.OutputStream fout = new java.io.FileOutputStream(filename); + final byte[] xmlData = xmlString.getBytes("UTF-8"); + fout.write(xmlData); + fout.close(); + } catch (final Exception ex) { + ex.printStackTrace(); + } + } } diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/ResourceBundleChain.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/ResourceBundleChain.java index 1edad95..a5c7ecc 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/ResourceBundleChain.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/ResourceBundleChain.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.util; import java.util.ArrayList; @@ -32,7 +31,7 @@ import java.util.ResourceBundle; /** * A class to chain ResourceBundles. - * + * * @author Patrick Peck * @version $Id$ */ @@ -40,11 +39,11 @@ public class ResourceBundleChain { /** Error message indicating the resource is not available. */ private static final String ERROR_MISSING_RESOURCE = "Missing resource"; /** The ResourceBundles contained in this chain. */ - private List resourceBundles = new ArrayList(); + private final List resourceBundles = new ArrayList(); /** * Add a ResourceBundle to the chain. - * + * * @param resourceBundle The ResourceBundle to add. */ public void addResourceBundle(ResourceBundle resourceBundle) { @@ -53,13 +52,13 @@ public class ResourceBundleChain { /** * Return the value of the resource. - * + * * @param key The key to access the String resource. * @return The resource value. All the registered ResourceBundles - * are searched in the order in which they have previously been added to this - * ResourceBundleChain. + * are searched in the order in which they have previously been added to + * this ResourceBundleChain. * @throws MissingResourceException The resource coult not be found in any of - * the bundles. + * the bundles. */ public String getString(String key) throws MissingResourceException { MissingResourceException lastException = null; @@ -68,19 +67,19 @@ public class ResourceBundleChain { // handle case where no resource bundles have been added if (resourceBundles.size() == 0) { throw new MissingResourceException( - ERROR_MISSING_RESOURCE, - this.getClass().getName(), - key); + ERROR_MISSING_RESOURCE, + this.getClass().getName(), + key); } // try to find the resource in one of the bundles; if it cannot be found, // return the exception thrown by the last bundle in the list for (iter = resourceBundles.iterator(); iter.hasNext();) { - ResourceBundle resourceBundle = (ResourceBundle) iter.next(); + final ResourceBundle resourceBundle = (ResourceBundle) iter.next(); try { - String value = resourceBundle.getString(key); + final String value = resourceBundle.getString(key); return value; - } catch (MissingResourceException e) { + } catch (final MissingResourceException e) { lastException = e; } } diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/SSLUtils.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/SSLUtils.java index 5078f01..d2d63cb 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/SSLUtils.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/SSLUtils.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.util; import java.io.IOException; @@ -38,207 +37,239 @@ import javax.net.ssl.TrustManagerFactory; /** * Utility for connecting to server applications via SSL. - * + * * @author Paul Ivancsics * @version $Id$ */ public class SSLUtils { - - /** - * Creates an SSLSocketFactory which utilizes the given trust store. - * - * @param trustStoreType key store type of trust store - * @param trustStoreInputStream input stream for reading JKS trust store containing - * trusted server certificates; if null, the default - * trust store will be utilized - * @param trustStorePassword if provided, it will be used to check - * the integrity of the trust store; if omitted, it will not be checked - * @return SSLSocketFactory to be used by an HttpsURLConnection - * @throws IOException thrown while reading from the input stream + + /** + * Creates an SSLSocketFactory which utilizes the given trust + * store. + * + * @param trustStoreType key store type of trust store + * @param trustStoreInputStream input stream for reading JKS trust store + * containing trusted server certificates; if + * null, the default trust store will + * be utilized + * @param trustStorePassword if provided, it will be used to check the + * integrity of the trust store; if omitted, it + * will not be checked + * @return SSLSocketFactory to be used by an + * HttpsURLConnection + * @throws IOException thrown while reading from the input stream * @throws GeneralSecurityException thrown while creating the socket factory - */ + */ public static SSLSocketFactory getSSLSocketFactory( - String trustStoreType, - InputStream trustStoreInputStream, - String trustStorePassword) - throws IOException, GeneralSecurityException { - - TrustManager[] tms = getTrustManagers(trustStoreType, trustStoreInputStream, trustStorePassword); - SSLContext ctx = SSLContext.getInstance("TLS"); - ctx.init(null, tms, null); - - SSLSocketFactory sf = ctx.getSocketFactory(); - return sf; + String trustStoreType, + InputStream trustStoreInputStream, + String trustStorePassword) + throws IOException, GeneralSecurityException { + + final TrustManager[] tms = getTrustManagers(trustStoreType, trustStoreInputStream, trustStorePassword); + final SSLContext ctx = SSLContext.getInstance("TLS"); + ctx.init(null, tms, null); + + final SSLSocketFactory sf = ctx.getSocketFactory(); + return sf; } - /** - * Creates an SSLSocketFactory which utilizes the - * given trust store and keystore. - * - * @param trustStore trust store containing trusted server certificates; - * if null, the default trust store will be utilized - * @param clientKeyStoreType key store type of clientKeyStore - * @param clientKeyStoreURL URL of key store containing keys to be used for - * client authentication; if null, the default key store will be utilized - * @param clientKeyStorePassword if provided, it will be used to check - * the integrity of the client key store; if omitted, it will not be checked - * @return SSLSocketFactory to be used by an HttpsURLConnection - * @throws IOException thrown while reading key store file + + /** + * Creates an SSLSocketFactory which utilizes the given trust store + * and keystore. + * + * @param trustStore trust store containing trusted server + * certificates; if null, the default + * trust store will be utilized + * @param clientKeyStoreType key store type of clientKeyStore + * @param clientKeyStoreURL URL of key store containing keys to be used for + * client authentication; if null, + * the default key store will be utilized + * @param clientKeyStorePassword if provided, it will be used to check the + * integrity of the client key store; if omitted, + * it will not be checked + * @return SSLSocketFactory to be used by an + * HttpsURLConnection + * @throws IOException thrown while reading key store file * @throws GeneralSecurityException thrown while creating the socket factory - */ + */ public static SSLSocketFactory getSSLSocketFactory( - KeyStore trustStore, - String clientKeyStoreType, - String clientKeyStoreURL, - String clientKeyStorePassword) - throws IOException, GeneralSecurityException { - - SSLContext ctx = getSSLContext( - trustStore, clientKeyStoreType, clientKeyStoreURL, clientKeyStorePassword); - SSLSocketFactory sf = ctx.getSocketFactory(); - return sf; + KeyStore trustStore, + String clientKeyStoreType, + String clientKeyStoreURL, + String clientKeyStorePassword) + throws IOException, GeneralSecurityException { + + final SSLContext ctx = getSSLContext( + trustStore, clientKeyStoreType, clientKeyStoreURL, clientKeyStorePassword); + final SSLSocketFactory sf = ctx.getSocketFactory(); + return sf; } - /** - * Creates an SSLContext initialized for the - * given trust store and keystore. - * - * @param trustStore trust store containing trusted server certificates; - * if null, the default trust store will be utilized - * @param clientKeyStoreType key store type of clientKeyStore - * @param clientKeyStoreURL URL of key store containing keys to be used for - * client authentication; if null, the default key store will be utilized - * @param clientKeyStorePassword if provided, it will be used to check - * the integrity of the client key store; if omitted, it will not be checked - * @return SSLContext to be used for creating an SSLSocketFactory - * @throws IOException thrown while reading key store file + + /** + * Creates an SSLContext initialized for the given trust store and + * keystore. + * + * @param trustStore trust store containing trusted server + * certificates; if null, the default + * trust store will be utilized + * @param clientKeyStoreType key store type of clientKeyStore + * @param clientKeyStoreURL URL of key store containing keys to be used for + * client authentication; if null, + * the default key store will be utilized + * @param clientKeyStorePassword if provided, it will be used to check the + * integrity of the client key store; if omitted, + * it will not be checked + * @return SSLContext to be used for creating an + * SSLSocketFactory + * @throws IOException thrown while reading key store file * @throws GeneralSecurityException thrown while creating the SSL context - */ + */ public static SSLContext getSSLContext( - KeyStore trustStore, - String clientKeyStoreType, - String clientKeyStoreURL, - String clientKeyStorePassword) - throws IOException, GeneralSecurityException { - - TrustManager[] tms = getTrustManagers(trustStore); - KeyManager[] kms = getKeyManagers(clientKeyStoreType, clientKeyStoreURL, clientKeyStorePassword); - SSLContext ctx = SSLContext.getInstance("TLS"); - ctx.init(kms, tms, null); - return ctx; + KeyStore trustStore, + String clientKeyStoreType, + String clientKeyStoreURL, + String clientKeyStorePassword) + throws IOException, GeneralSecurityException { + + final TrustManager[] tms = getTrustManagers(trustStore); + final KeyManager[] kms = getKeyManagers(clientKeyStoreType, clientKeyStoreURL, clientKeyStorePassword); + final SSLContext ctx = SSLContext.getInstance("TLS"); + ctx.init(kms, tms, null); + return ctx; } + /** - * Loads the trust store from an input stream and gets the + * Loads the trust store from an input stream and gets the * TrustManagers from a default TrustManagerFactory, - * initialized from the given trust store. - * @param trustStoreType key store type of trust store - * @param trustStoreInputStream input stream for reading JKS trust store containing - * trusted server certificates; if null, the default - * trust store will be utilized - * @param trustStorePassword if provided, it will be used to check - * the integrity of the trust store; if omitted, it will not be checked - * @return TrustManagers to be used for creating an - * SSLSocketFactory utilizing the given trust store - * @throws IOException thrown while reading from the input stream - * @throws GeneralSecurityException thrown while initializing the - * default TrustManagerFactory + * initialized from the given trust store. + * + * @param trustStoreType key store type of trust store + * @param trustStoreInputStream input stream for reading JKS trust store + * containing trusted server certificates; if + * null, the default trust store will + * be utilized + * @param trustStorePassword if provided, it will be used to check the + * integrity of the trust store; if omitted, it + * will not be checked + * @return TrustManagers to be used for creating an + * SSLSocketFactory utilizing the given trust store + * @throws IOException thrown while reading from the input stream + * @throws GeneralSecurityException thrown while initializing the default + * TrustManagerFactory */ - protected static TrustManager[] getTrustManagers( - String trustStoreType, - InputStream trustStoreInputStream, - String trustStorePassword) - throws IOException, GeneralSecurityException { - - if (trustStoreInputStream == null) - return null; - - // Set up the TrustStore to use. We need to load the file into - // a KeyStore instance. - KeyStore trustStore = KeyStoreUtils.loadKeyStore(trustStoreType, trustStoreInputStream, trustStorePassword); - return getTrustManagers(trustStore); - } - /** - * Gets the TrustManagers from a default TrustManagerFactory, - * initialized from the given trust store. - * - * @param trustStore the trust store to use - * @return TrustManagers to be used for creating an - * SSLSocketFactory utilizing the given trust store - * @throws GeneralSecurityException thrown while initializing the - * default TrustManagerFactory - */ - protected static TrustManager[] getTrustManagers(KeyStore trustStore) - throws GeneralSecurityException { - - if (trustStore == null) - return null; - - // Initialize the default TrustManagerFactory with this KeyStore - String alg=TrustManagerFactory.getDefaultAlgorithm(); - TrustManagerFactory tmFact=TrustManagerFactory.getInstance(alg); - tmFact.init(trustStore); - - // And now get the TrustManagers - TrustManager[] tms=tmFact.getTrustManagers(); - return tms; - } + protected static TrustManager[] getTrustManagers( + String trustStoreType, + InputStream trustStoreInputStream, + String trustStorePassword) + throws IOException, GeneralSecurityException { + + if (trustStoreInputStream == null) { + return null; + } + + // Set up the TrustStore to use. We need to load the file into + // a KeyStore instance. + final KeyStore trustStore = KeyStoreUtils.loadKeyStore(trustStoreType, trustStoreInputStream, + trustStorePassword); + return getTrustManagers(trustStore); + } + /** - * Loads the client key store from file and gets the - * KeyManagers from a default KeyManagerFactory, - * initialized from the given client key store. - * @param clientKeyStoreType key store type of clientKeyStore - * @param clientKeyStoreURL URL of key store containing keys to be used for - * client authentication; if null, the default key store will be utilized - * @param clientKeyStorePassword password used to check the integrity of the client key store; - * if null, it will not be checked - * @return KeyManagers to be used for creating an - * SSLSocketFactory utilizing the given client key store - * @throws IOException thrown while reading from the key store file - * @throws GeneralSecurityException thrown while initializing the - * default KeyManagerFactory + * Gets the TrustManagers from a default + * TrustManagerFactory, initialized from the given trust store. + * + * @param trustStore the trust store to use + * @return TrustManagers to be used for creating an + * SSLSocketFactory utilizing the given trust store + * @throws GeneralSecurityException thrown while initializing the default + * TrustManagerFactory */ - public static KeyManager[] getKeyManagers ( - String clientKeyStoreType, - String clientKeyStoreURL, - String clientKeyStorePassword) - throws IOException, GeneralSecurityException { - - if (clientKeyStoreURL == null) - return null; - - // Set up the KeyStore to use. We need to load the file into - // a KeyStore instance. - KeyStore clientKeyStore = KeyStoreUtils.loadKeyStore( - clientKeyStoreType, clientKeyStoreURL, clientKeyStorePassword); - return getKeyManagers(clientKeyStore, clientKeyStorePassword); - } + protected static TrustManager[] getTrustManagers(KeyStore trustStore) + throws GeneralSecurityException { + + if (trustStore == null) { + return null; + } + + // Initialize the default TrustManagerFactory with this KeyStore + final String alg = TrustManagerFactory.getDefaultAlgorithm(); + final TrustManagerFactory tmFact = TrustManagerFactory.getInstance(alg); + tmFact.init(trustStore); + + // And now get the TrustManagers + final TrustManager[] tms = tmFact.getTrustManagers(); + return tms; + } + /** - * Gets the KeyManagers from a default KeyManagerFactory, - * initialized from the given client key store. - * @param clientKeyStore client key store - * @param clientKeyStorePassword if provided, it will be used to check - * the integrity of the client key store; if omitted, it will not be checked - * @return KeyManagers to be used for creating an - * SSLSocketFactory utilizing the given client key store - * @throws GeneralSecurityException thrown while initializing the - * default KeyManagerFactory + * Loads the client key store from file and gets the KeyManagers + * from a default KeyManagerFactory, initialized from the given + * client key store. + * + * @param clientKeyStoreType key store type of clientKeyStore + * @param clientKeyStoreURL URL of key store containing keys to be used for + * client authentication; if null, + * the default key store will be utilized + * @param clientKeyStorePassword password used to check the integrity of the + * client key store; if null, it will + * not be checked + * @return KeyManagers to be used for creating an + * SSLSocketFactory utilizing the given client key store + * @throws IOException thrown while reading from the key store file + * @throws GeneralSecurityException thrown while initializing the default + * KeyManagerFactory */ - public static KeyManager[] getKeyManagers ( - KeyStore clientKeyStore, - String clientKeyStorePassword) - throws GeneralSecurityException { - - if (clientKeyStore == null) - return null; - - // Now we initialize the default KeyManagerFactory with this KeyStore - String alg=KeyManagerFactory.getDefaultAlgorithm(); - KeyManagerFactory kmFact=KeyManagerFactory.getInstance(alg); - char[] password = null; - if (clientKeyStorePassword != null) - password = clientKeyStorePassword.toCharArray(); - kmFact.init(clientKeyStore, password); - - // And now get the KeyManagers - KeyManager[] kms=kmFact.getKeyManagers(); - return kms; - } + public static KeyManager[] getKeyManagers( + String clientKeyStoreType, + String clientKeyStoreURL, + String clientKeyStorePassword) + throws IOException, GeneralSecurityException { + + if (clientKeyStoreURL == null) { + return null; + } + + // Set up the KeyStore to use. We need to load the file into + // a KeyStore instance. + final KeyStore clientKeyStore = KeyStoreUtils.loadKeyStore( + clientKeyStoreType, clientKeyStoreURL, clientKeyStorePassword); + return getKeyManagers(clientKeyStore, clientKeyStorePassword); + } + + /** + * Gets the KeyManagers from a default + * KeyManagerFactory, initialized from the given client key store. + * + * @param clientKeyStore client key store + * @param clientKeyStorePassword if provided, it will be used to check the + * integrity of the client key store; if omitted, + * it will not be checked + * @return KeyManagers to be used for creating an + * SSLSocketFactory utilizing the given client key store + * @throws GeneralSecurityException thrown while initializing the default + * KeyManagerFactory + */ + public static KeyManager[] getKeyManagers( + KeyStore clientKeyStore, + String clientKeyStorePassword) + throws GeneralSecurityException { + + if (clientKeyStore == null) { + return null; + } + + // Now we initialize the default KeyManagerFactory with this KeyStore + final String alg = KeyManagerFactory.getDefaultAlgorithm(); + final KeyManagerFactory kmFact = KeyManagerFactory.getInstance(alg); + char[] password = null; + if (clientKeyStorePassword != null) { + password = clientKeyStorePassword.toCharArray(); + } + kmFact.init(clientKeyStore, password); + + // And now get the KeyManagers + final KeyManager[] kms = kmFact.getKeyManagers(); + return kms; + } } diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/StreamEntityResolver.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/StreamEntityResolver.java index 5d328cf..06efdda 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/StreamEntityResolver.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/StreamEntityResolver.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.util; import java.io.IOException; @@ -33,23 +32,26 @@ import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** - * An EntityResolver that maps system IDs to + * An EntityResolver that maps system IDs to * InputStreams. - * + * * @author Patrick Peck * @version $Id$ */ public class StreamEntityResolver implements EntityResolver { - - /** A mapping from Public ID or System ID to an InputStream - * containing the entity. */ - private Map mappedEntities; - + + /** + * A mapping from Public ID or System ID to an InputStream + * containing the entity. + */ + private final Map mappedEntities; + /** * Create a StreamEntityResolver. - * - * @param mappedEntities A mapping from public or system IDs - * (String objects) to InputStreams. + * + * @param mappedEntities A mapping from public or system IDs + * (String objects) to + * InputStreams. */ public StreamEntityResolver(Map mappedEntities) { this.mappedEntities = mappedEntities; @@ -57,32 +59,33 @@ public class StreamEntityResolver implements EntityResolver { /** * Resolve an entity by looking it up in the mapped entities. - * + * * First, the public ID is looked up in the mapping, then the system ID. - * + * * @param publicId The public ID of the entity. * @param systemId The system ID of the entity. - * @return An InputStream containing the entity or - * null if no entity could be found. + * @return An InputStream containing the entity or + * null if no entity could be found. * @throws SAXException Signalling a parsing exception. - * @throws IOException Error reading the entity. + * @throws IOException Error reading the entity. */ - public InputSource resolveEntity(String publicId, String systemId) - throws SAXException, IOException { - + @Override + public InputSource resolveEntity(String publicId, String systemId) + throws SAXException, IOException { + InputSource src = null; - + if (publicId != null && mappedEntities.get(publicId) != null) { src = new InputSource((InputStream) mappedEntities.get(publicId)); } else if (systemId != null && mappedEntities.get(systemId) != null) { src = new InputSource((InputStream) mappedEntities.get(systemId)); } - + if (src != null) { src.setPublicId(publicId); src.setSystemId(systemId); } - + return src; } } diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/StreamUtils.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/StreamUtils.java index f3abe9c..41eae87 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/StreamUtils.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/StreamUtils.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.util; import java.io.ByteArrayOutputStream; @@ -32,34 +31,34 @@ 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. + * 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(InputStream is1, 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; } @@ -70,127 +69,128 @@ 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) { + } catch (final IOException e) { // ignore this } } } - + /** * 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 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. + * otherwise. */ private static boolean compareBytes(byte[] b1, byte[] b2, 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 { - 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 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. * @throws IOException on any exception thrown */ public static String readStream(InputStream in, String encoding) 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.toString(encoding); } - + /** - * Reads all data (until EOF is reached) from the given source to the + * 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. + * 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 + * @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. */ - private static void copyStream(InputStream source, OutputStream destination, byte[] buffer) throws IOException { + private static void copyStream(InputStream source, 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); - } + 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(); + public static String getStackTraceAsString(Throwable t) { + final ByteArrayOutputStream stackTraceBIS = new ByteArrayOutputStream(); t.printStackTrace(new PrintStream(stackTraceBIS)); return new String(stackTraceBIS.toByteArray()); } diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/StringUtils.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/StringUtils.java index 695be18..4c22340 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/StringUtils.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/StringUtils.java @@ -21,59 +21,59 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.util; import java.util.StringTokenizer; /** * Utitility functions for string manipulations. - * + * * @author Harald Bratko */ public class StringUtils { /** * Removes all blanks and tabs from the given string. - * + * * @param s The string to remove all blanks and tabs from. - * @return The input string with all blanks and tabs removed from. + * @return The input string with all blanks and tabs removed from. */ public static String removeBlanks(String s) { - StringTokenizer st = new StringTokenizer(s); - StringBuffer sb = new StringBuffer(s.length()); + final StringTokenizer st = new StringTokenizer(s); + final StringBuffer sb = new StringBuffer(s.length()); while (st.hasMoreTokens()) { sb.append(st.nextToken()); } return sb.toString(); } - + /** * Removes all occurences of the specified token from the the given string. - * + * * @param s The string to remove all occurences of the specified token from. - * @return The input string with all occurences of the specified token removed from. + * @return The input string with all occurences of the specified token removed + * from. */ public static String removeToken(String s, String token) { - StringTokenizer st = new StringTokenizer(s, token); - StringBuffer sb = new StringBuffer(s.length()); + final StringTokenizer st = new StringTokenizer(s, token); + final StringBuffer sb = new StringBuffer(s.length()); while (st.hasMoreTokens()) { sb.append(st.nextToken()); } return sb.toString(); } - + /** * Removes all leading zeros from the input string. - * - * @param s The string remove the leading zeros from. - * @return The input string with the leading zeros removed from. + * + * @param s The string remove the leading zeros from. + * @return The input string with the leading zeros removed from. */ public static String deleteLeadingZeros(String s) { - StringBuffer sb = new StringBuffer(s); - int l = sb.length(); + final StringBuffer sb = new StringBuffer(s); + final int l = sb.length(); int j = 0; - for (int i=0; is that matches the given * search string by the given replace string. - * - * @param s The string where the replacement should take place. - * @param search The pattern that should be replaced. - * @param replace The string that should replace all each search - * string within s. - * @return A string where all occurrence of search are - * replaced with replace. + * + * @param s The string where the replacement should take place. + * @param search The pattern that should be replaced. + * @param replace The string that should replace all each search + * string within s. + * @return A string where all occurrence of search are replaced + * with replace. */ - public static String replaceAll (String s, String search, String replace) - { - StringBuffer sb = new StringBuffer(); - int i = 0, j = 0; - int len = search.length(); - while (j > -1) - { - j = s.indexOf(search, i); + public static String replaceAll(String s, String search, String replace) { + final StringBuffer sb = new StringBuffer(); + int i = 0, j = 0; + final int len = search.length(); + while (j > -1) { + j = s.indexOf(search, i); + + if (j > -1) { + sb.append(s.substring(i, j)); + sb.append(replace); + i = j + len; + } + } - if (j > -1) - { - sb.append(s.substring(i,j)); - sb.append(replace); - i = j + len; - } - } - - sb.append(s.substring(i, s.length())); + sb.append(s.substring(i, s.length())); - return sb.toString(); + return sb.toString(); } - + /** - * Changes the SecurityLayer version in the given string. - * This method usually takes as input an XML structure represented in a string - * format and changes the SecurityLayer namespaces prefixes and URIs from - * one SecurityLayer version to another. - * e.g.: code>sl10 to sl and - * http://www.buergerkarte.at/namespaces/securitylayer/20020225# - * to - * http://www.buergerkarte.at/namespaces/securitylayer/1.2# - * - * @param s The string (usally an XML structure) where the - * SecurityLayer version should be changed. - * @param slPrefixOld The SecurityLayer namespace prefix that should be - * replaced by the new one. - * @param slPrefixNew The new SecurityLayer namespace prefix that should - * replace the old one. - * @param slNSUriOld The SecurityLayer namespace URI that should be - * replaced by the new one. - * @param slNSUriNew The new SecurityLayer namespace URI that should - * replace the old one. - * @return A string where the SecurityLayer namespace prefixes - * and URIs are replaced by new ones. + * Changes the SecurityLayer version in the given string. This method usually + * takes as input an XML structure represented in a string format and changes + * the SecurityLayer namespaces prefixes and URIs from one SecurityLayer version + * to another. e.g.: code>sl10 to sl and + * http://www.buergerkarte.at/namespaces/securitylayer/20020225# to + * http://www.buergerkarte.at/namespaces/securitylayer/1.2# + * + * @param s The string (usally an XML structure) where the + * SecurityLayer version should be changed. + * @param slPrefixOld The SecurityLayer namespace prefix that should be replaced + * by the new one. + * @param slPrefixNew The new SecurityLayer namespace prefix that should replace + * the old one. + * @param slNSUriOld The SecurityLayer namespace URI that should be replaced by + * the new one. + * @param slNSUriNew The new SecurityLayer namespace URI that should replace + * the old one. + * @return A string where the SecurityLayer namespace prefixes and URIs are + * replaced by new ones. */ - public static String changeSLVersion(String s, String slPrefixOld, String slPrefixNew, String slNSUriOld, String slNSUriNew) { + public static String changeSLVersion(String s, String slPrefixOld, String slPrefixNew, String slNSUriOld, + String slNSUriNew) { String retString = replaceAll(s, slPrefixOld, slPrefixNew); retString = replaceAll(retString, slNSUriOld, slNSUriNew); - return retString ; + return retString; } - + /** * Removes the XML declaration from an XML expression. - * + * * @param xmlString XML expression as String - * + * * @return XML expression, XML declaration removed */ public static String removeXMLDeclaration(String xmlString) { - if (xmlString!=null && xmlString.startsWith("application/x-www-form-urlencoded string using a specific encoding scheme. - * @param s the string to decode + * Decodes an application/x-www-form-urlencoded string using a + * specific encoding scheme. + * + * @param s the string to decode * @param encoding name of character encoding * @return the newly decoded string * @throws UnsupportedEncodingException if the encoding is not supported */ public static String decode(String s, String encoding) throws UnsupportedEncodingException { - StringReader in = new StringReader(s); - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - for (int b = read(in); b >= 0; b = read(in)) + final StringReader in = new StringReader(s); + final ByteArrayOutputStream bout = new ByteArrayOutputStream(); + for (int b = read(in); b >= 0; b = read(in)) { bout.write(b); + } return bout.toString(encoding); } + /** * Decodes the next byte from the string reader. + * * @param in string reader - * @return the next byte decoded; - * -1 upon end of string, on erroneous data, and on any exception caught + * @return the next byte decoded; -1 upon end of string, on erroneous data, and + * on any exception caught * @todo syntax check on string */ private static int read(StringReader in) { - try { - int b = in.read(); - if (b == '+') + try { + final int b = in.read(); + if (b == '+') { return ' '; + } if (b == '%') { - char[] hex = new char[2]; + final char[] hex = new char[2]; if (in.read(hex, 0, 2) >= 0) { - String hexString = new String(hex); + final String hexString = new String(hex); return Integer.valueOf(hexString, 16).intValue(); - } - else + } else { return -1; + } } return b; - } - catch (IOException ex) { - return -1; - } - catch (NumberFormatException ex) { - return -1; + } catch (final IOException ex) { + return -1; + } catch (final NumberFormatException ex) { + return -1; } } } diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/URLEncoder.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/URLEncoder.java index 2aa7e22..5eaece3 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/URLEncoder.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/URLEncoder.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.util; import java.io.ByteArrayInputStream; @@ -29,60 +28,68 @@ import java.io.StringWriter; import java.io.UnsupportedEncodingException; /** - * Translates a string into mime format "x-www-form-urlencoded". - * Provides a function missing in JDK 1.3. + * Translates a string into mime format "x-www-form-urlencoded". Provides a + * function missing in JDK 1.3. + * * @author Paul Ivancsics * @version $Id$ */ public class URLEncoder { - + /** * Translates a string into x-www-form-urlencoded format. - * @param s the string to be translated + * + * @param s the string to be translated * @param encoding the encoding to use * @return the translated string - * @throws UnsupportedEncodingException when the desired encoding is not supported + * @throws UnsupportedEncodingException when the desired encoding is not + * supported */ public static String encode(String s, String encoding) throws UnsupportedEncodingException { // if (MiscUtil.isEmpty(s)) // return null; - byte[] barr = s.getBytes(encoding); - ByteArrayInputStream bin = new ByteArrayInputStream(barr); - StringWriter out = new StringWriter(); - for (int b = bin.read(); b >= 0; b = bin.read()) + final byte[] barr = s.getBytes(encoding); + final ByteArrayInputStream bin = new ByteArrayInputStream(barr); + final StringWriter out = new StringWriter(); + for (int b = bin.read(); b >= 0; b = bin.read()) { encode(b, out); + } return out.toString(); } - + /** * Encode a character. - * @param ch The character to encode. + * + * @param ch The character to encode. * @param out The StringWriter containing the result. */ private static void encode(int ch, StringWriter out) { - if ((ch >= 'a' && ch <= 'z') - || (ch >= 'A' && ch <= 'Z') - || (ch >= '0' && ch <= '9') - || ch == '.' || ch == '-' || ch == '*' || ch == '_') + if (ch >= 'a' && ch <= 'z' + || ch >= 'A' && ch <= 'Z' + || ch >= '0' && ch <= '9' + || ch == '.' || ch == '-' || ch == '*' || ch == '_') { out.write(ch); - else if (ch == ' ') + } else if (ch == ' ') { out.write('+'); - else + } else { encodeHex(ch, out); + } } - + /** - * Encode a character as an escaped hex value. - * @param ch The character to encode. + * Encode a character as an escaped hex value. + * + * @param ch The character to encode. * @param out The StringWriter containing the result. */ private static void encodeHex(int ch, StringWriter out) { out.write('%'); - String hex = Integer.toHexString(ch).toUpperCase(); - if (hex.length() < 2) + final String hex = Integer.toHexString(ch).toUpperCase(); + if (hex.length() < 2) { out.write('0'); - else + } else { out.write(hex.charAt(hex.length() - 2)); + } out.write(hex.charAt(hex.length() - 1)); } diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/XPathException.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/XPathException.java index cbf3e4e..9a60bd2 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/XPathException.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/XPathException.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.util; import java.io.PrintStream; @@ -29,33 +28,33 @@ import java.io.PrintWriter; /** * An exception occurred evaluating an XPath. - * + * * @author Patrick Peck * @version $Id$ */ public class XPathException extends RuntimeException { /** - * - */ - private static final long serialVersionUID = 1736311265333034392L; -/** The wrapped exception. */ - private Throwable wrapped; - + * + */ + private static final long serialVersionUID = 1736311265333034392L; + /** The wrapped exception. */ + private final 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) { // TODO: remove wrapped from super cstr. again - super(message, wrapped); - this.wrapped = wrapped; + super(message, wrapped); + this.wrapped = wrapped; } - + /** * Return the wrapped exception. - * + * * @return The wrapped exception being the likely cause of this exception. */ public Throwable getWrapped() { @@ -65,6 +64,7 @@ public class XPathException extends RuntimeException { /** * @see java.lang.Throwable#printStackTrace(java.io.PrintStream) */ + @Override public void printStackTrace(PrintStream s) { super.printStackTrace(s); if (getWrapped() != null) { @@ -76,6 +76,7 @@ public class XPathException extends RuntimeException { /** * @see java.lang.Throwable#printStackTrace(java.io.PrintWriter) */ + @Override public void printStackTrace(PrintWriter s) { super.printStackTrace(s); if (getWrapped() != null) { @@ -83,5 +84,5 @@ public class XPathException extends RuntimeException { getWrapped().printStackTrace(s); } } - + } diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/XPathUtils.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/XPathUtils.java index 2604c20..3bc3bb9 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/XPathUtils.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/XPathUtils.java @@ -21,28 +21,26 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moaspss.util; import java.util.List; import java.util.Map; -import org.w3c.dom.Attr; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.w3c.dom.traversal.NodeIterator; - import org.jaxen.JaxenException; import org.jaxen.NamespaceContext; import org.jaxen.Navigator; import org.jaxen.SimpleNamespaceContext; import org.jaxen.dom.DOMXPath; import org.jaxen.dom.DocumentNavigator; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.w3c.dom.traversal.NodeIterator; /** * Utility methods to evaluate XPath expressions on DOM nodes. - * + * * @author Patrick Peck * @version $Id$ */ @@ -53,16 +51,16 @@ public class XPathUtils { * root node itself). */ public static final String ALL_NODES_XPATH = - "(.//. | .//@* | .//namespace::*)"; + "(.//. | .//@* | .//namespace::*)"; /** The DocumentNavigator to use for navigating the document. */ private static Navigator documentNavigator = - DocumentNavigator.getInstance(); + DocumentNavigator.getInstance(); /** The default namespace prefix to namespace URI mappings. */ private static NamespaceContext NS_CONTEXT; static { - SimpleNamespaceContext ctx = new SimpleNamespaceContext(); + final SimpleNamespaceContext ctx = new SimpleNamespaceContext(); ctx.addNamespace(Constants.MOA_PREFIX, Constants.MOA_NS_URI); ctx.addNamespace(Constants.MOA_CONFIG_PREFIX, Constants.MOA_CONFIG_NS_URI); ctx.addNamespace(Constants.MOA_ID_CONFIG_PREFIX, Constants.MOA_ID_CONFIG_NS_URI); @@ -95,18 +93,17 @@ public class XPathUtils { /** * 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. + * + * @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 { + throws XPathException { return selectNodeIterator(contextNode, NS_CONTEXT, exp); } @@ -114,28 +111,28 @@ public class XPathUtils { /** * 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. + * + * @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 { + Node contextNode, + Element namespaceElement, + 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) { - MessageProvider msg = MessageProvider.getInstance(); - String message = msg.getMessage("xpath.00", new Object[] { exp }); + } catch (final JaxenException e) { + final MessageProvider msg = MessageProvider.getInstance(); + final String message = msg.getMessage("xpath.00", new Object[] { exp }); throw new XPathException(message, e); } } @@ -143,23 +140,23 @@ public class XPathUtils { /** * Return a NodeIterator over the nodes matching the XPath * expression. - * - * @param contextNode The root node from which to evaluate 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. + * (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 { + Node contextNode, + Map namespaceMapping, + String exp) + throws XPathException { - SimpleNamespaceContext ctx = new SimpleNamespaceContext(namespaceMapping); + final SimpleNamespaceContext ctx = new SimpleNamespaceContext(namespaceMapping); return selectNodeIterator(contextNode, ctx, exp); } @@ -167,31 +164,31 @@ public class XPathUtils { /** * 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. + * + * @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 { + Node contextNode, + NamespaceContext nsContext, + 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) { - MessageProvider msg = MessageProvider.getInstance(); - String message = msg.getMessage("xpath.00", new Object[] { exp }); + } catch (final JaxenException e) { + final MessageProvider msg = MessageProvider.getInstance(); + final String message = msg.getMessage("xpath.00", new Object[] { exp }); throw new XPathException(message, e); } } @@ -199,18 +196,17 @@ public class XPathUtils { /** * 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. + * + * @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 { + throws XPathException { return selectNodeList(contextNode, NS_CONTEXT, exp); } @@ -218,29 +214,29 @@ public class XPathUtils { /** * 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. + * + * @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 { + Node contextNode, + Element namespaceElement, + 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) { - MessageProvider msg = MessageProvider.getInstance(); - String message = msg.getMessage("xpath.00", new Object[] { exp }); + } catch (final JaxenException e) { + final MessageProvider msg = MessageProvider.getInstance(); + final String message = msg.getMessage("xpath.00", new Object[] { exp }); throw new XPathException(message, e); } } @@ -248,23 +244,23 @@ public class XPathUtils { /** * Return a NodeList of all the nodes matching the XPath * expression. - * - * @param contextNode The root node from which to evaluate 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. + * (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 { + Node contextNode, + Map namespaceMapping, + String exp) + throws XPathException { - SimpleNamespaceContext ctx = new SimpleNamespaceContext(namespaceMapping); + final SimpleNamespaceContext ctx = new SimpleNamespaceContext(namespaceMapping); return selectNodeList(contextNode, ctx, exp); } @@ -272,133 +268,132 @@ public class XPathUtils { /** * 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. + * + * @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 { + Node contextNode, + NamespaceContext nsContext, + 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 NodeListAdapter(nodes); - } catch (JaxenException e) { - MessageProvider msg = MessageProvider.getInstance(); - String message = msg.getMessage("xpath.00", new Object[] { exp }); + } catch (final JaxenException e) { + final MessageProvider msg = MessageProvider.getInstance(); + final String message = msg.getMessage("xpath.00", new Object[] { exp }); throw new XPathException(message, 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. - * @param exp The XPath expression to evaluate. + * + * @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. + * null, if no node matched. * @throws XPathException An error occurred evaluating the XPath expression. */ public static Node selectSingleNode(Node contextNode, String exp) - throws XPathException { + 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 exp The XPath expression to evaluate. + * + * @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. + * 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 { + Node contextNode, + Element namespaceElement, + 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) { - MessageProvider msg = MessageProvider.getInstance(); - String message = msg.getMessage("xpath.00", new Object[] { exp }); + } catch (final JaxenException e) { + final MessageProvider msg = MessageProvider.getInstance(); + final String message = msg.getMessage("xpath.00", new Object[] { exp }); throw new XPathException(message, e); } } /** * Select the first node matching an XPath expression. - * - * @param contextNode The root node from which to evaluate 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. + * (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. + * 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 { + Node contextNode, + Map namespaceMapping, + 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 exp The XPath expression to evaluate. + * + * @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. + * 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 { + Node contextNode, + NamespaceContext nsContext, + 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) { - MessageProvider msg = MessageProvider.getInstance(); - String message = msg.getMessage("xpath.00", new Object[] { exp }); + } catch (final JaxenException e) { + final MessageProvider msg = MessageProvider.getInstance(); + final String message = msg.getMessage("xpath.00", new Object[] { exp }); throw new XPathException(message, e); } } @@ -406,140 +401,137 @@ public class XPathUtils { /** * 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 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. */ public static String getElementValue( - Element root, - String xpath, - String def) { + Element root, + String xpath, + String def) { - Element elem = (Element) XPathUtils.selectSingleNode(root, xpath); + 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. - * - * @param root The root element from which to evaluate the XPath. + * + * @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. + * 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) { + Element root, + String xpath, + 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. + * 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. * - * 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). + * @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(); + public static String getSlPrefix(Element contextElement) throws XPathException { + final String sLNamespace = contextElement.getNamespaceURI(); String sLPrefix = null; - if (sLNamespace.equals(Constants.SL10_NS_URI)) - { + if (sLNamespace.equals(Constants.SL10_NS_URI)) { sLPrefix = Constants.SL10_PREFIX; - } - else if (sLNamespace.equals(Constants.SL12_NS_URI)) - { + } else if (sLNamespace.equals(Constants.SL12_NS_URI)) { sLPrefix = Constants.SL12_PREFIX; - } - else if (sLNamespace.equals(Constants.SL11_NS_URI)) - { + } else if (sLNamespace.equals(Constants.SL11_NS_URI)) { sLPrefix = Constants.SL11_PREFIX; - } - else - { - MessageProvider msg = MessageProvider.getInstance(); - String message = msg.getMessage("xpath.00", new Object[] { "Ung�ltiger Security Layer Namespace: \"" + sLNamespace + "\"."}); + } else { + final MessageProvider msg = MessageProvider.getInstance(); + final String message = msg.getMessage("xpath.00", new Object[] { + "Ung�ltiger Security Layer Namespace: \"" + sLNamespace + "\"." }); throw new XPathException(message, null); } - + 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. * - * @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. + * @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 { - + public static String getSlPrefixFromNoRoot(Element contextElement) throws XPathException { + String slPrefix = checkSLnsDeclaration(contextElement, Constants.SL10_PREFIX, Constants.SL10_NS_URI); if (slPrefix == null) { slPrefix = checkSLnsDeclaration(contextElement, Constants.SL11_PREFIX, Constants.SL11_NS_URI); } if (slPrefix == null) { slPrefix = checkSLnsDeclaration(contextElement, Constants.SL12_PREFIX, Constants.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. + * 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. * - * @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. + * @return The valid SecurityLayer prefix or null if this prefix is + * not used. * @throws XPathException */ private static String checkSLnsDeclaration(Element contextElement, String slPrefix, String slNameSpace) - throws XPathException - { - String nsAtt = "xmlns:" + slPrefix; - String nameSpace = contextElement.getAttribute(nsAtt); + throws XPathException { + final String nsAtt = "xmlns:" + slPrefix; + final String nameSpace = contextElement.getAttribute(nsAtt); if (nameSpace == "") { return null; } else { @@ -547,8 +539,9 @@ public class XPathUtils { if (nameSpace.equals(slNameSpace)) { return slPrefix; } else { - MessageProvider msg = MessageProvider.getInstance(); - String message = msg.getMessage("xpath.00", new Object[] { "Ung�ltiger SecurityLayer Namespace: \"" + nameSpace + "\"."}); + final MessageProvider msg = MessageProvider.getInstance(); + final String message = msg.getMessage("xpath.00", new Object[] { + "Ung�ltiger SecurityLayer Namespace: \"" + nameSpace + "\"." }); throw new XPathException(message, null); } } diff --git a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/ex/EgovUtilException.java b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/ex/EgovUtilException.java index 27169b4..5960fce 100644 --- a/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/ex/EgovUtilException.java +++ b/moaSig/common/src/main/java/at/gv/egovernment/moaspss/util/ex/EgovUtilException.java @@ -1,13 +1,13 @@ /* * Copyright 2011 Federal Chancellery Austria and * Graz University of Technology - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,24 +18,24 @@ package at.gv.egovernment.moaspss.util.ex; public class EgovUtilException extends Exception { - /** - * + /** + * */ private static final long serialVersionUID = 1L; - public EgovUtilException() { - } + public EgovUtilException() { + } - public EgovUtilException(String message) { - super(message); - } + public EgovUtilException(String message) { + super(message); + } - public EgovUtilException(Throwable cause) { - super(cause); - } + public EgovUtilException(Throwable cause) { + super(cause); + } - public EgovUtilException(String message, Throwable cause) { - super(message, cause); - } + public EgovUtilException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/moaSig/moa-asic/build.gradle b/moaSig/moa-asic/build.gradle index f8a536d..8df208c 100644 --- a/moaSig/moa-asic/build.gradle +++ b/moaSig/moa-asic/build.gradle @@ -12,11 +12,16 @@ configurations { dependencies { - jaxb group: 'com.sun.xml.bind', name: 'jaxb-xjc', version: '2.2.4-1' + jaxb group: 'com.sun.xml.bind', name: 'jaxb-xjc', version: '2.2.11' compile project(':common') compile project(':moa-sig-lib') - compile 'org.slf4j:slf4j-log4j12:1.7.30' + compile 'org.slf4j:slf4j-log4j12:1.7.30' + implementation group: 'javax.xml.bind', name: 'jaxb-api', version: '2.3.1' + implementation group: 'javax.xml.ws', name: 'jaxws-api', version: '2.3.1' + //implementation group: 'com.sun.xml.bind', name: 'jaxb-core', version: '2.2.11' + //implementation group: 'com.sun.xml.bind', name: 'jaxb-impl', version: '2.2.11' + //implementation group: 'com.sun.xml.ws', name: 'jaxws-ri', version: '2.2.10', ext: 'pom' } sourceSets { diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiC.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiC.java index 759e910..d8bf4d9 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiC.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiC.java @@ -4,11 +4,15 @@ import java.util.Collection; import java.util.List; public interface ASiC { - public ASiCFormat getFormat(); - public boolean isXAdES(); - public boolean isCAdES(); + ASiCFormat getFormat(); - public List getSignaturesEntries(); - public Collection getDataEntries(); - public List getInformationEntries(); + boolean isXAdES(); + + boolean isCAdES(); + + List getSignaturesEntries(); + + Collection getDataEntries(); + + List getInformationEntries(); } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiCConstants.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiCConstants.java index 02baf40..b987346 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiCConstants.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiCConstants.java @@ -4,6 +4,6 @@ package at.gv.egiz.asic.api; * Created by afitzek on 6/15/16. */ public interface ASiCConstants { - public static final String FILE_MIME_TYPE = "mimetype"; - public static final String FILE_META_INF = "META-INF/"; + String FILE_MIME_TYPE = "mimetype"; + String FILE_META_INF = "META-INF/"; } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiCEntry.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiCEntry.java index 7c026cf..f0a9edd 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiCEntry.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiCEntry.java @@ -7,32 +7,32 @@ import java.io.InputStream; */ public class ASiCEntry { - private String entryName; - private InputStream contents; - - public ASiCEntry() { - } - - public String getEntryName() { - return entryName; - } - - public void setEntryName(String entryName) { - this.entryName = entryName; - } - - public InputStream getContents() { - return contents; - } - - public void setContents(InputStream contents) { - this.contents = contents; - } - - @Override - public String toString() { - return "ASiCEntry{" + - "entryName='" + entryName + '\'' + - '}'; - } + private String entryName; + private InputStream contents; + + public ASiCEntry() { + } + + public String getEntryName() { + return entryName; + } + + public void setEntryName(String entryName) { + this.entryName = entryName; + } + + public InputStream getContents() { + return contents; + } + + public void setContents(InputStream contents) { + this.contents = contents; + } + + @Override + public String toString() { + return "ASiCEntry{" + + "entryName='" + entryName + '\'' + + '}'; + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiCFactory.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiCFactory.java index 661e418..ccab9a4 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiCFactory.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiCFactory.java @@ -1,16 +1,5 @@ package at.gv.egiz.asic.api; -import at.gv.egiz.asic.exceptions.ASiCException; -import at.gv.egiz.asic.impl.ASiCBaseFormatFactory; -import at.gv.egiz.asic.impl.ASiCExtendedFormatFactory; -import at.gv.egiz.asic.impl.ASiCSimpleFormatFactory; -import at.gv.egiz.asic.impl.ZipCommentReaderStream; -import at.gv.egovernment.moa.spss.MOAApplicationException; -import at.gv.egovernment.moa.spss.MOAException; -import org.apache.commons.io.IOUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -18,147 +7,158 @@ import java.io.InputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import at.gv.egiz.asic.impl.ASiCBaseFormatFactory; +import at.gv.egiz.asic.impl.ASiCExtendedFormatFactory; +import at.gv.egiz.asic.impl.ASiCSimpleFormatFactory; +import at.gv.egiz.asic.impl.ZipCommentReaderStream; +import at.gv.egovernment.moa.spss.MOAApplicationException; +import at.gv.egovernment.moa.spss.MOAException; + /** * Created by afitzek on 6/15/16. */ public class ASiCFactory { - private static final Logger logger = LoggerFactory.getLogger(ASiCFactory.class); - - private static final String MIMETYPE_FORMAT_E = "application/vnd.etsi.asic-e+zip"; - private static final String MIMETYPE_FORMAT_S = "application/vnd.etsi.asic-s+zip"; - - public static ASiC parseASiC(InputStream is, ASiCFormat format) throws MOAException { - - InputStream newInputStream = is; - - - // Try to determine the asic format! - if (!newInputStream.markSupported()) { - ByteArrayOutputStream asicContainer = new ByteArrayOutputStream(); - - try { - IOUtils.copy(newInputStream, asicContainer); - } catch (IOException e) { - throw new MOAApplicationException("asic.0003", null); - } - newInputStream = new ByteArrayInputStream(asicContainer.toByteArray()); - } - - String mimeTypeFile = null; - ZipCommentReaderStream commentReaderStream = new ZipCommentReaderStream(newInputStream); - byte[] buffer = new byte[8096]; - try { - while (commentReaderStream.read(buffer) >= 0) { - } - newInputStream.reset(); - } catch (IOException e) { - throw new MOAApplicationException("asic.0003", null); - } - - ZipInputStream zipInputStream = new ZipInputStream(newInputStream); - - try { - for (ZipEntry entry = zipInputStream.getNextEntry(); entry != null; entry = zipInputStream.getNextEntry()) { - String entryName = entry.getName(); - - if("mimetype".equalsIgnoreCase(entryName)) { - if(mimeTypeFile == null) { - mimeTypeFile = IOUtils.toString(zipInputStream, "UTF-8"); - } else { - logger.warn("multiple mimetype files found in archiv"); - } - } - } - newInputStream.reset(); - } catch (IOException e) { - throw new MOAApplicationException("asic.0007", null); - } - - String fileComment = commentReaderStream.getFileComment(); - ASiCFormat fileCommentFormat = null; - if (fileComment != null) { - logger.debug("Found file comment in ASiC {}", fileComment); - if(fileComment.startsWith("mimetype=")) { - String fileCommentMimeType = fileComment.substring("mimetype=".length()); - if(fileCommentMimeType.startsWith(MIMETYPE_FORMAT_E)) { - fileCommentFormat = ASiCFormat.ASiCE; - } else if(fileCommentMimeType.startsWith(MIMETYPE_FORMAT_S)) { - fileCommentFormat = ASiCFormat.ASiCS; - } - } - } else { - logger.info("No file comment in ASiC"); - } - - - ASiCFormat mimeTypeFileFormat = null; - if (mimeTypeFile != null) { - logger.debug("Found mimetype file in ASiC {}", mimeTypeFile); - if(MIMETYPE_FORMAT_E.equalsIgnoreCase(mimeTypeFile)) { - mimeTypeFileFormat = ASiCFormat.ASiCE; - } else if(MIMETYPE_FORMAT_S.equalsIgnoreCase(mimeTypeFile)) { - mimeTypeFileFormat = ASiCFormat.ASiCS; - } - } else { - logger.info("No mimetype file in ASiC"); - } - - if (format == null) { - if (fileCommentFormat != null && mimeTypeFileFormat != null) { - // both are set - if (fileCommentFormat == mimeTypeFileFormat) { - format = fileCommentFormat; - } else { - throw new MOAApplicationException("asic.0009", null); - } - } else if (fileCommentFormat != null) { - format = fileCommentFormat; - } else if (mimeTypeFileFormat != null) { - format = mimeTypeFileFormat; - } else { - throw new MOAApplicationException("asic.0008", null); - } - } else { - // format is provided, only check for missmatches - if (fileCommentFormat != null && fileCommentFormat != format) { - logger.warn("ASiC format missmatch file comment {} vs provided {}", fileCommentFormat, format); - throw new MOAApplicationException("asic.0009", null); - } - if (mimeTypeFileFormat != null && mimeTypeFileFormat != format) { - logger.warn("ASiC format missmatch mimetype file {} vs provided {}", mimeTypeFileFormat, format); - throw new MOAApplicationException("asic.0009", null); - } - - if (fileCommentFormat != null && mimeTypeFileFormat != null) { - // both are set - if (fileCommentFormat != mimeTypeFileFormat) { - logger.warn("ASiC format missmatch file comment {} vs mimetype file {}", fileCommentFormat, mimeTypeFileFormat); - throw new MOAApplicationException("asic.0009", null); - } - } - } + private static final Logger logger = LoggerFactory.getLogger(ASiCFactory.class); - ASiCBaseFormatFactory formatFactory = null; + private static final String MIMETYPE_FORMAT_E = "application/vnd.etsi.asic-e+zip"; + private static final String MIMETYPE_FORMAT_S = "application/vnd.etsi.asic-s+zip"; - if (format == null) { - throw new MOAApplicationException("asic.0008", null); + public static ASiC parseASiC(InputStream is, ASiCFormat format) throws MOAException { + + InputStream newInputStream = is; + + // Try to determine the asic format! + if (!newInputStream.markSupported()) { + final ByteArrayOutputStream asicContainer = new ByteArrayOutputStream(); + + try { + IOUtils.copy(newInputStream, asicContainer); + } catch (final IOException e) { + throw new MOAApplicationException("asic.0003", null); + } + newInputStream = new ByteArrayInputStream(asicContainer.toByteArray()); + } + + String mimeTypeFile = null; + final ZipCommentReaderStream commentReaderStream = new ZipCommentReaderStream(newInputStream); + final byte[] buffer = new byte[8096]; + try { + while (commentReaderStream.read(buffer) >= 0) { + } + newInputStream.reset(); + } catch (final IOException e) { + throw new MOAApplicationException("asic.0003", null); + } + + final ZipInputStream zipInputStream = new ZipInputStream(newInputStream); + + try { + for (ZipEntry entry = zipInputStream.getNextEntry(); entry != null; entry = zipInputStream + .getNextEntry()) { + final String entryName = entry.getName(); + + if ("mimetype".equalsIgnoreCase(entryName)) { + if (mimeTypeFile == null) { + mimeTypeFile = IOUtils.toString(zipInputStream, "UTF-8"); + } else { + logger.warn("multiple mimetype files found in archiv"); + } } + } + newInputStream.reset(); + } catch (final IOException e) { + throw new MOAApplicationException("asic.0007", null); + } - switch (format) { - case ASiCE: - formatFactory = new ASiCExtendedFormatFactory(); - break; - case ASiCS: - formatFactory = new ASiCSimpleFormatFactory(); - break; + final String fileComment = commentReaderStream.getFileComment(); + ASiCFormat fileCommentFormat = null; + if (fileComment != null) { + logger.debug("Found file comment in ASiC {}", fileComment); + if (fileComment.startsWith("mimetype=")) { + final String fileCommentMimeType = fileComment.substring("mimetype=".length()); + if (fileCommentMimeType.startsWith(MIMETYPE_FORMAT_E)) { + fileCommentFormat = ASiCFormat.ASiCE; + } else if (fileCommentMimeType.startsWith(MIMETYPE_FORMAT_S)) { + fileCommentFormat = ASiCFormat.ASiCS; } + } + } else { + logger.info("No file comment in ASiC"); + } - if (formatFactory == null) { - throw new MOAApplicationException("asic.0008", null); + ASiCFormat mimeTypeFileFormat = null; + if (mimeTypeFile != null) { + logger.debug("Found mimetype file in ASiC {}", mimeTypeFile); + if (MIMETYPE_FORMAT_E.equalsIgnoreCase(mimeTypeFile)) { + mimeTypeFileFormat = ASiCFormat.ASiCE; + } else if (MIMETYPE_FORMAT_S.equalsIgnoreCase(mimeTypeFile)) { + mimeTypeFileFormat = ASiCFormat.ASiCS; + } + } else { + logger.info("No mimetype file in ASiC"); + } + + if (format == null) { + if (fileCommentFormat != null && mimeTypeFileFormat != null) { + // both are set + if (fileCommentFormat == mimeTypeFileFormat) { + format = fileCommentFormat; + } else { + throw new MOAApplicationException("asic.0009", null); } + } else if (fileCommentFormat != null) { + format = fileCommentFormat; + } else if (mimeTypeFileFormat != null) { + format = mimeTypeFileFormat; + } else { + throw new MOAApplicationException("asic.0008", null); + } + } else { + // format is provided, only check for missmatches + if (fileCommentFormat != null && fileCommentFormat != format) { + logger.warn("ASiC format missmatch file comment {} vs provided {}", fileCommentFormat, format); + throw new MOAApplicationException("asic.0009", null); + } + if (mimeTypeFileFormat != null && mimeTypeFileFormat != format) { + logger.warn("ASiC format missmatch mimetype file {} vs provided {}", mimeTypeFileFormat, format); + throw new MOAApplicationException("asic.0009", null); + } + + if (fileCommentFormat != null && mimeTypeFileFormat != null) { + // both are set + if (fileCommentFormat != mimeTypeFileFormat) { + logger.warn("ASiC format missmatch file comment {} vs mimetype file {}", fileCommentFormat, + mimeTypeFileFormat); + throw new MOAApplicationException("asic.0009", null); + } + } + } + + ASiCBaseFormatFactory formatFactory = null; - return formatFactory.createASiC(newInputStream); + if (format == null) { + throw new MOAApplicationException("asic.0008", null); } + switch (format) { + case ASiCE: + formatFactory = new ASiCExtendedFormatFactory(); + break; + case ASiCS: + formatFactory = new ASiCSimpleFormatFactory(); + break; + } + + if (formatFactory == null) { + throw new MOAApplicationException("asic.0008", null); + } + + return formatFactory.createASiC(newInputStream); + } + } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiCFormat.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiCFormat.java index 8106944..cc72f58 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiCFormat.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiCFormat.java @@ -4,6 +4,6 @@ package at.gv.egiz.asic.api; * Created by Andreas Fitzek on 6/15/16. */ public enum ASiCFormat { - ASiCS, - ASiCE + ASiCS, + ASiCE } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiCVerificationResult.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiCVerificationResult.java index ce8f374..a29b5c2 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiCVerificationResult.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiCVerificationResult.java @@ -1,41 +1,43 @@ package at.gv.egiz.asic.api; +import java.util.ArrayList; +import java.util.List; + import at.gv.egiz.asic.impl.AsicSignedFilesContainer; import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureResponse; import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureResponse; -import java.util.ArrayList; -import java.util.List; - /** * Created by Andreas Fitzek on 6/16/16. */ public class ASiCVerificationResult { - private List signedFiles = new ArrayList(); + private List signedFiles = new ArrayList<>(); - private VerifyCMSSignatureResponse cmsResult = null; - private VerifyXMLSignatureResponse xmlResult = null; + private VerifyCMSSignatureResponse cmsResult = null; + private VerifyXMLSignatureResponse xmlResult = null; - public ASiCVerificationResult(List references, VerifyCMSSignatureResponse cmsResult) { - this.signedFiles = references; - this.cmsResult = cmsResult; - } + public ASiCVerificationResult(List references, + VerifyCMSSignatureResponse cmsResult) { + this.signedFiles = references; + this.cmsResult = cmsResult; + } - public ASiCVerificationResult(List references, VerifyXMLSignatureResponse xmlResult) { - this.signedFiles = references; - this.xmlResult = xmlResult; - } + public ASiCVerificationResult(List references, + VerifyXMLSignatureResponse xmlResult) { + this.signedFiles = references; + this.xmlResult = xmlResult; + } - public List getSignedFiles() { - return signedFiles; - } + public List getSignedFiles() { + return signedFiles; + } - public VerifyXMLSignatureResponse getXmlResult() { - return xmlResult; - } + public VerifyXMLSignatureResponse getXmlResult() { + return xmlResult; + } - public VerifyCMSSignatureResponse getCmsResult() { - return cmsResult; - } + public VerifyCMSSignatureResponse getCmsResult() { + return cmsResult; + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiCVerifier.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiCVerifier.java index 77bc61d..fc8de87 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiCVerifier.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/api/ASiCVerifier.java @@ -1,16 +1,15 @@ package at.gv.egiz.asic.api; -import at.gv.egovernment.moa.spss.MOAException; -import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureResponse; - import java.util.Date; import java.util.List; +import at.gv.egovernment.moa.spss.MOAException; + /** * Created by Andreas Fitzek on 6/15/16. */ public interface ASiCVerifier { - public List verify(ASiC asic, String trustProfileID, Date date) throws MOAException; + List verify(ASiC asic, String trustProfileID, Date date) throws MOAException; } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/exceptions/ASiCContainerInvalidException.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/exceptions/ASiCContainerInvalidException.java index ea6d19c..1927528 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/exceptions/ASiCContainerInvalidException.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/exceptions/ASiCContainerInvalidException.java @@ -1,7 +1,7 @@ package at.gv.egiz.asic.exceptions; public class ASiCContainerInvalidException extends ASiCException { - public ASiCContainerInvalidException(String reason) { - super(); - } + public ASiCContainerInvalidException(String reason) { + super(); + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ASiCBaseFormatFactory.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ASiCBaseFormatFactory.java index 578371c..65c6ccc 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ASiCBaseFormatFactory.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ASiCBaseFormatFactory.java @@ -1,16 +1,5 @@ package at.gv.egiz.asic.impl; -import at.gv.egiz.asic.api.ASiC; -import at.gv.egiz.asic.api.ASiCEntry; -import at.gv.egiz.asic.api.ASiCFormat; -import at.gv.egiz.asic.impl.handler.*; -import at.gv.egovernment.moa.spss.MOAApplicationException; -import at.gv.egovernment.moa.spss.MOAException; -import iaik.util.logging.Log; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; @@ -21,125 +10,142 @@ import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import at.gv.egiz.asic.api.ASiC; +import at.gv.egiz.asic.api.ASiCEntry; +import at.gv.egiz.asic.api.ASiCFormat; +import at.gv.egiz.asic.impl.handler.AllDataHandler; +import at.gv.egiz.asic.impl.handler.MetaInfHandler; +import at.gv.egiz.asic.impl.handler.MimefileHandler; +import at.gv.egovernment.moa.spss.MOAApplicationException; +import at.gv.egovernment.moa.spss.MOAException; + /** * Created by Andreas Fitzek on 6/15/16. */ public abstract class ASiCBaseFormatFactory implements ASiCContainer { - private static final Logger logger = LoggerFactory.getLogger(ASiCBaseFormatFactory.class); - - protected boolean cadesSigned = false; - protected boolean xadesSigned = false; - protected boolean timestamped = false; + private static final Logger logger = LoggerFactory.getLogger(ASiCBaseFormatFactory.class); - protected String mimeType = null; + protected boolean cadesSigned = false; + protected boolean xadesSigned = false; + protected boolean timestamped = false; - protected List signatureEntries = new ArrayList(); - protected Map dataEntries = new HashMap(); - protected List informationEntries = new ArrayList(); + protected String mimeType = null; - protected List handlers = new ArrayList(); + protected List signatureEntries = new ArrayList<>(); + protected Map dataEntries = new HashMap<>(); + protected List informationEntries = new ArrayList<>(); - @Override - public void addDataEntry(ASiCEntry entry) throws MOAApplicationException { - //check if entry with a specific name already exists - if (!dataEntries.containsKey(entry.getEntryName())) { - this.dataEntries.put(entry.getEntryName(), entry); - - } else { - logger.warn("ASiC container already contains a DataEntry with name: " + entry.getEntryName() + " ASiC container is INVALID"); - throw new MOAApplicationException("asic.0017", new Object[]{entry.getEntryName()}); - } - } + protected List handlers = new ArrayList<>(); - @Override - public void addSignatureEntry(ASiCEntry entry) { - this.signatureEntries.add(entry); - } + @Override + public void addDataEntry(ASiCEntry entry) throws MOAApplicationException { + // check if entry with a specific name already exists + if (!dataEntries.containsKey(entry.getEntryName())) { + this.dataEntries.put(entry.getEntryName(), entry); - @Override - public void addInformationEntry(ASiCEntry entry) { - this.informationEntries.add(entry); + } else { + logger.warn("ASiC container already contains a DataEntry with name: " + entry.getEntryName() + + " ASiC container is INVALID"); + throw new MOAApplicationException("asic.0017", new Object[] { entry.getEntryName() }); } + } - public ASiCBaseFormatFactory() { - handlers.add(new MimefileHandler()); - handlers.add(new MetaInfHandler()); - handlers.add(new AllDataHandler()); - } + @Override + public void addSignatureEntry(ASiCEntry entry) { + this.signatureEntries.add(entry); + } - public abstract ASiCFormat factoryFormat(); + @Override + public void addInformationEntry(ASiCEntry entry) { + this.informationEntries.add(entry); + } - protected abstract void validate() throws MOAException; + public ASiCBaseFormatFactory() { + handlers.add(new MimefileHandler()); + handlers.add(new MetaInfHandler()); + handlers.add(new AllDataHandler()); + } - public ASiC createASiC(InputStream is) throws MOAException { + public abstract ASiCFormat factoryFormat(); - ZipCommentReaderStream commentReaderStream = new ZipCommentReaderStream(is); + protected abstract void validate() throws MOAException; - ZipInputStream zipInputStream = new ZipInputStream(commentReaderStream); + public ASiC createASiC(InputStream is) throws MOAException { - try { - for (ZipEntry entry = zipInputStream.getNextEntry(); entry != null; entry = zipInputStream.getNextEntry()) { - String entryName = entry.getName(); + final ZipCommentReaderStream commentReaderStream = new ZipCommentReaderStream(is); - Iterator handlerIterator = this.handlers.iterator(); - while (handlerIterator.hasNext()) { - EntryHandler entryHandler = handlerIterator.next(); + final ZipInputStream zipInputStream = new ZipInputStream(commentReaderStream); - if (entryHandler.handle(entryName, zipInputStream, this)) { - break; - } - } - } - } catch(IOException e) { - logger.info("Failed to read from ASiC Container", e); - throw new MOAApplicationException("asic.0007", null); - } + try { + for (ZipEntry entry = zipInputStream.getNextEntry(); entry != null; entry = zipInputStream + .getNextEntry()) { + final String entryName = entry.getName(); + final Iterator handlerIterator = this.handlers.iterator(); + while (handlerIterator.hasNext()) { + final EntryHandler entryHandler = handlerIterator.next(); - if(this.mimeType == null) { - String mimeTypeComment = commentReaderStream.getFileComment(); - if(mimeTypeComment != null) { - this.mimeType = mimeTypeComment; - } + if (entryHandler.handle(entryName, zipInputStream, this)) { + break; + } } - - this.validate(); - - // unpack and retrieve all available information on ASiC signature - return new ASiCImpl(this.factoryFormat(), this.xadesSigned, this.cadesSigned, this.signatureEntries, dataEntries.values(), this.informationEntries); + } + } catch (final IOException e) { + logger.info("Failed to read from ASiC Container", e); + throw new MOAApplicationException("asic.0007", null); } - @Override - public void setMimeType(String mimeType) { - this.mimeType = mimeType; + if (this.mimeType == null) { + final String mimeTypeComment = commentReaderStream.getFileComment(); + if (mimeTypeComment != null) { + this.mimeType = mimeTypeComment; + } } - public void setIsXAdES() throws MOAException { - if(this.cadesSigned) { - throw new MOAApplicationException("asic.0010", null); - } - this.xadesSigned = true; - } + this.validate(); - public void setIsCAdES() throws MOAException { - if(this.xadesSigned) { - throw new MOAApplicationException("asic.0010", null); - } - this.cadesSigned = true; - } + // unpack and retrieve all available information on ASiC signature + return new ASiCImpl(this.factoryFormat(), this.xadesSigned, this.cadesSigned, this.signatureEntries, + dataEntries.values(), this.informationEntries); + } - public void setIsTimestamped() throws MOAException { - throw new MOAApplicationException("asic.0013", null); - } + @Override + public void setMimeType(String mimeType) { + this.mimeType = mimeType; + } - @Override - public void setIsEvidenceERS() throws MOAException { - throw new MOAApplicationException("asic.0011", null); + @Override + public void setIsXAdES() throws MOAException { + if (this.cadesSigned) { + throw new MOAApplicationException("asic.0010", null); } + this.xadesSigned = true; + } - @Override - public void setIsEvidenceXML() throws MOAException { - throw new MOAApplicationException("asic.0012", null); + @Override + public void setIsCAdES() throws MOAException { + if (this.xadesSigned) { + throw new MOAApplicationException("asic.0010", null); } + this.cadesSigned = true; + } + + @Override + public void setIsTimestamped() throws MOAException { + throw new MOAApplicationException("asic.0013", null); + } + + @Override + public void setIsEvidenceERS() throws MOAException { + throw new MOAApplicationException("asic.0011", null); + } + + @Override + public void setIsEvidenceXML() throws MOAException { + throw new MOAApplicationException("asic.0012", null); + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ASiCContainer.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ASiCContainer.java index 3960a37..26f2924 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ASiCContainer.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ASiCContainer.java @@ -9,15 +9,22 @@ import at.gv.egovernment.moa.spss.MOAException; */ public interface ASiCContainer { - public void setMimeType(String mimeType); - public void addDataEntry(ASiCEntry entry) throws MOAApplicationException; - public void addSignatureEntry(ASiCEntry entry); - public void addInformationEntry(ASiCEntry entry); - - public void setIsXAdES() throws MOAException; - public void setIsCAdES() throws MOAException; - public void setIsEvidenceERS() throws MOAException; - public void setIsEvidenceXML() throws MOAException; - public void setIsTimestamped() throws MOAException; + void setMimeType(String mimeType); + + void addDataEntry(ASiCEntry entry) throws MOAApplicationException; + + void addSignatureEntry(ASiCEntry entry); + + void addInformationEntry(ASiCEntry entry); + + void setIsXAdES() throws MOAException; + + void setIsCAdES() throws MOAException; + + void setIsEvidenceERS() throws MOAException; + + void setIsEvidenceXML() throws MOAException; + + void setIsTimestamped() throws MOAException; } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ASiCExtendedFormatFactory.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ASiCExtendedFormatFactory.java index f71552b..854bf81 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ASiCExtendedFormatFactory.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ASiCExtendedFormatFactory.java @@ -1,51 +1,49 @@ package at.gv.egiz.asic.impl; -import at.gv.egiz.asic.api.ASiC; -import at.gv.egiz.asic.api.ASiCFormat; -import at.gv.egiz.asic.impl.handler.*; +import java.util.Collections; +import java.util.Iterator; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; +import at.gv.egiz.asic.api.ASiCFormat; +import at.gv.egiz.asic.impl.handler.ExtendedASiCCAdESHandler; +import at.gv.egiz.asic.impl.handler.ExtendedASiCXAdESHandler; +import at.gv.egiz.asic.impl.handler.ExtendedEvidenceERSRecordHandler; +import at.gv.egiz.asic.impl.handler.ExtendedEvidenceXMLRecordHandler; +import at.gv.egiz.asic.impl.handler.HandlerSorter; /** * Created by Andreas Fitzek on 6/15/16. */ public class ASiCExtendedFormatFactory extends ASiCBaseFormatFactory { - private static final Logger logger = LoggerFactory.getLogger(ASiCExtendedFormatFactory.class); + private static final Logger logger = LoggerFactory.getLogger(ASiCExtendedFormatFactory.class); - public ASiCExtendedFormatFactory() { - super(); - handlers.add(new ExtendedASiCCAdESHandler()); - handlers.add(new ExtendedASiCXAdESHandler()); - handlers.add(new ExtendedEvidenceERSRecordHandler()); - handlers.add(new ExtendedEvidenceXMLRecordHandler()); + public ASiCExtendedFormatFactory() { + super(); + handlers.add(new ExtendedASiCCAdESHandler()); + handlers.add(new ExtendedASiCXAdESHandler()); + handlers.add(new ExtendedEvidenceERSRecordHandler()); + handlers.add(new ExtendedEvidenceXMLRecordHandler()); - Collections.sort(handlers, new HandlerSorter()); + Collections.sort(handlers, new HandlerSorter()); - logger.debug("Handler ordering for ASiCExtendedFormatFactory"); - Iterator handlerIterator = this.handlers.iterator(); - while(handlerIterator.hasNext()) { - EntryHandler entryHandler = handlerIterator.next(); - logger.debug(" " + entryHandler.getPriority() + " " + entryHandler.getClass().getSimpleName()); - } + logger.debug("Handler ordering for ASiCExtendedFormatFactory"); + final Iterator handlerIterator = this.handlers.iterator(); + while (handlerIterator.hasNext()) { + final EntryHandler entryHandler = handlerIterator.next(); + logger.debug(" " + entryHandler.getPriority() + " " + entryHandler.getClass().getSimpleName()); } + } - @Override - protected void validate() { + @Override + protected void validate() { - } + } - @Override - public ASiCFormat factoryFormat() { - return ASiCFormat.ASiCE; - } + @Override + public ASiCFormat factoryFormat() { + return ASiCFormat.ASiCE; + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ASiCImpl.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ASiCImpl.java index 34f6343..e7cfc7e 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ASiCImpl.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ASiCImpl.java @@ -1,74 +1,75 @@ package at.gv.egiz.asic.impl; -import at.gv.egiz.asic.api.ASiC; -import at.gv.egiz.asic.api.ASiCEntry; -import at.gv.egiz.asic.api.ASiCFormat; - import java.util.ArrayList; import java.util.Collection; import java.util.List; +import at.gv.egiz.asic.api.ASiC; +import at.gv.egiz.asic.api.ASiCEntry; +import at.gv.egiz.asic.api.ASiCFormat; + /** * Created by Andreas Fitzek on 6/15/16. */ public class ASiCImpl implements ASiC { - private ASiCFormat format; - private boolean xades; - private boolean cades; + private final ASiCFormat format; + private final boolean xades; + private final boolean cades; - protected List signatureEntries = new ArrayList(); - protected Collection dataEntries = new ArrayList(); - protected List informationEntries = new ArrayList(); + protected List signatureEntries = new ArrayList<>(); + protected Collection dataEntries = new ArrayList<>(); + protected List informationEntries = new ArrayList<>(); - public ASiCImpl(ASiCFormat format, boolean xades, boolean cades, List signatureEntries, Collection collection, List informationEntries) { - this.format = format; - this.xades = xades; - this.cades = cades; - this.signatureEntries = signatureEntries; - this.dataEntries = collection; - this.informationEntries = informationEntries; - } + public ASiCImpl(ASiCFormat format, boolean xades, boolean cades, List signatureEntries, + Collection collection, List informationEntries) { + this.format = format; + this.xades = xades; + this.cades = cades; + this.signatureEntries = signatureEntries; + this.dataEntries = collection; + this.informationEntries = informationEntries; + } - @Override - public ASiCFormat getFormat() { - return format; - } + @Override + public ASiCFormat getFormat() { + return format; + } - @Override - public boolean isXAdES() { - return xades; - } + @Override + public boolean isXAdES() { + return xades; + } - @Override - public boolean isCAdES() { - return cades; - } + @Override + public boolean isCAdES() { + return cades; + } - @Override - public List getSignaturesEntries() { - return signatureEntries; - } + @Override + public List getSignaturesEntries() { + return signatureEntries; + } - @Override - public Collection getDataEntries() { - return dataEntries; - } + @Override + public Collection getDataEntries() { + return dataEntries; + } - @Override - public List getInformationEntries() { - return informationEntries; - } + @Override + public List getInformationEntries() { + return informationEntries; + } - @Override - public String toString() { - return "ASiCImpl{" + - "format=" + format + - ", xades=" + xades + - ", cades=" + cades + - ", signatureEntries=" + signatureEntries + - ", dataEntries=" + dataEntries + - ", informationEntries=" + informationEntries + - '}'; - } + @Override + public String toString() { + return "ASiCImpl{" + + "format=" + format + + ", xades=" + xades + + ", cades=" + cades + + ", signatureEntries=" + signatureEntries + + ", dataEntries=" + dataEntries + + ", informationEntries=" + informationEntries + + '}'; + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ASiCMOAVerifier.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ASiCMOAVerifier.java index 51392da..1ae32ed 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ASiCMOAVerifier.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ASiCMOAVerifier.java @@ -1,87 +1,62 @@ package at.gv.egiz.asic.impl; -import at.gv.egiz.asic.ASiCManifestType; -import at.gv.egiz.asic.DataObjectReferenceType; -import at.gv.egiz.asic.ReferenceType; -import at.gv.egiz.asic.XAdESSignaturesType; -import at.gv.egiz.asic.api.*; +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import at.gv.egiz.asic.api.ASiC; +import at.gv.egiz.asic.api.ASiCVerificationResult; +import at.gv.egiz.asic.api.ASiCVerifier; import at.gv.egiz.asic.impl.verifier.ExtendedCAdESVerifier; import at.gv.egiz.asic.impl.verifier.ExtendedXAdESVerifier; import at.gv.egiz.asic.impl.verifier.SimpleCAdESVerifier; import at.gv.egiz.asic.impl.verifier.SimpleXAdESVerifier; -import at.gv.egovernment.moa.spss.MOAApplicationException; import at.gv.egovernment.moa.spss.MOAException; -import at.gv.egovernment.moa.spss.MOARuntimeException; import at.gv.egovernment.moa.spss.MOASystemException; -import at.gv.egovernment.moa.spss.api.SPSSFactory; -import at.gv.egovernment.moa.spss.api.cmsverify.*; -import at.gv.egovernment.moa.spss.api.common.*; -import at.gv.egovernment.moa.spss.api.impl.SPSSFactoryImpl; -import at.gv.egovernment.moa.spss.api.xmlverify.SupplementProfile; -import at.gv.egovernment.moa.spss.api.xmlverify.VerifySignatureInfo; -import at.gv.egovernment.moa.spss.api.xmlverify.VerifySignatureLocation; -import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureRequest; -import at.gv.egovernment.moa.spss.server.invoke.CMSSignatureVerificationInvoker; -import at.gv.egovernment.moa.spss.server.invoke.VerifyCMSSignatureResponseBuilder; -import at.gv.egovernment.moa.spss.server.invoke.XMLSignatureVerificationInvoker; -import iaik.server.cmspdfverify.CertificateValidationResult; -import org.apache.commons.codec.binary.Hex; -import org.apache.commons.io.IOUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.xml.bind.DataBindingException; -import javax.xml.bind.JAXB; -import javax.xml.crypto.dsig.Reference; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.security.DigestInputStream; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.cert.X509Certificate; -import java.util.*; /** * Created by Andreas Fitzek on 6/15/16. */ public class ASiCMOAVerifier implements ASiCVerifier { - private static final Logger logger = LoggerFactory.getLogger(ASiCMOAVerifier.class); + private static final Logger logger = LoggerFactory.getLogger(ASiCMOAVerifier.class); - private List verifierMap = new ArrayList(); + private final List verifierMap = new ArrayList<>(); - public ASiCMOAVerifier() { - verifierMap.add(new SimpleCAdESVerifier()); - verifierMap.add(new SimpleXAdESVerifier()); - verifierMap.add(new ExtendedCAdESVerifier()); - verifierMap.add(new ExtendedXAdESVerifier()); - } + public ASiCMOAVerifier() { + verifierMap.add(new SimpleCAdESVerifier()); + verifierMap.add(new SimpleXAdESVerifier()); + verifierMap.add(new ExtendedCAdESVerifier()); + verifierMap.add(new ExtendedXAdESVerifier()); + } - @Override - public List verify(ASiC asic, String trustProfileID, Date date) throws MOAException { - List response = new ArrayList(); - boolean handled = false; + @Override + public List verify(ASiC asic, String trustProfileID, Date date) + throws MOAException { + final List response = new ArrayList<>(); + boolean handled = false; - Iterator verifierIterator = verifierMap.iterator(); + final Iterator verifierIterator = verifierMap.iterator(); - while (verifierIterator.hasNext()) { - Verifier verifier = verifierIterator.next(); - if (verifier.handles(asic)) { - verifier.verify(asic, trustProfileID, date, response); - handled = true; - break; - } - } - - if (!handled) { - logger.warn("Cannot handle ASiC: {}", asic); - throw new MOASystemException("asic.0016", null); - } + while (verifierIterator.hasNext()) { + final Verifier verifier = verifierIterator.next(); + if (verifier.handles(asic)) { + verifier.verify(asic, trustProfileID, date, response); + handled = true; + break; + } + } - return response; + if (!handled) { + logger.warn("Cannot handle ASiC: {}", asic); + throw new MOASystemException("asic.0016", null); } + return response; + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ASiCSimpleFormatFactory.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ASiCSimpleFormatFactory.java index 90b3081..f478f93 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ASiCSimpleFormatFactory.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ASiCSimpleFormatFactory.java @@ -1,54 +1,59 @@ package at.gv.egiz.asic.impl; -import at.gv.egiz.asic.api.ASiCFormat; -import at.gv.egiz.asic.impl.handler.*; -import at.gv.egovernment.moa.spss.MOAApplicationException; +import java.util.Collections; +import java.util.Iterator; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Collections; -import java.util.Iterator; +import at.gv.egiz.asic.api.ASiCFormat; +import at.gv.egiz.asic.impl.handler.HandlerSorter; +import at.gv.egiz.asic.impl.handler.SimpleASiCCAdESHandler; +import at.gv.egiz.asic.impl.handler.SimpleASiCXAdESHandler; +import at.gv.egiz.asic.impl.handler.SimpleEvidenceERSRecordHandler; +import at.gv.egiz.asic.impl.handler.SimpleEvidenceXMLRecordHandler; +import at.gv.egovernment.moa.spss.MOAApplicationException; /** * Created by Andreas Fitzek on 6/15/16. */ public class ASiCSimpleFormatFactory extends ASiCBaseFormatFactory { - private static final Logger logger = LoggerFactory.getLogger(ASiCSimpleFormatFactory.class); + private static final Logger logger = LoggerFactory.getLogger(ASiCSimpleFormatFactory.class); - public ASiCSimpleFormatFactory() { - super(); + public ASiCSimpleFormatFactory() { + super(); - handlers.add(new SimpleASiCCAdESHandler()); - handlers.add(new SimpleASiCXAdESHandler()); - handlers.add(new SimpleEvidenceXMLRecordHandler()); - handlers.add(new SimpleEvidenceERSRecordHandler()); + handlers.add(new SimpleASiCCAdESHandler()); + handlers.add(new SimpleASiCXAdESHandler()); + handlers.add(new SimpleEvidenceXMLRecordHandler()); + handlers.add(new SimpleEvidenceERSRecordHandler()); - Collections.sort(handlers, new HandlerSorter()); + Collections.sort(handlers, new HandlerSorter()); - logger.debug("Handler ordering for ASiCSimpleFormatFactory"); - Iterator handlerIterator = this.handlers.iterator(); - while(handlerIterator.hasNext()) { - EntryHandler entryHandler = handlerIterator.next(); - logger.debug(" " + entryHandler.getPriority() + " " + entryHandler.getClass().getSimpleName()); - } + logger.debug("Handler ordering for ASiCSimpleFormatFactory"); + final Iterator handlerIterator = this.handlers.iterator(); + while (handlerIterator.hasNext()) { + final EntryHandler entryHandler = handlerIterator.next(); + logger.debug(" " + entryHandler.getPriority() + " " + entryHandler.getClass().getSimpleName()); } + } - @Override - protected void validate() throws MOAApplicationException { - if(this.dataEntries.size() != 1) { - logger.warn("There can only be one data entry for ASiC signatures in simple format"); - throw new MOAApplicationException("asic.0014", null); - } - - if(this.signatureEntries.size() != 1) { - logger.warn("There can only be one signature entry for ASiC signatures in simple format"); - throw new MOAApplicationException("asic.0015", null); - } + @Override + protected void validate() throws MOAApplicationException { + if (this.dataEntries.size() != 1) { + logger.warn("There can only be one data entry for ASiC signatures in simple format"); + throw new MOAApplicationException("asic.0014", null); } - @Override - public ASiCFormat factoryFormat() { - return ASiCFormat.ASiCS; + if (this.signatureEntries.size() != 1) { + logger.warn("There can only be one signature entry for ASiC signatures in simple format"); + throw new MOAApplicationException("asic.0015", null); } + } + + @Override + public ASiCFormat factoryFormat() { + return ASiCFormat.ASiCS; + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/AsicSignedFilesContainer.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/AsicSignedFilesContainer.java index c21960d..fe88a0e 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/AsicSignedFilesContainer.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/AsicSignedFilesContainer.java @@ -2,38 +2,37 @@ package at.gv.egiz.asic.impl; public class AsicSignedFilesContainer { - private String uri = null; - private String hashAlg = null; - - - /** - * Container element with ASIC signed files information - * - * @param uri Identifier of the file - * @param hashAlg Hash algorithm that is used to hash the file - */ - public AsicSignedFilesContainer(String uri, String hashAlg) { - this.uri = uri; - this.hashAlg = hashAlg; - - } - - /** - * Get file identifier - * - * @return - */ - public String getUri() { - return uri; - } - - /** - * Get hash algorithm that is used to hash the file - * - * @return - */ - public String getHashAlg() { - return hashAlg; - } - + private String uri = null; + private String hashAlg = null; + + /** + * Container element with ASIC signed files information + * + * @param uri Identifier of the file + * @param hashAlg Hash algorithm that is used to hash the file + */ + public AsicSignedFilesContainer(String uri, String hashAlg) { + this.uri = uri; + this.hashAlg = hashAlg; + + } + + /** + * Get file identifier + * + * @return + */ + public String getUri() { + return uri; + } + + /** + * Get hash algorithm that is used to hash the file + * + * @return + */ + public String getHashAlg() { + return hashAlg; + } + } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/EntryHandler.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/EntryHandler.java index 7767b33..e5e19ed 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/EntryHandler.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/EntryHandler.java @@ -1,14 +1,15 @@ package at.gv.egiz.asic.impl; -import at.gv.egovernment.moa.spss.MOAException; - import java.io.IOException; import java.io.InputStream; +import at.gv.egovernment.moa.spss.MOAException; + /** * Created by afitzek on 6/15/16. */ public interface EntryHandler { - public int getPriority(); - public boolean handle(String entryName, InputStream is, ASiCContainer container) throws IOException, MOAException; + int getPriority(); + + boolean handle(String entryName, InputStream is, ASiCContainer container) throws IOException, MOAException; } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/Verifier.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/Verifier.java index 95a2450..29bba58 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/Verifier.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/Verifier.java @@ -1,18 +1,18 @@ package at.gv.egiz.asic.impl; +import java.util.Date; +import java.util.List; + import at.gv.egiz.asic.api.ASiC; import at.gv.egiz.asic.api.ASiCVerificationResult; import at.gv.egovernment.moa.spss.MOAException; -import java.util.Date; -import java.util.List; - /** * Created by Andreas Fitzek on 6/17/16. */ public interface Verifier { - public boolean handles(ASiC asic); + boolean handles(ASiC asic); - public void verify(ASiC asic, String trustProfileID, Date date, List response) - throws MOAException; + void verify(ASiC asic, String trustProfileID, Date date, List response) + throws MOAException; } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ZipCommentReaderStream.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ZipCommentReaderStream.java index 93b7651..dacc76e 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ZipCommentReaderStream.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/ZipCommentReaderStream.java @@ -1,7 +1,5 @@ package at.gv.egiz.asic.impl; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; @@ -10,171 +8,171 @@ import java.io.InputStream; */ public class ZipCommentReaderStream extends InputStream { - private InputStream inputStream; + private final InputStream inputStream; - private int[] tempBuffer = new int[22]; + private final int[] tempBuffer = new int[22]; - private int[] commentBuffer = null; + private int[] commentBuffer = null; - private int commentBufferContentLen = 0; - private int commentBufferContentOff = 0; + private int commentBufferContentLen = 0; + private int commentBufferContentOff = 0; - private int tempBufferContentLen = 0; - private int tempBufferContentOff = 0; + private int tempBufferContentLen = 0; + private int tempBufferContentOff = 0; - private String fileComment = null; + private String fileComment = null; - private static final byte[] directoryRecord = new byte[] { (byte)0x50, (byte)0x4b, 0x05, 0x06 }; + private static final byte[] directoryRecord = new byte[] { (byte) 0x50, (byte) 0x4b, 0x05, 0x06 }; - public ZipCommentReaderStream(InputStream inputStream) { - this.inputStream = inputStream; - } - - private int readIntIntoBuffer() throws IOException { - int tValue = this.inputStream.read(); - - if(this.tempBuffer.length <= tempBufferContentOff) { - throw new IOException("Temp Buffer is out of space! @ " + tempBufferContentOff); - } + public ZipCommentReaderStream(InputStream inputStream) { + this.inputStream = inputStream; + } - this.tempBuffer[tempBufferContentOff] = tValue; - tempBufferContentOff++; - tempBufferContentLen++; + private int readIntIntoBuffer() throws IOException { + final int tValue = this.inputStream.read(); - return tValue; + if (this.tempBuffer.length <= tempBufferContentOff) { + throw new IOException("Temp Buffer is out of space! @ " + tempBufferContentOff); } - private int readIntIntoCommentBuffer() throws IOException { - int tValue = this.inputStream.read(); + this.tempBuffer[tempBufferContentOff] = tValue; + tempBufferContentOff++; + tempBufferContentLen++; - if(this.commentBuffer.length <= commentBufferContentOff) { - throw new IOException("Comment Buffer is out of space! @ " + commentBufferContentOff); - } + return tValue; + } - this.commentBuffer[commentBufferContentOff] = tValue; - commentBufferContentOff++; - commentBufferContentLen++; + private int readIntIntoCommentBuffer() throws IOException { + final int tValue = this.inputStream.read(); - return tValue; + if (this.commentBuffer.length <= commentBufferContentOff) { + throw new IOException("Comment Buffer is out of space! @ " + commentBufferContentOff); } - private void checkMagicBytes() throws IOException { - boolean foundMagic = true; - tempBufferContentOff = 0; - tempBufferContentLen = 0; - for(int i = 1; i < directoryRecord.length; i++) { - int tValue = readIntIntoBuffer(); - if(tValue != directoryRecord[i]) { - foundMagic = false; - break; - } - if(tValue < 0) { - // Found EOF - return; - } - } + this.commentBuffer[commentBufferContentOff] = tValue; + commentBufferContentOff++; + commentBufferContentLen++; + + return tValue; + } + + private void checkMagicBytes() throws IOException { + boolean foundMagic = true; + tempBufferContentOff = 0; + tempBufferContentLen = 0; + for (int i = 1; i < directoryRecord.length; i++) { + final int tValue = readIntIntoBuffer(); + if (tValue != directoryRecord[i]) { + foundMagic = false; + break; + } + if (tValue < 0) { + // Found EOF + return; + } + } - if(foundMagic) { - // read input stream until comment length - for(int i = 0; i < 16; i++) { - int tValue = readIntIntoBuffer(); + if (foundMagic) { + // read input stream until comment length + for (int i = 0; i < 16; i++) { + final int tValue = readIntIntoBuffer(); - if(tValue < 0) { - // Found EOF - return; - } - } + if (tValue < 0) { + // Found EOF + return; + } + } - int commentlengthHigh = readIntIntoBuffer(); + final int commentlengthHigh = readIntIntoBuffer(); - if(commentlengthHigh < 0) { - // Found EOF - return; - } + if (commentlengthHigh < 0) { + // Found EOF + return; + } - int commentlengthLow = readIntIntoBuffer(); + final int commentlengthLow = readIntIntoBuffer(); - if(commentlengthLow < 0) { - // Found EOF - return; - } + if (commentlengthLow < 0) { + // Found EOF + return; + } - int commentLength = commentlengthLow * 255 + commentlengthHigh; + final int commentLength = commentlengthLow * 255 + commentlengthHigh; - if(commentLength == 0) { - return; - } + if (commentLength == 0) { + return; + } - this.commentBuffer = new int[commentLength]; + this.commentBuffer = new int[commentLength]; - commentBufferContentOff = 0; - commentBufferContentLen = 0; + commentBufferContentOff = 0; + commentBufferContentLen = 0; - // read comment buffer string - for(int i = 0; i < commentLength; i++) { - int tValue = readIntIntoCommentBuffer(); + // read comment buffer string + for (int i = 0; i < commentLength; i++) { + final int tValue = readIntIntoCommentBuffer(); - if(tValue < 0) { - // Found EOF - return; - } - } + if (tValue < 0) { + // Found EOF + return; + } + } - byte[] stringBuffer = new byte[this.commentBuffer.length]; + final byte[] stringBuffer = new byte[this.commentBuffer.length]; - for(int i = 0; i < stringBuffer.length; i++) { - stringBuffer[i] = (byte)this.commentBuffer[i]; - } + for (int i = 0; i < stringBuffer.length; i++) { + stringBuffer[i] = (byte) this.commentBuffer[i]; + } - this.fileComment = new String(stringBuffer); - } + this.fileComment = new String(stringBuffer); } + } - @Override - public int read() throws IOException { - int value = -1; - if(tempBufferContentLen > 0) { - value = this.tempBuffer[tempBufferContentOff]; - tempBufferContentOff++; + @Override + public int read() throws IOException { + int value = -1; + if (tempBufferContentLen > 0) { + value = this.tempBuffer[tempBufferContentOff]; + tempBufferContentOff++; - // reset temp buffer - if(tempBufferContentOff >= tempBufferContentLen) { - tempBufferContentOff = 0; - tempBufferContentLen = 0; - } + // reset temp buffer + if (tempBufferContentOff >= tempBufferContentLen) { + tempBufferContentOff = 0; + tempBufferContentLen = 0; + } - return value; - } + return value; + } - if(this.commentBuffer != null) { - value = this.commentBuffer[commentBufferContentOff]; + if (this.commentBuffer != null) { + value = this.commentBuffer[commentBufferContentOff]; - commentBufferContentOff++; + commentBufferContentOff++; - // reset comment buffer - if(commentBufferContentOff >= commentBufferContentLen) { - commentBufferContentOff = 0; - commentBufferContentLen = 0; - this.commentBuffer = null; - } + // reset comment buffer + if (commentBufferContentOff >= commentBufferContentLen) { + commentBufferContentOff = 0; + commentBufferContentLen = 0; + this.commentBuffer = null; + } - return value; - } - - value = this.inputStream.read(); + return value; + } - if(value == directoryRecord[0] && this.fileComment == null) { - // might have found start of magic bytes - checkMagicBytes(); - // reset buffer offsets - tempBufferContentOff = 0; - commentBufferContentOff = 0; - } + value = this.inputStream.read(); - return value; + if (value == directoryRecord[0] && this.fileComment == null) { + // might have found start of magic bytes + checkMagicBytes(); + // reset buffer offsets + tempBufferContentOff = 0; + commentBufferContentOff = 0; } - public String getFileComment() { - return this.fileComment; - } + return value; + } + + public String getFileComment() { + return this.fileComment; + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/AllDataHandler.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/AllDataHandler.java index cbf7a35..e1d95c0 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/AllDataHandler.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/AllDataHandler.java @@ -1,29 +1,30 @@ package at.gv.egiz.asic.impl.handler; +import java.io.IOException; +import java.io.InputStream; + import at.gv.egiz.asic.api.ASiCConstants; -import at.gv.egiz.asic.impl.ASiCContainer; import at.gv.egiz.asic.api.ASiCEntry; +import at.gv.egiz.asic.impl.ASiCContainer; import at.gv.egiz.asic.impl.EntryHandler; import at.gv.egovernment.moa.spss.MOAApplicationException; -import java.io.IOException; -import java.io.InputStream; - /** * Created by afitzek on 6/15/16. */ public class AllDataHandler extends BaseHandler implements EntryHandler, ASiCConstants { - @Override - public int getPriority() { - return 100; - } + @Override + public int getPriority() { + return 100; + } - @Override - public boolean handle(String entryName, InputStream is, ASiCContainer container) throws IOException, MOAApplicationException { + @Override + public boolean handle(String entryName, InputStream is, ASiCContainer container) throws IOException, + MOAApplicationException { - ASiCEntry entry = buildASiCEntry(entryName, is); - container.addDataEntry(entry); + final ASiCEntry entry = buildASiCEntry(entryName, is); + container.addDataEntry(entry); - return true; - } + return true; + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/BaseHandler.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/BaseHandler.java index 2b5ca9a..208edb4 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/BaseHandler.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/BaseHandler.java @@ -1,27 +1,28 @@ package at.gv.egiz.asic.impl.handler; -import at.gv.egiz.asic.api.ASiCConstants; -import at.gv.egiz.asic.api.ASiCEntry; -import at.gv.egiz.asic.impl.EntryHandler; -import org.apache.commons.io.IOUtils; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; +import org.apache.commons.io.IOUtils; + +import at.gv.egiz.asic.api.ASiCConstants; +import at.gv.egiz.asic.api.ASiCEntry; +import at.gv.egiz.asic.impl.EntryHandler; + /** * Created by Andreas Fitzek on 6/15/16. */ public abstract class BaseHandler implements EntryHandler, ASiCConstants { - protected ASiCEntry buildASiCEntry(String entryName, InputStream is) throws IOException { - ASiCEntry entry = new ASiCEntry(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - IOUtils.copy(is, baos); - entry.setContents(new ByteArrayInputStream(baos.toByteArray())); - entry.setEntryName(entryName); - return entry; - } + protected ASiCEntry buildASiCEntry(String entryName, InputStream is) throws IOException { + final ASiCEntry entry = new ASiCEntry(); + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + IOUtils.copy(is, baos); + entry.setContents(new ByteArrayInputStream(baos.toByteArray())); + entry.setEntryName(entryName); + return entry; + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/CAdESHandler.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/CAdESHandler.java index 3ee97fc..fef2e38 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/CAdESHandler.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/CAdESHandler.java @@ -5,16 +5,13 @@ import at.gv.egiz.asic.impl.ASiCContainer; import at.gv.egiz.asic.impl.EntryHandler; import at.gv.egovernment.moa.spss.MOAException; -import java.io.IOException; -import java.io.InputStream; - /** * Created by Andreas Fitzek on 6/15/16. */ public abstract class CAdESHandler extends SignatureHandler implements EntryHandler, ASiCConstants { - @Override - protected void setType(ASiCContainer container) throws MOAException { - container.setIsCAdES(); - } + @Override + protected void setType(ASiCContainer container) throws MOAException { + container.setIsCAdES(); + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/EvidenceERSRecordHandler.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/EvidenceERSRecordHandler.java index f89c6d0..5ba05d6 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/EvidenceERSRecordHandler.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/EvidenceERSRecordHandler.java @@ -3,16 +3,13 @@ package at.gv.egiz.asic.impl.handler; import at.gv.egiz.asic.impl.ASiCContainer; import at.gv.egovernment.moa.spss.MOAException; -import java.io.IOException; -import java.io.InputStream; - /** * Created by Andreas Fitzek on 6/17/16. */ public abstract class EvidenceERSRecordHandler extends SignatureHandler { - @Override - protected void setType(ASiCContainer container) throws MOAException { - container.setIsEvidenceERS(); - } + @Override + protected void setType(ASiCContainer container) throws MOAException { + container.setIsEvidenceERS(); + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/EvidenceXMLRecordHandler.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/EvidenceXMLRecordHandler.java index 4516bb0..932687b 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/EvidenceXMLRecordHandler.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/EvidenceXMLRecordHandler.java @@ -8,8 +8,8 @@ import at.gv.egovernment.moa.spss.MOAException; */ public abstract class EvidenceXMLRecordHandler extends SignatureHandler { - @Override - protected void setType(ASiCContainer container) throws MOAException { - container.setIsEvidenceXML(); - } + @Override + protected void setType(ASiCContainer container) throws MOAException { + container.setIsEvidenceXML(); + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/ExtendedASiCCAdESHandler.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/ExtendedASiCCAdESHandler.java index 464bcf6..6eb4d60 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/ExtendedASiCCAdESHandler.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/ExtendedASiCCAdESHandler.java @@ -1,13 +1,12 @@ package at.gv.egiz.asic.impl.handler; -import at.gv.egiz.asic.api.ASiCConstants; - /** * Created by Andreas Fitzek on 6/15/16. */ public class ExtendedASiCCAdESHandler extends CAdESHandler { - @Override - protected boolean matches(String entryName) { - return entryName.endsWith(".p7s") && entryName.startsWith(FILE_META_INF) && entryName.contains("signature"); - } + @Override + protected boolean matches(String entryName) { + return entryName.endsWith(".p7s") && entryName.startsWith(FILE_META_INF) && entryName.contains( + "signature"); + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/ExtendedASiCXAdESHandler.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/ExtendedASiCXAdESHandler.java index 971ba31..199dda1 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/ExtendedASiCXAdESHandler.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/ExtendedASiCXAdESHandler.java @@ -2,17 +2,17 @@ package at.gv.egiz.asic.impl.handler; /** * Created by Andreas Fitzek on 6/15/16. - * + * * Updated by Thomas Lenz on 02/03/17 */ public class ExtendedASiCXAdESHandler extends XAdESHandler { - @Override - protected boolean matches(String entryName) { - return entryName.endsWith(".xml") - && entryName.startsWith(FILE_META_INF) - && entryName.contains("signatures") + @Override + protected boolean matches(String entryName) { + return entryName.endsWith(".xml") + && entryName.startsWith(FILE_META_INF) + && entryName.contains("signatures") // && !entryName.contains("ASiCManifest") // && !entryName.contains("AsiCManifest") - ; - } + ; + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/ExtendedEvidenceERSRecordHandler.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/ExtendedEvidenceERSRecordHandler.java index ccf9224..ab6f2d5 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/ExtendedEvidenceERSRecordHandler.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/ExtendedEvidenceERSRecordHandler.java @@ -4,8 +4,9 @@ package at.gv.egiz.asic.impl.handler; * Created by Andreas Fitzek on 6/17/16. */ public class ExtendedEvidenceERSRecordHandler extends EvidenceERSRecordHandler { - @Override - protected boolean matches(String entryName) { - return entryName.endsWith(".ers") && entryName.startsWith(FILE_META_INF) && entryName.contains("evidencerecord"); - } + @Override + protected boolean matches(String entryName) { + return entryName.endsWith(".ers") && entryName.startsWith(FILE_META_INF) && entryName.contains( + "evidencerecord"); + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/ExtendedEvidenceXMLRecordHandler.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/ExtendedEvidenceXMLRecordHandler.java index d24d61b..ecac8b6 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/ExtendedEvidenceXMLRecordHandler.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/ExtendedEvidenceXMLRecordHandler.java @@ -4,8 +4,9 @@ package at.gv.egiz.asic.impl.handler; * Created by Andreas Fitzek on 6/17/16. */ public class ExtendedEvidenceXMLRecordHandler extends EvidenceERSRecordHandler { - @Override - protected boolean matches(String entryName) { - return entryName.endsWith(".xml") && entryName.startsWith(FILE_META_INF) && entryName.contains("evidencerecord"); - } + @Override + protected boolean matches(String entryName) { + return entryName.endsWith(".xml") && entryName.startsWith(FILE_META_INF) && entryName.contains( + "evidencerecord"); + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/HandlerSorter.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/HandlerSorter.java index 36a215d..2f753cf 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/HandlerSorter.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/HandlerSorter.java @@ -1,16 +1,16 @@ package at.gv.egiz.asic.impl.handler; -import at.gv.egiz.asic.impl.EntryHandler; - import java.util.Comparator; +import at.gv.egiz.asic.impl.EntryHandler; + /** * Created by afitzek on 6/15/16. */ public class HandlerSorter implements Comparator { - @Override - public int compare(EntryHandler o1, EntryHandler o2) { - return Integer.compare(o1.getPriority(), o2.getPriority()); - } + @Override + public int compare(EntryHandler o1, EntryHandler o2) { + return Integer.compare(o1.getPriority(), o2.getPriority()); + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/MetaInfHandler.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/MetaInfHandler.java index ec4f101..0127ea4 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/MetaInfHandler.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/MetaInfHandler.java @@ -1,33 +1,33 @@ package at.gv.egiz.asic.impl.handler; +import java.io.IOException; +import java.io.InputStream; + import at.gv.egiz.asic.api.ASiCConstants; -import at.gv.egiz.asic.impl.ASiCContainer; import at.gv.egiz.asic.api.ASiCEntry; +import at.gv.egiz.asic.impl.ASiCContainer; import at.gv.egiz.asic.impl.EntryHandler; -import java.io.IOException; -import java.io.InputStream; - /** * Created by Andreas Fitzek on 6/15/16. */ public class MetaInfHandler extends BaseHandler implements EntryHandler, ASiCConstants { - @Override - public int getPriority() { - return 20; - } + @Override + public int getPriority() { + return 20; + } - @Override - public boolean handle(String entryName, InputStream is, ASiCContainer container) throws IOException { + @Override + public boolean handle(String entryName, InputStream is, ASiCContainer container) throws IOException { - boolean metainf = entryName.startsWith(FILE_META_INF); + final boolean metainf = entryName.startsWith(FILE_META_INF); - if(metainf) { - ASiCEntry entry = buildASiCEntry(entryName, is); - container.addInformationEntry(entry); - return true; - } - - return false; + if (metainf) { + final ASiCEntry entry = buildASiCEntry(entryName, is); + container.addInformationEntry(entry); + return true; } + + return false; + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/MimefileHandler.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/MimefileHandler.java index 68fc87e..5a67fb8 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/MimefileHandler.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/MimefileHandler.java @@ -1,36 +1,37 @@ package at.gv.egiz.asic.impl.handler; +import java.io.IOException; +import java.io.InputStream; + +import org.apache.commons.io.IOUtils; + import at.gv.egiz.asic.api.ASiCConstants; import at.gv.egiz.asic.impl.ASiCContainer; import at.gv.egiz.asic.impl.EntryHandler; -import org.apache.commons.io.IOUtils; - -import java.io.IOException; -import java.io.InputStream; /** * Created by afitzek on 6/15/16. */ public class MimefileHandler implements EntryHandler, ASiCConstants { - private boolean isMimeType(String entryName) { - return FILE_MIME_TYPE.equalsIgnoreCase(entryName); - } - - @Override - public int getPriority() { - return 1; - } + private boolean isMimeType(String entryName) { + return FILE_MIME_TYPE.equalsIgnoreCase(entryName); + } - @Override - public boolean handle(String entryName, InputStream is, ASiCContainer container) throws IOException { + @Override + public int getPriority() { + return 1; + } - if(isMimeType(entryName)) { - String mimeType = IOUtils.toString(is, "UTF-8"); - container.setMimeType(mimeType); - return true; - } + @Override + public boolean handle(String entryName, InputStream is, ASiCContainer container) throws IOException { - return false; + if (isMimeType(entryName)) { + final String mimeType = IOUtils.toString(is, "UTF-8"); + container.setMimeType(mimeType); + return true; } + + return false; + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/SignatureHandler.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/SignatureHandler.java index 621c9d4..08adbe9 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/SignatureHandler.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/SignatureHandler.java @@ -1,36 +1,37 @@ package at.gv.egiz.asic.impl.handler; -import at.gv.egiz.asic.impl.ASiCContainer; -import at.gv.egovernment.moa.spss.MOAException; - import java.io.IOException; import java.io.InputStream; +import at.gv.egiz.asic.impl.ASiCContainer; +import at.gv.egovernment.moa.spss.MOAException; + /** * Created by Andreas Fitzek on 6/15/16. */ public abstract class SignatureHandler extends BaseHandler { - @Override - public int getPriority() { - return 0; - } - - protected abstract boolean matches(String entryName); + @Override + public int getPriority() { + return 0; + } - protected abstract void setType(ASiCContainer container) throws MOAException; + protected abstract boolean matches(String entryName); - @Override - public boolean handle(String entryName, InputStream is, ASiCContainer container) throws IOException, MOAException { - boolean signature = this.matches(entryName); + protected abstract void setType(ASiCContainer container) throws MOAException; - if(signature) { - this.setType(container); - container.addSignatureEntry(buildASiCEntry(entryName, is)); - return true; - } + @Override + public boolean handle(String entryName, InputStream is, ASiCContainer container) throws IOException, + MOAException { + final boolean signature = this.matches(entryName); - return false; + if (signature) { + this.setType(container); + container.addSignatureEntry(buildASiCEntry(entryName, is)); + return true; } + return false; + } + } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/SimpleASiCCAdESHandler.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/SimpleASiCCAdESHandler.java index fdeda41..b049767 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/SimpleASiCCAdESHandler.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/SimpleASiCCAdESHandler.java @@ -6,8 +6,8 @@ import at.gv.egiz.asic.api.ASiCConstants; * Created by Andreas Fitzek on 6/15/16. */ public class SimpleASiCCAdESHandler extends CAdESHandler { - @Override - protected boolean matches(String entryName) { - return (ASiCConstants.FILE_META_INF + "signature.p7s").equalsIgnoreCase(entryName); - } + @Override + protected boolean matches(String entryName) { + return (ASiCConstants.FILE_META_INF + "signature.p7s").equalsIgnoreCase(entryName); + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/SimpleASiCXAdESHandler.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/SimpleASiCXAdESHandler.java index 66a7546..8425b51 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/SimpleASiCXAdESHandler.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/SimpleASiCXAdESHandler.java @@ -6,8 +6,8 @@ import at.gv.egiz.asic.api.ASiCConstants; * Created by Andreas Fitzek on 6/15/16. */ public class SimpleASiCXAdESHandler extends XAdESHandler { - @Override - protected boolean matches(String entryName) { - return (ASiCConstants.FILE_META_INF + "signatures.xml").equalsIgnoreCase(entryName); - } + @Override + protected boolean matches(String entryName) { + return (ASiCConstants.FILE_META_INF + "signatures.xml").equalsIgnoreCase(entryName); + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/SimpleEvidenceERSRecordHandler.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/SimpleEvidenceERSRecordHandler.java index 58221f5..63a70da 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/SimpleEvidenceERSRecordHandler.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/SimpleEvidenceERSRecordHandler.java @@ -6,8 +6,8 @@ import at.gv.egiz.asic.api.ASiCConstants; * Created by Andreas Fitzek on 6/17/16. */ public class SimpleEvidenceERSRecordHandler extends EvidenceERSRecordHandler { - @Override - protected boolean matches(String entryName) { - return (ASiCConstants.FILE_META_INF + "evidencerecord.ers").equalsIgnoreCase(entryName); - } + @Override + protected boolean matches(String entryName) { + return (ASiCConstants.FILE_META_INF + "evidencerecord.ers").equalsIgnoreCase(entryName); + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/SimpleEvidenceXMLRecordHandler.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/SimpleEvidenceXMLRecordHandler.java index dacc218..db7c063 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/SimpleEvidenceXMLRecordHandler.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/SimpleEvidenceXMLRecordHandler.java @@ -6,8 +6,8 @@ import at.gv.egiz.asic.api.ASiCConstants; * Created by Andreas Fitzek on 6/17/16. */ public class SimpleEvidenceXMLRecordHandler extends EvidenceERSRecordHandler { - @Override - protected boolean matches(String entryName) { - return (ASiCConstants.FILE_META_INF + "evidencerecord.xml").equalsIgnoreCase(entryName); - } + @Override + protected boolean matches(String entryName) { + return (ASiCConstants.FILE_META_INF + "evidencerecord.xml").equalsIgnoreCase(entryName); + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/XAdESHandler.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/XAdESHandler.java index ff19759..19e37c1 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/XAdESHandler.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/handler/XAdESHandler.java @@ -10,8 +10,8 @@ import at.gv.egovernment.moa.spss.MOAException; */ public abstract class XAdESHandler extends SignatureHandler implements EntryHandler, ASiCConstants { - @Override - protected void setType(ASiCContainer container) throws MOAException { - container.setIsXAdES(); - } + @Override + protected void setType(ASiCContainer container) throws MOAException { + container.setIsXAdES(); + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/BaseVerifier.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/BaseVerifier.java index cc2d363..3060f67 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/BaseVerifier.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/BaseVerifier.java @@ -1,61 +1,61 @@ package at.gv.egiz.asic.impl.verifier; -import at.gv.egiz.asic.impl.Verifier; -import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureResponse; -import org.apache.commons.codec.binary.Hex; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; +import org.apache.commons.codec.binary.Hex; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import at.gv.egiz.asic.impl.Verifier; + /** * Created by Andreas Fitzek on 6/17/16. */ public abstract class BaseVerifier implements Verifier { - protected static Map hashTranslator = new HashMap(); - - static { - hashTranslator.put("http://www.w3.org/2000/09/xmldsig#sha1", "SHA-1"); - hashTranslator.put("http://www.w3.org/2001/04/xmldsig-more#sha224", "SHA-224"); - hashTranslator.put("http://www.w3.org/2001/04/xmlenc#sha256", "SHA-256"); - hashTranslator.put("http://www.w3.org/2001/04/xmldsig-more#sha384", "SHA-384"); - hashTranslator.put("http://www.w3.org/2001/04/xmlenc#sha512", "SHA-512"); - hashTranslator.put("http://www.w3.org/2001/04/xmlenc#ripemd160", "RIPEMD-160"); - } - - private static final Logger logger = LoggerFactory.getLogger(BaseVerifier.class); - - protected boolean compareHash(byte[] reference, byte[] calculated, String refName) { - String referenceHex = Hex.encodeHexString(reference); - String calculatedHex = Hex.encodeHexString(calculated); - if(Arrays.equals(reference, calculated)) { - logger.debug("Digest from manifest do match for {}", refName); - return true; - } else { - logger.info("Digest from manifest do not match for {}", refName); - logger.info("Digest from manifest for {} : {}", refName, referenceHex); - logger.info("Digest from calculated for {} : {}", refName, calculatedHex); - return false; - } + protected static Map hashTranslator = new HashMap<>(); + + static { + hashTranslator.put("http://www.w3.org/2000/09/xmldsig#sha1", "SHA-1"); + hashTranslator.put("http://www.w3.org/2001/04/xmldsig-more#sha224", "SHA-224"); + hashTranslator.put("http://www.w3.org/2001/04/xmlenc#sha256", "SHA-256"); + hashTranslator.put("http://www.w3.org/2001/04/xmldsig-more#sha384", "SHA-384"); + hashTranslator.put("http://www.w3.org/2001/04/xmlenc#sha512", "SHA-512"); + hashTranslator.put("http://www.w3.org/2001/04/xmlenc#ripemd160", "RIPEMD-160"); + } + + private static final Logger logger = LoggerFactory.getLogger(BaseVerifier.class); + + protected boolean compareHash(byte[] reference, byte[] calculated, String refName) { + final String referenceHex = Hex.encodeHexString(reference); + final String calculatedHex = Hex.encodeHexString(calculated); + if (Arrays.equals(reference, calculated)) { + logger.debug("Digest from manifest do match for {}", refName); + return true; + } else { + logger.info("Digest from manifest do not match for {}", refName); + logger.info("Digest from manifest for {} : {}", refName, referenceHex); + logger.info("Digest from calculated for {} : {}", refName, calculatedHex); + return false; } + } - protected MessageDigest getMessageDigestFromURI(String uri) { - try { + protected MessageDigest getMessageDigestFromURI(String uri) { + try { - String algo = hashTranslator.get(uri); + String algo = hashTranslator.get(uri); - if(algo == null) { - algo = uri; - } + if (algo == null) { + algo = uri; + } - return MessageDigest.getInstance(algo); - } catch (NoSuchAlgorithmException e) { - return null; - } + return MessageDigest.getInstance(algo); + } catch (final NoSuchAlgorithmException e) { + return null; } + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/CAdESVerifier.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/CAdESVerifier.java index 5ab677c..ac96f90 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/CAdESVerifier.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/CAdESVerifier.java @@ -1,5 +1,8 @@ package at.gv.egiz.asic.impl.verifier; +import java.io.InputStream; +import java.util.Date; + import at.gv.egiz.asic.api.ASiC; import at.gv.egovernment.moa.spss.MOAException; import at.gv.egovernment.moa.spss.api.SPSSFactory; @@ -9,35 +12,34 @@ import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureRequest; import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureResponse; import at.gv.egovernment.moa.spss.server.invoke.CMSSignatureVerificationInvoker; -import java.io.InputStream; -import java.util.Date; - /** * Created by Andreas Fitzek on 6/17/16. */ public abstract class CAdESVerifier extends BaseVerifier { - @Override - public boolean handles(ASiC asic) { - return asic.isCAdES(); - } + @Override + public boolean handles(ASiC asic) { + return asic.isCAdES(); + } - protected VerifyCMSSignatureResponse runCMSVerification(InputStream signedData, InputStream cmsSignature, - String trustProfileID, Date date) throws MOAException { - CMSContent cmsContent = SPSSFactory.getInstance().createCMSContent(signedData); - CMSDataObject cmsDataObject = SPSSFactory.getInstance().createCMSDataObject(null, cmsContent, null, null); + protected VerifyCMSSignatureResponse runCMSVerification(InputStream signedData, InputStream cmsSignature, + String trustProfileID, Date date) throws MOAException { + final CMSContent cmsContent = SPSSFactory.getInstance().createCMSContent(signedData); + final CMSDataObject cmsDataObject = SPSSFactory.getInstance().createCMSDataObject(null, cmsContent, null, + null); - VerifyCMSSignatureRequest verifyCMSSignatureRequest = - SPSSFactory.getInstance().createVerifyCMSSignatureRequest( - VerifyCMSSignatureRequest.ALL_SIGNATORIES, - date, - cmsSignature, - cmsDataObject, - trustProfileID, - false, - true); + final VerifyCMSSignatureRequest verifyCMSSignatureRequest = + SPSSFactory.getInstance().createVerifyCMSSignatureRequest( + VerifyCMSSignatureRequest.ALL_SIGNATORIES, + date, + cmsSignature, + cmsDataObject, + trustProfileID, + false, + true); - VerifyCMSSignatureResponse verifyResponse = CMSSignatureVerificationInvoker.getInstance().verifyCMSSignature( - verifyCMSSignatureRequest); - return verifyResponse; - } + final VerifyCMSSignatureResponse verifyResponse = CMSSignatureVerificationInvoker.getInstance() + .verifyCMSSignature( + verifyCMSSignatureRequest); + return verifyResponse; + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/ExtendedCAdESVerifier.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/ExtendedCAdESVerifier.java index 4dda99f..62ac1c8 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/ExtendedCAdESVerifier.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/ExtendedCAdESVerifier.java @@ -1,5 +1,19 @@ package at.gv.egiz.asic.impl.verifier; +import java.io.IOException; +import java.security.DigestInputStream; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.List; + +import javax.xml.bind.JAXB; + +import org.apache.commons.codec.binary.Hex; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import at.gv.egiz.asic.ASiCManifestType; import at.gv.egiz.asic.DataObjectReferenceType; import at.gv.egiz.asic.api.ASiC; @@ -11,162 +25,155 @@ import at.gv.egovernment.moa.spss.MOAApplicationException; import at.gv.egovernment.moa.spss.MOAException; import at.gv.egovernment.moa.spss.MOASystemException; import at.gv.egovernment.moa.spss.api.SPSSFactory; -import at.gv.egovernment.moa.spss.api.cmsverify.*; +import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureResponse; +import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureResponseElement; import at.gv.egovernment.moa.spss.api.common.CheckResult; import at.gv.egovernment.moa.spss.api.common.SignerInfo; -import at.gv.egovernment.moa.spss.server.invoke.CMSSignatureVerificationInvoker; -import org.apache.commons.codec.binary.Hex; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.xml.bind.JAXB; -import java.io.IOException; -import java.security.DigestInputStream; -import java.security.MessageDigest; -import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; -import java.util.List; /** * Created by Andreas Fitzek on 6/17/16. */ public class ExtendedCAdESVerifier extends CAdESVerifier { - private static final Logger logger = LoggerFactory.getLogger(ExtendedCAdESVerifier.class); + private static final Logger logger = LoggerFactory.getLogger(ExtendedCAdESVerifier.class); - @Override - public boolean handles(ASiC asic) { - return super.handles(asic) && ASiCFormat.ASiCE.equals(asic.getFormat()); - } + @Override + public boolean handles(ASiC asic) { + return super.handles(asic) && ASiCFormat.ASiCE.equals(asic.getFormat()); + } + + @Override + public void verify(ASiC asic, String trustProfileID, Date date, List response) + throws MOAException { + try { + final Iterator informationsIterator = asic.getInformationEntries().iterator(); - @Override - public void verify(ASiC asic, String trustProfileID, Date date, List response) throws MOAException { - try { - Iterator informationsIterator = asic.getInformationEntries().iterator(); + while (informationsIterator.hasNext()) { + final ASiCEntry informationEntry = informationsIterator.next(); + + if (informationEntry.getEntryName().startsWith("META-INF/") && informationEntry.getEntryName() + .endsWith(".xml") + && informationEntry.getEntryName().contains("ASiCManifest")) { + // Got ASiC Manifest + final ASiCManifestType asiCManifestType = JAXB.unmarshal(informationEntry.getContents(), + ASiCManifestType.class); + final String signatureName = asiCManifestType.getSigReference().getURI(); + + ASiCEntry cadesSignature = null; + + // find referenced signature + final Iterator cadesSignatureIterator = asic.getSignaturesEntries().iterator(); + + while (cadesSignatureIterator.hasNext()) { + final ASiCEntry tmpCadesSignature = cadesSignatureIterator.next(); + if (signatureName.equalsIgnoreCase(tmpCadesSignature.getEntryName())) { + cadesSignature = tmpCadesSignature; + break; + } + } - while (informationsIterator.hasNext()) { - ASiCEntry informationEntry = informationsIterator.next(); - - if (informationEntry.getEntryName().startsWith("META-INF/") && informationEntry.getEntryName().endsWith(".xml") - && informationEntry.getEntryName().contains("ASiCManifest")) { - // Got ASiC Manifest - ASiCManifestType asiCManifestType = JAXB.unmarshal(informationEntry.getContents(), ASiCManifestType.class); - String signatureName = asiCManifestType.getSigReference().getURI(); - - ASiCEntry cadesSignature = null; - - // find referenced signature - Iterator cadesSignatureIterator = asic.getSignaturesEntries().iterator(); - - while (cadesSignatureIterator.hasNext()) { - ASiCEntry tmpCadesSignature = cadesSignatureIterator.next(); - if (signatureName.equalsIgnoreCase(tmpCadesSignature.getEntryName())) { - cadesSignature = tmpCadesSignature; - break; - } - } - - if (cadesSignature == null) { - throw new MOAApplicationException("asic.0004", new Object[]{signatureName}); - } - - // verify all references - - boolean allReferencesValid = true; - List signedFiles = new ArrayList(); - Iterator dataObjectReferenceTypeIterator = asiCManifestType.getDataObjectReference().iterator(); - while (dataObjectReferenceTypeIterator.hasNext()) { - DataObjectReferenceType dataObjectReferenceType = dataObjectReferenceTypeIterator.next(); - - String mdURI = dataObjectReferenceType.getDigestMethod().getAlgorithm(); - String uri = dataObjectReferenceType.getURI(); - signedFiles.add(new AsicSignedFilesContainer(uri, mdURI)); - - Iterator dataEntryIterator = asic.getDataEntries().iterator(); - - while (dataEntryIterator.hasNext()) { - ASiCEntry dataEntry = dataEntryIterator.next(); - if (uri.equalsIgnoreCase(dataEntry.getEntryName())) { - MessageDigest md = this.getMessageDigestFromURI(mdURI); - if (md == null) { - throw new MOAApplicationException("asic.0005", new Object[]{mdURI}); - } - DigestInputStream dis = new DigestInputStream(dataEntry.getContents(), md); - byte[] buffer = new byte[8096]; - while (dis.read(buffer) > 0) ; - - if (!this.compareHash(dataObjectReferenceType.getDigestValue(), md.digest(), uri)) { - allReferencesValid = false; - } - - dataEntry.getContents().reset(); - break; - } - } - } - - if (allReferencesValid) { - logger.info("ASiCManifest {} references do match data files!", - informationEntry.getEntryName()); - } - - informationEntry.getContents().reset(); - MessageDigest md = this.getMessageDigestFromURI("SHA-256"); - DigestInputStream dis = new DigestInputStream(informationEntry.getContents(), md); - - VerifyCMSSignatureResponse verifyResponse = - this.runCMSVerification(dis, cadesSignature.getContents(), trustProfileID, date); - - dis.close(); - - String fullDigest = Hex.encodeHexString(md.digest()); - logger.debug("CMS Input data {}", fullDigest); - - if (!allReferencesValid) { - logger.warn("ASiCManifest {} References do not match data files!", - informationEntry.getEntryName()); - List responseElements = new ArrayList(); - - SignerInfo signerInfo; - - - // add SignerInfo element - Iterator responseElementIterator = verifyResponse.getResponseElements().iterator(); - while (responseElementIterator.hasNext()) { - VerifyCMSSignatureResponseElement orig = (VerifyCMSSignatureResponseElement) - responseElementIterator.next(); - - CheckResult signatureCheck; - CheckResult certificateCheck; - - // add SignatureCheck element - signatureCheck = SPSSFactory.getInstance().createCheckResult(1, null); - - // build the response element - VerifyCMSSignatureResponseElement responseElement = - SPSSFactory.getInstance().createVerifyCMSSignatureResponseElement( - orig.getSignerInfo(), - signatureCheck, - orig.getCertificateCheck(), - orig.getAdESFormResults(), - orig.getExtendedCertificateCheck(), - orig.getSignatureAlgorithm(), - null, - null); - responseElements.add(responseElement); - } - VerifyCMSSignatureResponse verifyCMSSignatureResponse = SPSSFactory.getInstance(). - createVerifyCMSSignatureResponse(responseElements); - response.add(new ASiCVerificationResult(signedFiles, verifyCMSSignatureResponse)); - continue; - } else { - response.add(new ASiCVerificationResult(signedFiles, verifyResponse)); - } + if (cadesSignature == null) { + throw new MOAApplicationException("asic.0004", new Object[] { signatureName }); + } + + // verify all references + + boolean allReferencesValid = true; + final List signedFiles = new ArrayList<>(); + final Iterator dataObjectReferenceTypeIterator = asiCManifestType + .getDataObjectReference().iterator(); + while (dataObjectReferenceTypeIterator.hasNext()) { + final DataObjectReferenceType dataObjectReferenceType = dataObjectReferenceTypeIterator.next(); + + final String mdURI = dataObjectReferenceType.getDigestMethod().getAlgorithm(); + final String uri = dataObjectReferenceType.getURI(); + signedFiles.add(new AsicSignedFilesContainer(uri, mdURI)); + + final Iterator dataEntryIterator = asic.getDataEntries().iterator(); + + while (dataEntryIterator.hasNext()) { + final ASiCEntry dataEntry = dataEntryIterator.next(); + if (uri.equalsIgnoreCase(dataEntry.getEntryName())) { + final MessageDigest md = this.getMessageDigestFromURI(mdURI); + if (md == null) { + throw new MOAApplicationException("asic.0005", new Object[] { mdURI }); } + final DigestInputStream dis = new DigestInputStream(dataEntry.getContents(), md); + final byte[] buffer = new byte[8096]; + while (dis.read(buffer) > 0) { + ; + } + + if (!this.compareHash(dataObjectReferenceType.getDigestValue(), md.digest(), uri)) { + allReferencesValid = false; + } + + dataEntry.getContents().reset(); + break; + } + } + } + + if (allReferencesValid) { + logger.info("ASiCManifest {} references do match data files!", + informationEntry.getEntryName()); + } + + informationEntry.getContents().reset(); + final MessageDigest md = this.getMessageDigestFromURI("SHA-256"); + final DigestInputStream dis = new DigestInputStream(informationEntry.getContents(), md); + + final VerifyCMSSignatureResponse verifyResponse = + this.runCMSVerification(dis, cadesSignature.getContents(), trustProfileID, date); + + dis.close(); + + final String fullDigest = Hex.encodeHexString(md.digest()); + logger.debug("CMS Input data {}", fullDigest); + + if (!allReferencesValid) { + logger.warn("ASiCManifest {} References do not match data files!", + informationEntry.getEntryName()); + final List responseElements = new ArrayList(); + + final SignerInfo signerInfo; + + // add SignerInfo element + final Iterator responseElementIterator = verifyResponse.getResponseElements().iterator(); + while (responseElementIterator.hasNext()) { + final VerifyCMSSignatureResponseElement orig = + (VerifyCMSSignatureResponseElement) responseElementIterator.next(); + + CheckResult signatureCheck; + final CheckResult certificateCheck; + + // add SignatureCheck element + signatureCheck = SPSSFactory.getInstance().createCheckResult(1, null); + + // build the response element + final VerifyCMSSignatureResponseElement responseElement = + SPSSFactory.getInstance().createVerifyCMSSignatureResponseElement( + orig.getSignerInfo(), + signatureCheck, + orig.getCertificateCheck(), + orig.getAdESFormResults(), + orig.getExtendedCertificateCheck(), + orig.getSignatureAlgorithm(), + null, + null); + responseElements.add(responseElement); } - } catch (IOException ex) { - throw new MOASystemException("asic.0003", null, ex); + final VerifyCMSSignatureResponse verifyCMSSignatureResponse = SPSSFactory.getInstance() + .createVerifyCMSSignatureResponse(responseElements); + response.add(new ASiCVerificationResult(signedFiles, verifyCMSSignatureResponse)); + continue; + } else { + response.add(new ASiCVerificationResult(signedFiles, verifyResponse)); + } } + } + } catch (final IOException ex) { + throw new MOASystemException("asic.0003", null, ex); } + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/ExtendedXAdESVerifier.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/ExtendedXAdESVerifier.java index 86918bf..565921f 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/ExtendedXAdESVerifier.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/ExtendedXAdESVerifier.java @@ -1,5 +1,30 @@ package at.gv.egiz.asic.impl.verifier; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.JAXB; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + import at.gv.egiz.asic.ReferenceType; import at.gv.egiz.asic.SignatureType; import at.gv.egiz.asic.XAdESSignaturesType; @@ -15,187 +40,187 @@ import at.gv.egovernment.moa.spss.MOASystemException; import at.gv.egovernment.moa.spss.api.SPSSFactory; import at.gv.egovernment.moa.spss.api.common.Content; import at.gv.egovernment.moa.spss.api.common.XMLDataObjectAssociation; -import at.gv.egovernment.moa.spss.api.impl.SPSSFactoryImpl; import at.gv.egovernment.moa.spss.api.xmlverify.SupplementProfile; import at.gv.egovernment.moa.spss.api.xmlverify.VerifySignatureInfo; import at.gv.egovernment.moa.spss.api.xmlverify.VerifySignatureLocation; import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureRequest; import at.gv.egovernment.moa.spss.server.invoke.XMLSignatureVerificationInvoker; import at.gv.egovernment.moaspss.util.URLEncoder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.*; -import org.xml.sax.SAXException; - -import javax.xml.bind.*; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import java.io.*; -import java.util.*; /** * Created by Andreas Fitzek on 6/17/16. */ public class ExtendedXAdESVerifier extends XAdESVerifier { - private static final Logger logger = LoggerFactory.getLogger(ExtendedXAdESVerifier.class); + private static final Logger logger = LoggerFactory.getLogger(ExtendedXAdESVerifier.class); - private void resetStream(InputStream is) { - try { - is.reset(); - } catch (IOException e) { - throw new MOARuntimeException("Failed to reset inputStream", null, e); - } + private void resetStream(InputStream is) { + try { + is.reset(); + } catch (final IOException e) { + throw new MOARuntimeException("Failed to reset inputStream", null, e); } + } - @Override - public void verify(ASiC asic, String trustProfileID, Date date, List response) throws MOAException { - try { - Iterator xadesSignatureIterator = asic.getSignaturesEntries().iterator(); + @Override + public void verify(ASiC asic, String trustProfileID, Date date, List response) + throws MOAException { + try { + final Iterator xadesSignatureIterator = asic.getSignaturesEntries().iterator(); - while (xadesSignatureIterator.hasNext()) { - ASiCEntry xadesSignature = xadesSignatureIterator.next(); + while (xadesSignatureIterator.hasNext()) { + final ASiCEntry xadesSignature = xadesSignatureIterator.next(); - List xmlSignatures = null; - //int signatureSize = 0; + List xmlSignatures = null; + // int signatureSize = 0; - - // TODO: support not only XAdESSignaturesType object 4.4.3.2 + // TODO: support not only XAdESSignaturesType object 4.4.3.2 // XAdESSignaturesType xAdESSignaturesType = JAXB.unmarshal(xadesSignature.getContents(), XAdESSignaturesType.class); - // signatureSize = xAdESSignaturesType.getSignature().size(); - - // this.resetStream(xadesSignature.getContents()); - DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); - dbFactory.setNamespaceAware(true); - //dbFactory.setValidating(true); - DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); - Document doc = dBuilder.parse(xadesSignature.getContents()); - - this.resetStream(xadesSignature.getContents()); - - org.w3c.dom.Element rootElement = doc.getDocumentElement(); - - if ("http://www.w3.org/2000/09/xmldsig#".equals(rootElement.getNamespaceURI()) && - "Signature".equals(rootElement.getTagName())) { - JAXBContext jc = JAXBContext.newInstance("at.gv.egiz.asic"); - JAXBElement xmlSignatureJaxb = jc.createUnmarshaller().unmarshal(rootElement, SignatureType.class); - SignatureType xmlSignature = xmlSignatureJaxb.getValue(); - xmlSignatures = new ArrayList(); - xmlSignatures.add(xmlSignature); - } else if ("http://uri.etsi.org/02918/v1.2.1#".equals(rootElement.getNamespaceURI()) && - "XAdESSignatures".equals(rootElement.getLocalName())) { - XAdESSignaturesType xAdESSignaturesType = JAXB.unmarshal(xadesSignature.getContents(), XAdESSignaturesType.class); - xmlSignatures = xAdESSignaturesType.getSignature(); - - //TODO: maybe add additional XAdES version - } else if ("http://uri.etsi.org/02918/v1.1.1#".equals(rootElement.getNamespaceURI()) && - "XAdESSignatures".equals(rootElement.getLocalName())) { - - logger.warn("ASiC v1.1.1 is not supported any more. MOA-SP only supports v1.2.1 (http://uri.etsi.org/02918/v1.2.1#)"); - //XAdESSignaturesType xAdESSignaturesType = JAXB.unmarshal(xadesSignature.getContents(), XAdESSignaturesType.class); - //xmlSignatures = xAdESSignaturesType.getSignature(); - - } else { - NodeList childrenNodes = rootElement.getChildNodes(); - for(int i = 0; i < childrenNodes.getLength(); i++) { - Node node = childrenNodes.item(i); - JAXBContext jc = JAXBContext.newInstance("at.gv.egiz.asic"); - xmlSignatures = new ArrayList(); - if ("http://www.w3.org/2000/09/xmldsig#".equals(node.getNamespaceURI()) && - "Signature".equals(rootElement.getTagName())) { - JAXBElement xmlSignatureJaxb = jc.createUnmarshaller().unmarshal(rootElement, SignatureType.class); - SignatureType xmlSignature = xmlSignatureJaxb.getValue(); - xmlSignatures.add(xmlSignature); - } - } - } - - - this.resetStream(xadesSignature.getContents()); - - Map namespaces = new HashMap(); - - //namespaces.put("asic", "http://uri.etsi.org/02918/v1.2.1#"); - namespaces.put("ds", "http://www.w3.org/2000/09/xmldsig#"); - - if (xmlSignatures == null || xmlSignatures.size() == 0) { - logger.info("ASiC container does not include a signature or signature format is not supported"); - throw new MOAApplicationException("asic.0016", null); - - } - - for (int i = 0; i < xmlSignatures.size(); i++) { - //NodeList nodes = (NodeList) result; - - //for(int i = 0; i < nodes.getLength(); i++) { - //Node node = nodes.item(i); - //JAXBContext jc = JAXBContext.newInstance( "at.gv.egiz.asic" ); - //JAXBElement xmlSignatureJaxb = jc.createUnmarshaller().unmarshal(node, SignatureType.class); - //SignatureType xmlSignature = xmlSignatureJaxb.getValue(); - List signedFiles = new ArrayList(); - - //Iterator it = xmlSignature.getSignedInfo().getReference().iterator(); - Iterator it = xmlSignatures.get(i).getSignedInfo().getReference().iterator(); - while (it.hasNext()) { - ReferenceType refType = it.next(); - if (!refType.getURI().startsWith("#")) { - signedFiles.add(new AsicSignedFilesContainer(refType.getURI(), refType.getDigestMethod().getAlgorithm())); - } - } - - Iterator dataEntryIterator = asic.getDataEntries().iterator(); - - Content content = SPSSFactory.getInstance().createContent(xadesSignature.getContents(), null); - - List supplementsList = new ArrayList(); - while (dataEntryIterator.hasNext()) { - ASiCEntry dataEntry = dataEntryIterator.next(); - dataEntry.getContents().reset(); - String entryName = URLEncoder.encode(dataEntry.getEntryName(), "UTF-8") - .replaceAll("\\+", "%20") - .replaceAll("\\%21", "!") - .replaceAll("\\%2F", "/") - //.replaceAll("\\%27", "'") - //.replaceAll("\\%28", "(") - //.replaceAll("\\%29", ")") - .replaceAll("\\%7E", "~"); - logger.info("Adding Entry : {}", entryName); - Content dataContent = SPSSFactory.getInstance().createContent(dataEntry.getContents(), entryName); - XMLDataObjectAssociation association = SPSSFactoryImpl.getInstance().createXMLDataObjectAssociation(null, dataContent); - SupplementProfile profile = SPSSFactoryImpl.getInstance().createSupplementProfile(association); - supplementsList.add(profile); - } - String location = "(//ds:Signature)[" + (i + 1) + "]"; - - VerifySignatureLocation verifySignatureLocation = SPSSFactory.getInstance().createVerifySignatureLocation( - location, namespaces); - - VerifySignatureInfo verifySignatureInfo = SPSSFactory.getInstance().createVerifySignatureInfo(content, verifySignatureLocation); - - VerifyXMLSignatureRequest verifyXMLSignatureRequest = SPSSFactory.getInstance().createVerifyXMLSignatureRequest( - date, verifySignatureInfo, supplementsList, null, false, trustProfileID, true); - - response.add(new ASiCVerificationResult(signedFiles, - XMLSignatureVerificationInvoker.getInstance().verifyXMLSignature(verifyXMLSignatureRequest))); - } + // signatureSize = xAdESSignaturesType.getSignature().size(); + + // this.resetStream(xadesSignature.getContents()); + final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); + dbFactory.setNamespaceAware(true); + // dbFactory.setValidating(true); + final DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); + final Document doc = dBuilder.parse(xadesSignature.getContents()); + + this.resetStream(xadesSignature.getContents()); + + final org.w3c.dom.Element rootElement = doc.getDocumentElement(); + + if ("http://www.w3.org/2000/09/xmldsig#".equals(rootElement.getNamespaceURI()) && + "Signature".equals(rootElement.getTagName())) { + final JAXBContext jc = JAXBContext.newInstance("at.gv.egiz.asic"); + final JAXBElement xmlSignatureJaxb = jc.createUnmarshaller().unmarshal(rootElement, + SignatureType.class); + final SignatureType xmlSignature = xmlSignatureJaxb.getValue(); + xmlSignatures = new ArrayList<>(); + xmlSignatures.add(xmlSignature); + } else if ("http://uri.etsi.org/02918/v1.2.1#".equals(rootElement.getNamespaceURI()) && + "XAdESSignatures".equals(rootElement.getLocalName())) { + final XAdESSignaturesType xAdESSignaturesType = JAXB.unmarshal(xadesSignature.getContents(), + XAdESSignaturesType.class); + xmlSignatures = xAdESSignaturesType.getSignature(); + + // TODO: maybe add additional XAdES version + } else if ("http://uri.etsi.org/02918/v1.1.1#".equals(rootElement.getNamespaceURI()) && + "XAdESSignatures".equals(rootElement.getLocalName())) { + + logger.warn( + "ASiC v1.1.1 is not supported any more. MOA-SP only supports v1.2.1 (http://uri.etsi.org/02918/v1.2.1#)"); + // XAdESSignaturesType xAdESSignaturesType = + // JAXB.unmarshal(xadesSignature.getContents(), XAdESSignaturesType.class); + // xmlSignatures = xAdESSignaturesType.getSignature(); + + } else { + final NodeList childrenNodes = rootElement.getChildNodes(); + for (int i = 0; i < childrenNodes.getLength(); i++) { + final Node node = childrenNodes.item(i); + final JAXBContext jc = JAXBContext.newInstance("at.gv.egiz.asic"); + xmlSignatures = new ArrayList<>(); + if ("http://www.w3.org/2000/09/xmldsig#".equals(node.getNamespaceURI()) && + "Signature".equals(rootElement.getTagName())) { + final JAXBElement xmlSignatureJaxb = jc.createUnmarshaller().unmarshal( + rootElement, SignatureType.class); + final SignatureType xmlSignature = xmlSignatureJaxb.getValue(); + xmlSignatures.add(xmlSignature); } - } catch( UnsupportedEncodingException e) { - logger.error("UTF8 encoding not supported by system. MOA will not work on this system!", e); - throw new MOARuntimeException("asic.0003", null, e); - } catch (IOException ex) { - throw new MOASystemException("asic.0003", null, ex); - } catch (ParserConfigurationException e) { - throw new MOASystemException("asic.0003", null, e); - } catch (SAXException e) { - throw new MOASystemException("asic.0003", null, e); - } catch (JAXBException e) { - throw new MOASystemException("asic.0003", null, e); + } } - } - @Override - public boolean handles(ASiC asic) { - return super.handles(asic) && ASiCFormat.ASiCE.equals(asic.getFormat()); + this.resetStream(xadesSignature.getContents()); + + final Map namespaces = new HashMap(); + + // namespaces.put("asic", "http://uri.etsi.org/02918/v1.2.1#"); + namespaces.put("ds", "http://www.w3.org/2000/09/xmldsig#"); + + if (xmlSignatures == null || xmlSignatures.size() == 0) { + logger.info("ASiC container does not include a signature or signature format is not supported"); + throw new MOAApplicationException("asic.0016", null); + + } + + for (int i = 0; i < xmlSignatures.size(); i++) { + // NodeList nodes = (NodeList) result; + + // for(int i = 0; i < nodes.getLength(); i++) { + // Node node = nodes.item(i); + // JAXBContext jc = JAXBContext.newInstance( "at.gv.egiz.asic" ); + // JAXBElement xmlSignatureJaxb = + // jc.createUnmarshaller().unmarshal(node, SignatureType.class); + // SignatureType xmlSignature = xmlSignatureJaxb.getValue(); + final List signedFiles = new ArrayList<>(); + + // Iterator it = + // xmlSignature.getSignedInfo().getReference().iterator(); + final Iterator it = xmlSignatures.get(i).getSignedInfo().getReference().iterator(); + while (it.hasNext()) { + final ReferenceType refType = it.next(); + if (!refType.getURI().startsWith("#")) { + signedFiles.add(new AsicSignedFilesContainer(refType.getURI(), refType.getDigestMethod() + .getAlgorithm())); + } + } + + final Iterator dataEntryIterator = asic.getDataEntries().iterator(); + + final Content content = SPSSFactory.getInstance().createContent(xadesSignature.getContents(), null); + + final List supplementsList = new ArrayList(); + while (dataEntryIterator.hasNext()) { + final ASiCEntry dataEntry = dataEntryIterator.next(); + dataEntry.getContents().reset(); + final String entryName = URLEncoder.encode(dataEntry.getEntryName(), "UTF-8") + .replaceAll("\\+", "%20") + .replaceAll("\\%21", "!") + .replaceAll("\\%2F", "/") + // .replaceAll("\\%27", "'") + // .replaceAll("\\%28", "(") + // .replaceAll("\\%29", ")") + .replaceAll("\\%7E", "~"); + logger.info("Adding Entry : {}", entryName); + final Content dataContent = SPSSFactory.getInstance().createContent(dataEntry.getContents(), + entryName); + final XMLDataObjectAssociation association = SPSSFactory.getInstance() + .createXMLDataObjectAssociation(null, dataContent); + final SupplementProfile profile = SPSSFactory.getInstance().createSupplementProfile(association); + supplementsList.add(profile); + } + final String location = "(//ds:Signature)[" + (i + 1) + "]"; + + final VerifySignatureLocation verifySignatureLocation = SPSSFactory.getInstance() + .createVerifySignatureLocation( + location, namespaces); + + final VerifySignatureInfo verifySignatureInfo = SPSSFactory.getInstance().createVerifySignatureInfo( + content, verifySignatureLocation); + + final VerifyXMLSignatureRequest verifyXMLSignatureRequest = SPSSFactory.getInstance() + .createVerifyXMLSignatureRequest( + date, verifySignatureInfo, supplementsList, null, false, trustProfileID, true); + + response.add(new ASiCVerificationResult(signedFiles, + XMLSignatureVerificationInvoker.getInstance().verifyXMLSignature(verifyXMLSignatureRequest))); + } + } + } catch (final UnsupportedEncodingException e) { + logger.error("UTF8 encoding not supported by system. MOA will not work on this system!", e); + throw new MOARuntimeException("asic.0003", null, e); + } catch (final IOException ex) { + throw new MOASystemException("asic.0003", null, ex); + } catch (final ParserConfigurationException e) { + throw new MOASystemException("asic.0003", null, e); + } catch (final SAXException e) { + throw new MOASystemException("asic.0003", null, e); + } catch (final JAXBException e) { + throw new MOASystemException("asic.0003", null, e); } + } + + @Override + public boolean handles(ASiC asic) { + return super.handles(asic) && ASiCFormat.ASiCE.equals(asic.getFormat()); + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/SimpleCAdESVerifier.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/SimpleCAdESVerifier.java index f1756fa..5af344a 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/SimpleCAdESVerifier.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/SimpleCAdESVerifier.java @@ -1,47 +1,42 @@ package at.gv.egiz.asic.impl.verifier; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + import at.gv.egiz.asic.api.ASiC; import at.gv.egiz.asic.api.ASiCEntry; import at.gv.egiz.asic.api.ASiCFormat; import at.gv.egiz.asic.api.ASiCVerificationResult; import at.gv.egiz.asic.impl.AsicSignedFilesContainer; import at.gv.egovernment.moa.spss.MOAException; -import at.gv.egovernment.moa.spss.api.SPSSFactory; -import at.gv.egovernment.moa.spss.api.cmsverify.CMSContent; -import at.gv.egovernment.moa.spss.api.cmsverify.CMSDataObject; -import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureRequest; import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureResponse; -import at.gv.egovernment.moa.spss.server.invoke.CMSSignatureVerificationInvoker; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; /** * Created by Andreas Fitzek on 6/17/16. */ public class SimpleCAdESVerifier extends CAdESVerifier { - @Override - public boolean handles(ASiC asic) { - return super.handles(asic) && ASiCFormat.ASiCS.equals(asic.getFormat()); - } + @Override + public boolean handles(ASiC asic) { + return super.handles(asic) && ASiCFormat.ASiCS.equals(asic.getFormat()); + } - @Override - public void verify(ASiC asic, String trustProfileID, Date date, List response) throws MOAException { - ASiCEntry cadesSignature = asic.getSignaturesEntries().get(0); + @Override + public void verify(ASiC asic, String trustProfileID, Date date, List response) + throws MOAException { + final ASiCEntry cadesSignature = asic.getSignaturesEntries().get(0); - //get first element - ASiCEntry dataEntry = asic.getDataEntries().iterator().next(); + // get first element + final ASiCEntry dataEntry = asic.getDataEntries().iterator().next(); - List signedFiles = new ArrayList(); - signedFiles.add(new AsicSignedFilesContainer(dataEntry.getEntryName(), null)); + final List signedFiles = new ArrayList<>(); + signedFiles.add(new AsicSignedFilesContainer(dataEntry.getEntryName(), null)); - VerifyCMSSignatureResponse verifyResponse = - this.runCMSVerification(dataEntry.getContents(), cadesSignature.getContents(), trustProfileID, date); - - response.add(new ASiCVerificationResult(signedFiles, - verifyResponse)); - } + final VerifyCMSSignatureResponse verifyResponse = + this.runCMSVerification(dataEntry.getContents(), cadesSignature.getContents(), trustProfileID, date); + response.add(new ASiCVerificationResult(signedFiles, + verifyResponse)); + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/SimpleXAdESVerifier.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/SimpleXAdESVerifier.java index b378d5b..bc418e2 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/SimpleXAdESVerifier.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/SimpleXAdESVerifier.java @@ -1,5 +1,19 @@ package at.gv.egiz.asic.impl.verifier; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.JAXB; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import at.gv.egiz.asic.ReferenceType; import at.gv.egiz.asic.XAdESSignaturesType; import at.gv.egiz.asic.api.ASiC; @@ -13,117 +27,116 @@ import at.gv.egovernment.moa.spss.MOARuntimeException; import at.gv.egovernment.moa.spss.api.SPSSFactory; import at.gv.egovernment.moa.spss.api.common.Content; import at.gv.egovernment.moa.spss.api.common.XMLDataObjectAssociation; -import at.gv.egovernment.moa.spss.api.impl.SPSSFactoryImpl; import at.gv.egovernment.moa.spss.api.xmlverify.SupplementProfile; import at.gv.egovernment.moa.spss.api.xmlverify.VerifySignatureInfo; import at.gv.egovernment.moa.spss.api.xmlverify.VerifySignatureLocation; import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureRequest; import at.gv.egovernment.moa.spss.server.invoke.XMLSignatureVerificationInvoker; import at.gv.egovernment.moaspss.util.URLEncoder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.xml.bind.JAXB; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.util.*; /** * Created by Andreas Fitzek on 6/17/16. */ public class SimpleXAdESVerifier extends XAdESVerifier { - private static final Logger logger = LoggerFactory.getLogger(SimpleXAdESVerifier.class); - - - @Override - public void verify(ASiC asic, String trustProfileID, Date date, List response) throws MOAException { - // XAdES - try { - ASiCEntry xadesSignature = asic.getSignaturesEntries().get(0); - - XAdESSignaturesType xAdESSignaturesType = null; - try { - xAdESSignaturesType = JAXB.unmarshal(xadesSignature.getContents(), XAdESSignaturesType.class); - } catch (Throwable ex) { - logger.warn("Failed to process xml signature: ex"); - throw new MOAApplicationException("asic.0003", null, ex); - } - - if (xAdESSignaturesType == null) { - throw new MOAApplicationException("asic.0003", null); - } - - int signatureSize = xAdESSignaturesType.getSignature().size(); - - try { - xadesSignature.getContents().reset(); - } catch (IOException e) { - throw new MOARuntimeException("asic.0003", null, e); - } - Map namespaces = new HashMap(); - - namespaces.put("asic", "http://uri.etsi.org/02918/v1.2.1#"); - namespaces.put("ds", "http://www.w3.org/2000/09/xmldsig#"); - - for (int i = 0; i < signatureSize; i++) { - - List signedFiles = new ArrayList(); - - Iterator it = xAdESSignaturesType.getSignature().get(i).getSignedInfo().getReference().iterator(); - while (it.hasNext()) { - ReferenceType refType = it.next(); - if (!refType.getURI().startsWith("#")) { - signedFiles.add(new AsicSignedFilesContainer(refType.getURI(), refType.getDigestMethod().getAlgorithm())); - } - } - - boolean addAll = signedFiles.isEmpty() && asic.getDataEntries().size() == 1; - - Iterator dataEntryIterator = asic.getDataEntries().iterator(); - - Content content = SPSSFactory.getInstance().createContent(xadesSignature.getContents(), null); - List supplementsList = new ArrayList(); - while (dataEntryIterator.hasNext()) { - ASiCEntry dataEntry = dataEntryIterator.next(); - String uriName = URLEncoder.encode(dataEntry.getEntryName(), "UTF-8") - .replaceAll("\\+", "%20") - .replaceAll("\\%21", "!") - .replaceAll("\\%27", "'") - //.replaceAll("\\%28", "(") - //.replaceAll("\\%29", ")") - .replaceAll("\\%7E", "~"); - - Content dataContent = SPSSFactory.getInstance().createContent(dataEntry.getContents(), uriName); - XMLDataObjectAssociation association = SPSSFactoryImpl.getInstance().createXMLDataObjectAssociation(null, dataContent); - SupplementProfile profile = SPSSFactoryImpl.getInstance().createSupplementProfile(association); - supplementsList.add(profile); - - if (addAll) { - signedFiles.add(new AsicSignedFilesContainer(dataEntry.getEntryName(), null)); - } - } - String location = "(//ds:Signature)[" + (i + 1) + "]"; - - VerifySignatureLocation verifySignatureLocation = SPSSFactory.getInstance().createVerifySignatureLocation( - location, namespaces); - - VerifySignatureInfo verifySignatureInfo = SPSSFactory.getInstance().createVerifySignatureInfo(content, verifySignatureLocation); - - VerifyXMLSignatureRequest verifyXMLSignatureRequest = SPSSFactory.getInstance().createVerifyXMLSignatureRequest( - date, verifySignatureInfo, supplementsList, null, false, trustProfileID, true); - - response.add(new ASiCVerificationResult(signedFiles, - XMLSignatureVerificationInvoker.getInstance().verifyXMLSignature(verifyXMLSignatureRequest))); - } - } catch(UnsupportedEncodingException e) { - logger.error("UTF8 encoding not supported by system. MOA will not work on this system!", e); - throw new MOARuntimeException("asic.0003", null, e); + private static final Logger logger = LoggerFactory.getLogger(SimpleXAdESVerifier.class); + + @Override + public void verify(ASiC asic, String trustProfileID, Date date, List response) + throws MOAException { + // XAdES + try { + final ASiCEntry xadesSignature = asic.getSignaturesEntries().get(0); + + XAdESSignaturesType xAdESSignaturesType = null; + try { + xAdESSignaturesType = JAXB.unmarshal(xadesSignature.getContents(), XAdESSignaturesType.class); + } catch (final Throwable ex) { + logger.warn("Failed to process xml signature: ex"); + throw new MOAApplicationException("asic.0003", null, ex); + } + + if (xAdESSignaturesType == null) { + throw new MOAApplicationException("asic.0003", null); + } + + final int signatureSize = xAdESSignaturesType.getSignature().size(); + + try { + xadesSignature.getContents().reset(); + } catch (final IOException e) { + throw new MOARuntimeException("asic.0003", null, e); + } + final Map namespaces = new HashMap(); + + namespaces.put("asic", "http://uri.etsi.org/02918/v1.2.1#"); + namespaces.put("ds", "http://www.w3.org/2000/09/xmldsig#"); + + for (int i = 0; i < signatureSize; i++) { + + final List signedFiles = new ArrayList<>(); + + final Iterator it = xAdESSignaturesType.getSignature().get(i).getSignedInfo() + .getReference().iterator(); + while (it.hasNext()) { + final ReferenceType refType = it.next(); + if (!refType.getURI().startsWith("#")) { + signedFiles.add(new AsicSignedFilesContainer(refType.getURI(), refType.getDigestMethod() + .getAlgorithm())); + } } - } - @Override - public boolean handles(ASiC asic) { - return super.handles(asic) && ASiCFormat.ASiCS.equals(asic.getFormat()); + final boolean addAll = signedFiles.isEmpty() && asic.getDataEntries().size() == 1; + + final Iterator dataEntryIterator = asic.getDataEntries().iterator(); + + final Content content = SPSSFactory.getInstance().createContent(xadesSignature.getContents(), null); + final List supplementsList = new ArrayList(); + while (dataEntryIterator.hasNext()) { + final ASiCEntry dataEntry = dataEntryIterator.next(); + final String uriName = URLEncoder.encode(dataEntry.getEntryName(), "UTF-8") + .replaceAll("\\+", "%20") + .replaceAll("\\%21", "!") + .replaceAll("\\%27", "'") + // .replaceAll("\\%28", "(") + // .replaceAll("\\%29", ")") + .replaceAll("\\%7E", "~"); + + final Content dataContent = SPSSFactory.getInstance().createContent(dataEntry.getContents(), + uriName); + final XMLDataObjectAssociation association = SPSSFactory.getInstance() + .createXMLDataObjectAssociation(null, dataContent); + final SupplementProfile profile = SPSSFactory.getInstance().createSupplementProfile(association); + supplementsList.add(profile); + + if (addAll) { + signedFiles.add(new AsicSignedFilesContainer(dataEntry.getEntryName(), null)); + } + } + final String location = "(//ds:Signature)[" + (i + 1) + "]"; + + final VerifySignatureLocation verifySignatureLocation = SPSSFactory.getInstance() + .createVerifySignatureLocation( + location, namespaces); + + final VerifySignatureInfo verifySignatureInfo = SPSSFactory.getInstance().createVerifySignatureInfo( + content, verifySignatureLocation); + + final VerifyXMLSignatureRequest verifyXMLSignatureRequest = SPSSFactory.getInstance() + .createVerifyXMLSignatureRequest( + date, verifySignatureInfo, supplementsList, null, false, trustProfileID, true); + + response.add(new ASiCVerificationResult(signedFiles, + XMLSignatureVerificationInvoker.getInstance().verifyXMLSignature(verifyXMLSignatureRequest))); + } + } catch (final UnsupportedEncodingException e) { + logger.error("UTF8 encoding not supported by system. MOA will not work on this system!", e); + throw new MOARuntimeException("asic.0003", null, e); } + } + + @Override + public boolean handles(ASiC asic) { + return super.handles(asic) && ASiCFormat.ASiCS.equals(asic.getFormat()); + } } \ No newline at end of file diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/XAdESVerifier.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/XAdESVerifier.java index 904ad4e..2074464 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/XAdESVerifier.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/impl/verifier/XAdESVerifier.java @@ -1,54 +1,54 @@ package at.gv.egiz.asic.impl.verifier; +import java.io.InputStream; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import at.gv.egiz.asic.api.ASiC; -import at.gv.egiz.asic.api.ASiCEntry; -import at.gv.egiz.asic.api.ASiCVerificationResult; import at.gv.egovernment.moa.spss.MOAException; import at.gv.egovernment.moa.spss.api.SPSSFactory; -import at.gv.egovernment.moa.spss.api.cmsverify.CMSContent; -import at.gv.egovernment.moa.spss.api.cmsverify.CMSDataObject; -import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureRequest; -import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureResponse; import at.gv.egovernment.moa.spss.api.common.Content; -import at.gv.egovernment.moa.spss.api.common.XMLDataObjectAssociation; -import at.gv.egovernment.moa.spss.api.impl.SPSSFactoryImpl; -import at.gv.egovernment.moa.spss.api.xmlverify.*; -import at.gv.egovernment.moa.spss.server.invoke.CMSSignatureVerificationInvoker; +import at.gv.egovernment.moa.spss.api.xmlverify.VerifySignatureInfo; +import at.gv.egovernment.moa.spss.api.xmlverify.VerifySignatureLocation; +import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureRequest; +import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureResponse; import at.gv.egovernment.moa.spss.server.invoke.XMLSignatureVerificationInvoker; -import java.io.InputStream; -import java.util.*; - /** * Created by Andreas Fitzek on 6/17/16. */ public abstract class XAdESVerifier extends BaseVerifier { - @Override - public boolean handles(ASiC asic) { - return asic.isXAdES(); - } + @Override + public boolean handles(ASiC asic) { + return asic.isXAdES(); + } - protected VerifyXMLSignatureResponse runXMLVerification(InputStream signedData, InputStream xmlSignature, - String trustProfileID, Date date, List supplementsList, - String location, Map namespaces) throws MOAException { + protected VerifyXMLSignatureResponse runXMLVerification(InputStream signedData, InputStream xmlSignature, + String trustProfileID, Date date, List supplementsList, + String location, Map namespaces) throws MOAException { - if(namespaces == null) { - namespaces = new HashMap(); + if (namespaces == null) { + namespaces = new HashMap(); - namespaces.put("asic", "http://uri.etsi.org/02918/v1.2.1#"); - namespaces.put("ds", "http://www.w3.org/2000/09/xmldsig#"); - } + namespaces.put("asic", "http://uri.etsi.org/02918/v1.2.1#"); + namespaces.put("ds", "http://www.w3.org/2000/09/xmldsig#"); + } - Content content = SPSSFactory.getInstance().createContent(xmlSignature, null); + final Content content = SPSSFactory.getInstance().createContent(xmlSignature, null); - VerifySignatureLocation verifySignatureLocation = SPSSFactory.getInstance().createVerifySignatureLocation( - location, namespaces); + final VerifySignatureLocation verifySignatureLocation = SPSSFactory.getInstance() + .createVerifySignatureLocation( + location, namespaces); - VerifySignatureInfo verifySignatureInfo = SPSSFactory.getInstance().createVerifySignatureInfo(content, verifySignatureLocation); + final VerifySignatureInfo verifySignatureInfo = SPSSFactory.getInstance().createVerifySignatureInfo( + content, verifySignatureLocation); - VerifyXMLSignatureRequest verifyXMLSignatureRequest = SPSSFactory.getInstance().createVerifyXMLSignatureRequest( - date, verifySignatureInfo, supplementsList, null, false, trustProfileID, true); + final VerifyXMLSignatureRequest verifyXMLSignatureRequest = SPSSFactory.getInstance() + .createVerifyXMLSignatureRequest( + date, verifySignatureInfo, supplementsList, null, false, trustProfileID, true); - return XMLSignatureVerificationInvoker.getInstance().verifyXMLSignature(verifyXMLSignatureRequest); - } + return XMLSignatureVerificationInvoker.getInstance().verifyXMLSignature(verifyXMLSignatureRequest); + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/xmlbind/VerifyASICSignatureRequestParser.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/xmlbind/VerifyASICSignatureRequestParser.java index c06e30e..b152b6d 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/xmlbind/VerifyASICSignatureRequestParser.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/xmlbind/VerifyASICSignatureRequestParser.java @@ -21,31 +21,25 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egiz.asic.xmlbind; +import java.io.InputStream; +import java.util.Date; + +import org.w3c.dom.Element; + import at.gv.egiz.asic.api.ASiCFormat; import at.gv.egovernment.moa.spss.MOAApplicationException; import at.gv.egovernment.moa.spss.api.SPSSFactory; -import at.gv.egovernment.moa.spss.api.cmsverify.CMSContent; -import at.gv.egovernment.moa.spss.api.cmsverify.CMSDataObject; -import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureRequest; -import at.gv.egovernment.moa.spss.api.common.MetaInfo; import at.gv.egovernment.moa.spss.api.xmlbind.RequestParserUtils; -import at.gv.egovernment.moaspss.util.*; -import org.w3c.dom.Element; - -import java.io.InputStream; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.StringTokenizer; +import at.gv.egovernment.moaspss.util.Base64Utils; +import at.gv.egovernment.moaspss.util.Constants; +import at.gv.egovernment.moaspss.util.XPathUtils; /** * A parser to parse VerifyCMSSignatureRequest DOM trees into * VerifyCMSSignatureRequest API objects. - * + * * @author Patrick Peck * @version $Id$ */ @@ -61,48 +55,47 @@ public class VerifyASICSignatureRequestParser { private static final String ASIC_EXTENSION_XPATH = MOA + "ASICExtension"; private static final String TRUST_PROFILE_ID_XPATH = MOA + "TrustProfileID"; - /** The SPSSFactory for creating new API objects. */ - private SPSSFactory factory = SPSSFactory.getInstance(); + private final SPSSFactory factory = SPSSFactory.getInstance(); /** - * Parse a VerifyCMSSignatureRequest DOM element, as defined - * by the MOA schema. - * + * Parse a VerifyCMSSignatureRequest DOM element, as defined by the + * MOA schema. + * * @param requestElem The VerifyCMSSignatureRequest to parse. The - * request must have been successfully parsed against the schema for this - * method to succeed. - * @return A VerifyCMSSignatureRequest API objects containing - * the data from the DOM element. + * request must have been successfully parsed against the + * schema for this method to succeed. + * @return A VerifyCMSSignatureRequest API objects containing the + * data from the DOM element. * @throws MOAApplicationException An error occurred parsing the request. */ public VerifyASiCRequest parseASIC(Element requestElem) - throws MOAApplicationException { - Date dateTime = - RequestParserUtils.parseDateTime(requestElem, DATE_TIME_XPATH); + throws MOAApplicationException { + final Date dateTime = + RequestParserUtils.parseDateTime(requestElem, DATE_TIME_XPATH); + + final boolean extendedValidation = + RequestParserUtils.parseExtendedValidation(requestElem, EXTENDED_VALIDATION_XPATH, false); - boolean extendedValidation = - RequestParserUtils.parseExtendedValidation(requestElem, EXTENDED_VALIDATION_XPATH, false); - - String asicSignatureStr = - XPathUtils.getElementValue(requestElem, ASIC_SIGNATURE_XPATH, ""); + final String asicSignatureStr = + XPathUtils.getElementValue(requestElem, ASIC_SIGNATURE_XPATH, ""); - String asicExtensionStr = - XPathUtils.getElementValue(requestElem, ASIC_EXTENSION_XPATH, ""); + final String asicExtensionStr = + XPathUtils.getElementValue(requestElem, ASIC_EXTENSION_XPATH, ""); - String trustProfileID = - XPathUtils.getElementValue(requestElem, TRUST_PROFILE_ID_XPATH, null); - //Logger.info("CMSSignature: " + cmsSignatureStr); - InputStream asicSignature = - Base64Utils.decodeToStream(asicSignatureStr, true); + final String trustProfileID = + XPathUtils.getElementValue(requestElem, TRUST_PROFILE_ID_XPATH, null); + // Logger.info("CMSSignature: " + cmsSignatureStr); + final InputStream asicSignature = + Base64Utils.decodeToStream(asicSignatureStr, true); ASiCFormat format = null; - if("asics".equalsIgnoreCase(asicExtensionStr) || "scs".equalsIgnoreCase(asicExtensionStr) - || "application/vnd.etsi.asic-s+zip".equalsIgnoreCase(asicExtensionStr)) { + if ("asics".equalsIgnoreCase(asicExtensionStr) || "scs".equalsIgnoreCase(asicExtensionStr) + || "application/vnd.etsi.asic-s+zip".equalsIgnoreCase(asicExtensionStr)) { format = ASiCFormat.ASiCS; - } else if("asice".equalsIgnoreCase(asicExtensionStr) || "sce".equalsIgnoreCase(asicExtensionStr) - || "application/vnd.etsi.asic-e+zip".equalsIgnoreCase(asicExtensionStr)) { + } else if ("asice".equalsIgnoreCase(asicExtensionStr) || "sce".equalsIgnoreCase(asicExtensionStr) + || "application/vnd.etsi.asic-e+zip".equalsIgnoreCase(asicExtensionStr)) { format = ASiCFormat.ASiCE; } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/xmlbind/VerifyASICSignatureResponseBuilder.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/xmlbind/VerifyASICSignatureResponseBuilder.java index 67d8b05..34744ef 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/xmlbind/VerifyASICSignatureResponseBuilder.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/xmlbind/VerifyASICSignatureResponseBuilder.java @@ -21,168 +21,172 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egiz.asic.xmlbind; +import java.util.Iterator; +import java.util.List; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; + import at.gv.egiz.asic.api.ASiCVerificationResult; import at.gv.egiz.asic.impl.AsicSignedFilesContainer; import at.gv.egovernment.moa.spss.MOAApplicationException; import at.gv.egovernment.moa.spss.MOAException; import at.gv.egovernment.moa.spss.MOASystemException; -import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureResponse; import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureResponseElement; import at.gv.egovernment.moa.spss.api.common.CheckResult; import at.gv.egovernment.moa.spss.api.common.SignerInfo; import at.gv.egovernment.moa.spss.api.xmlbind.ResponseBuilderUtils; +import at.gv.egovernment.moa.spss.api.xmlbind.VerifyCMSSignatureResponseBuilder; import at.gv.egovernment.moa.spss.api.xmlbind.VerifyXMLSignatureResponseBuilder; import at.gv.egovernment.moa.spss.api.xmlverify.AdESFormResults; -import at.gv.egovernment.moa.spss.api.xmlbind.VerifyCMSSignatureResponseBuilder; import at.gv.egovernment.moaspss.util.Constants; import at.gv.egovernment.moaspss.util.MiscUtil; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import java.util.Iterator; -import java.util.List; - /** - * Convert a VerifyCMSSignatureResponse API object into its - * XML representation, according to the MOA XML schema. - * + * Convert a VerifyCMSSignatureResponse API object into its XML + * representation, according to the MOA XML schema. + * * @author Patrick Peck * @version $Id$ */ public class VerifyASICSignatureResponseBuilder { /** The XML document containing the response element. */ - private Document responseDoc; + private final Document responseDoc; /** The response VerifyCMSSignatureResponse DOM element. */ - private Element responseElem; + private final Element responseElem; /** * Create a new VerifyCMSSignatureResponseBuilder: * - * @throws MOASystemException An error occurred setting up the resulting - * XML document. + * @throws MOASystemException An error occurred setting up the resulting XML + * document. */ public VerifyASICSignatureResponseBuilder() throws MOASystemException { responseDoc = - ResponseBuilderUtils.createResponse("VerifyASICSignatureResponse"); + ResponseBuilderUtils.createResponse("VerifyASICSignatureResponse"); responseElem = responseDoc.getDocumentElement(); } - + /** - * Build a document containing a VerifyCMSSignatureResponse - * DOM element being the XML representation of the given + * Build a document containing a VerifyCMSSignatureResponse DOM + * element being the XML representation of the given * VerifyCMSSignatureResponse API object. - * - * @param response The VerifyCMSSignatureResponse to convert - * to XML. - * @return A document containing the VerifyCMSSignatureResponse - * DOM element. + * + * @param response The VerifyCMSSignatureResponse to convert to + * XML. + * @return A document containing the VerifyCMSSignatureResponse DOM + * element. * @throws MOAApplicationException An error occurred building the response. */ public Document build(List results) - throws MOAException { + throws MOAException { - Iterator iter = results.iterator(); + final Iterator iter = results.iterator(); - while(iter.hasNext()) { - ASiCVerificationResult aSiCVerificationResult = iter.next(); - addASiCResultElement(aSiCVerificationResult); + while (iter.hasNext()) { + final ASiCVerificationResult aSiCVerificationResult = iter.next(); + addASiCResultElement(aSiCVerificationResult); } - + return responseDoc; } - private void addASiCResultElement(ASiCVerificationResult aSiCVerificationResult) - throws MOAException { - Element asiCSignatureResultElem = responseDoc.createElementNS(Constants.MOA_NS_URI, "ASiCSignatureResult"); - - Iterator signedFiles = aSiCVerificationResult.getSignedFiles().iterator(); - while (signedFiles.hasNext()) { - AsicSignedFilesContainer signedFile = signedFiles.next(); - Element signedFilesElem = responseDoc.createElementNS(Constants.MOA_NS_URI, "signedFiles"); - signedFilesElem.setTextContent(signedFile.getUri()); - if (MiscUtil.isNotEmpty(signedFile.getHashAlg())) - signedFilesElem.setAttribute("hashAlgorithm", signedFile.getHashAlg()); - - asiCSignatureResultElem.appendChild(signedFilesElem); - } - - if(aSiCVerificationResult.getXmlResult() != null) { - VerifyXMLSignatureResponseBuilder verifyXMLSignatureResponseBuilder = new VerifyXMLSignatureResponseBuilder(this.responseDoc, "XMLSignatureResult", true); - asiCSignatureResultElem.appendChild(verifyXMLSignatureResponseBuilder.buildElement(aSiCVerificationResult.getXmlResult())); - } else if(aSiCVerificationResult.getCmsResult() != null) { - VerifyCMSSignatureResponseBuilder verifyCMSSignatureResponseBuilder = new VerifyCMSSignatureResponseBuilder(this.responseDoc, "CMSSignatureResult", true); - asiCSignatureResultElem.appendChild(verifyCMSSignatureResponseBuilder.buildElement(aSiCVerificationResult.getCmsResult())); - } - - responseElem.appendChild(asiCSignatureResultElem); + private void addASiCResultElement(ASiCVerificationResult aSiCVerificationResult) + throws MOAException { + final Element asiCSignatureResultElem = responseDoc.createElementNS(Constants.MOA_NS_URI, + "ASiCSignatureResult"); + + final Iterator signedFiles = aSiCVerificationResult.getSignedFiles().iterator(); + while (signedFiles.hasNext()) { + final AsicSignedFilesContainer signedFile = signedFiles.next(); + final Element signedFilesElem = responseDoc.createElementNS(Constants.MOA_NS_URI, "signedFiles"); + signedFilesElem.setTextContent(signedFile.getUri()); + if (MiscUtil.isNotEmpty(signedFile.getHashAlg())) { + signedFilesElem.setAttribute("hashAlgorithm", signedFile.getHashAlg()); + } + + asiCSignatureResultElem.appendChild(signedFilesElem); + } + + if (aSiCVerificationResult.getXmlResult() != null) { + final VerifyXMLSignatureResponseBuilder verifyXMLSignatureResponseBuilder = + new VerifyXMLSignatureResponseBuilder(this.responseDoc, "XMLSignatureResult", true); + asiCSignatureResultElem.appendChild(verifyXMLSignatureResponseBuilder.buildElement( + aSiCVerificationResult.getXmlResult())); + } else if (aSiCVerificationResult.getCmsResult() != null) { + final VerifyCMSSignatureResponseBuilder verifyCMSSignatureResponseBuilder = + new VerifyCMSSignatureResponseBuilder(this.responseDoc, "CMSSignatureResult", true); + asiCSignatureResultElem.appendChild(verifyCMSSignatureResponseBuilder.buildElement( + aSiCVerificationResult.getCmsResult())); } + responseElem.appendChild(asiCSignatureResultElem); + } + /** * Add an element to the response. - * + * * @param responseElement The element to add to the response. * @throws MOAApplicationException An error occurred adding the element. */ private void addResponseElement(VerifyCMSSignatureResponseElement responseElement) - throws MOAApplicationException { + throws MOAApplicationException { + + final SignerInfo signerInfo = responseElement.getSignerInfo(); + final CheckResult signatureCheck = responseElement.getSignatureCheck(); + final CheckResult certCheck = responseElement.getCertificateCheck(); - SignerInfo signerInfo = responseElement.getSignerInfo(); - CheckResult signatureCheck = responseElement.getSignatureCheck(); - CheckResult certCheck = responseElement.getCertificateCheck(); - ResponseBuilderUtils.addSignerInfo( - responseDoc, - responseElem, - signerInfo.getSignerCertificate(), - signerInfo.isQualifiedCertificate(), - signerInfo.getQCSource(), - signerInfo.isPublicAuthority(), - signerInfo.getPublicAuhtorityID(), - signerInfo.isSSCD(), - signerInfo.getSSCDSource(), - signerInfo.getIssuerCountryCode(), - signerInfo.getTslInfos()); + responseDoc, + responseElem, + signerInfo.getSignerCertificate(), + signerInfo.isQualifiedCertificate(), + signerInfo.getQCSource(), + signerInfo.isPublicAuthority(), + signerInfo.getPublicAuhtorityID(), + signerInfo.isSSCD(), + signerInfo.getSSCDSource(), + signerInfo.getIssuerCountryCode(), + signerInfo.getTslInfos()); ResponseBuilderUtils.addSignatureAlgorithm(responseDoc, - responseElem, - responseElement.getSignatureAlgorithm()); - + responseElem, + responseElement.getSignatureAlgorithm()); + ResponseBuilderUtils.addCodeInfoElement( - responseDoc, - responseElem, - "SignatureCheck", - signatureCheck.getCode(), - signatureCheck.getInfo()); + responseDoc, + responseElem, + "SignatureCheck", + signatureCheck.getCode(), + signatureCheck.getInfo()); ResponseBuilderUtils.addCodeInfoElement( - responseDoc, - responseElem, - "CertificateCheck", - certCheck.getCode(), - certCheck.getInfo()); - + responseDoc, + responseElem, + "CertificateCheck", + certCheck.getCode(), + certCheck.getInfo()); if (responseElement.getAdESFormResults() != null) { - Iterator formIterator = responseElement.getAdESFormResults().iterator(); - - while (formIterator.hasNext()) { - AdESFormResults adESFormResult = (AdESFormResults) formIterator.next(); - // add the CertificateCheck - ResponseBuilderUtils.addFormCheckElement(responseDoc, responseElem, "FormCheckResult", - adESFormResult.getCode().intValue(), adESFormResult.getName()); - - } - } - - if(responseElement.getExtendedCertificateCheck() != null) { - ResponseBuilderUtils.addExtendendResult(responseDoc, responseElem, responseElement.getExtendedCertificateCheck()); - } - + final Iterator formIterator = responseElement.getAdESFormResults().iterator(); + + while (formIterator.hasNext()) { + final AdESFormResults adESFormResult = (AdESFormResults) formIterator.next(); + // add the CertificateCheck + ResponseBuilderUtils.addFormCheckElement(responseDoc, responseElem, "FormCheckResult", + adESFormResult.getCode().intValue(), adESFormResult.getName()); + + } + } + + if (responseElement.getExtendedCertificateCheck() != null) { + ResponseBuilderUtils.addExtendendResult(responseDoc, responseElem, responseElement + .getExtendedCertificateCheck()); + } + } } diff --git a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/xmlbind/VerifyASiCRequest.java b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/xmlbind/VerifyASiCRequest.java index 37584a6..93218bc 100644 --- a/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/xmlbind/VerifyASiCRequest.java +++ b/moaSig/moa-asic/src/main/java/at/gv/egiz/asic/xmlbind/VerifyASiCRequest.java @@ -1,46 +1,46 @@ package at.gv.egiz.asic.xmlbind; -import at.gv.egiz.asic.api.ASiCFormat; - import java.io.InputStream; import java.util.Date; +import at.gv.egiz.asic.api.ASiCFormat; + /** * Created by Andreas Fitzek on 6/16/16. */ public class VerifyASiCRequest { - private Date date; - private InputStream asicInput; - private String trustProfile; - private ASiCFormat format; - private boolean extendedValidation; - - - public VerifyASiCRequest(ASiCFormat format, Date date, InputStream asicInput, String trustProfile, boolean extendedValidation) { - this.format = format; - this.date = date; - this.asicInput = asicInput; - this.trustProfile = trustProfile; - this.extendedValidation = extendedValidation; - } - - public Date getDate() { - return date; - } - - public InputStream getAsicInput() { - return asicInput; - } - - public String getTrustProfile() { - return trustProfile; - } - - public ASiCFormat getFormat() { - return format; - } - - public boolean isExtendedValidation() { - return extendedValidation; - } + private final Date date; + private final InputStream asicInput; + private final String trustProfile; + private final ASiCFormat format; + private final boolean extendedValidation; + + public VerifyASiCRequest(ASiCFormat format, Date date, InputStream asicInput, String trustProfile, + boolean extendedValidation) { + this.format = format; + this.date = date; + this.asicInput = asicInput; + this.trustProfile = trustProfile; + this.extendedValidation = extendedValidation; + } + + public Date getDate() { + return date; + } + + public InputStream getAsicInput() { + return asicInput; + } + + public String getTrustProfile() { + return trustProfile; + } + + public ASiCFormat getFormat() { + return format; + } + + public boolean isExtendedValidation() { + return extendedValidation; + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/MOAApplicationException.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/MOAApplicationException.java index 305c227..97e63c5 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/MOAApplicationException.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/MOAApplicationException.java @@ -21,30 +21,30 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss; + /** * Base class of application specific MOA exceptions. - * - * Application exceptions are exceptions that originate from application - * code (e.g. inconsistent data provided by the user, no permission to access - * certain resources, etc.) - * + * + * Application exceptions are exceptions that originate from application code + * (e.g. inconsistent data provided by the user, no permission to access certain + * resources, etc.) + * * @author Patrick Peck * @version $Id$ */ public class MOAApplicationException extends MOAException { - + /** - * - */ - private static final long serialVersionUID = 1042877795934327684L; + * + */ + private static final long serialVersionUID = 1042877795934327684L; -/** + /** * Create a new MOAApplicationException. - * - * @param messageId The identifier of the message associated with this - * exception. + * + * @param messageId The identifier of the message associated with this + * exception. * @param parameters Additional message parameters. */ public MOAApplicationException(String messageId, Object[] parameters) { @@ -53,17 +53,17 @@ public class MOAApplicationException extends MOAException { /** * Create a new MOAApplicationException. - * - * @param messageId The identifier of the message associated with this - * MOAApplicationException. + * + * @param messageId The identifier of the message associated with this + * MOAApplicationException. * @param parameters Additional message parameters. - * @param wrapped The exception wrapped by this - * MOAApplicationException. + * @param wrapped The exception wrapped by this + * MOAApplicationException. */ public MOAApplicationException( - String messageId, - Object[] parameters, - Throwable wrapped) { + String messageId, + Object[] parameters, + Throwable wrapped) { super(messageId, parameters, wrapped); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/MOAException.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/MOAException.java index bf7f9af..0aff639 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/MOAException.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/MOAException.java @@ -21,8 +21,8 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss; + import java.io.PrintStream; import java.io.PrintWriter; @@ -39,30 +39,30 @@ import at.gv.egovernment.moaspss.util.Constants; /** * Base class of MOA specific exceptions. - * - * This class has the ability to wrap other exceptions which may be seen - * as the root cause for this exception. A similar mechanism is in place - * since JDK1.4 (see the getClause() method) but will not be used - * because of required compatibility with JDK1.3. - * + * + * This class has the ability to wrap other exceptions which may be seen as the + * root cause for this exception. A similar mechanism is in place since JDK1.4 + * (see the getClause() method) but will not be used because of + * required compatibility with JDK1.3. + * * @author Patrick Peck * @version $Id$ */ public abstract class MOAException extends Exception { /** - * - */ - private static final long serialVersionUID = 7115301799538771949L; -/** The message ID. */ - private String messageId; + * + */ + private static final long serialVersionUID = 7115301799538771949L; + /** The message ID. */ + private final String messageId; /** The wrapped Throwable. */ private Throwable wrapped; /** * Create a MOAException. - * - * @param messageId The message ID of the message contained in the created - * MOAException. + * + * @param messageId The message ID of the message contained in the created + * MOAException. * @param parameters The parameters needed to fill in the message arguments. */ public MOAException(String messageId, Object[] parameters) { @@ -72,15 +72,15 @@ public abstract class MOAException extends Exception { /** * Create a MOAException. - * - * @param messageId The message ID of the message contained in the created - * MOAException. + * + * @param messageId The message ID of the message contained in the created + * MOAException. * @param parameters The parameters needed to fill in the message arguments. - * @param wrapped The exception wrapped by the created - * MOAException. + * @param wrapped The exception wrapped by the created + * MOAException. */ public MOAException(String messageId, Object[] parameters, Throwable wrapped) { - // TODO: remove wrapped again from super constructor + // TODO: remove wrapped again from super constructor super(MessageProvider.getInstance().getMessage(messageId, parameters), wrapped); this.messageId = messageId; this.wrapped = wrapped; @@ -88,7 +88,7 @@ public abstract class MOAException extends Exception { /** * Returns the message ID of this exception. - * + * * @return The message ID as provided in the constructor. */ public String getMessageId() { @@ -97,9 +97,9 @@ public abstract class MOAException extends Exception { /** * Returns the exception wrapped by this MOAException. - * - * @return The exception wrapped by this exception. Possibly - * null, if none was provided at construction time. + * + * @return The exception wrapped by this exception. Possibly null, + * if none was provided at construction time. */ public Throwable getWrapped() { return wrapped; @@ -108,9 +108,10 @@ public abstract class MOAException extends Exception { /** * Convert this MOAException to an ErrorResponse * element from the MOA namespace. - * + * * @return An ErrorResponse element, containing the subelements - * ErrorCode and Info required by the MOA schema. + * ErrorCode and Info required by the MOA + * schema. */ public Element toErrorResponse() { DocumentBuilder builder; @@ -124,7 +125,7 @@ public abstract class MOAException extends Exception { try { builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); impl = builder.getDOMImplementation(); - } catch (ParserConfigurationException e) { + } catch (final ParserConfigurationException e) { return null; } @@ -134,11 +135,11 @@ public abstract class MOAException extends Exception { // add MOA namespace declaration errorResponse.setAttributeNS( - Constants.XMLNS_NS_URI, - "xmlns", - Constants.MOA_NS_URI); + Constants.XMLNS_NS_URI, + "xmlns", + Constants.MOA_NS_URI); - // build the child elements + // build the child elements errorCode = doc.createElementNS(Constants.MOA_NS_URI, "ErrorCode"); errorCode.appendChild(doc.createTextNode(messageId)); info = doc.createElementNS(Constants.MOA_NS_URI, "Info"); @@ -147,22 +148,24 @@ public abstract class MOAException extends Exception { errorResponse.appendChild(info); return errorResponse; } - + /** * Print a stack trace of this exception to System.err. - * + * * @see java.lang.Throwable#printStackTrace() */ + @Override public void printStackTrace() { printStackTrace(System.err); } /** * Print a stack trace of this exception, including the wrapped exception. - * + * * @param s The stream to write the stack trace to. * @see java.lang.Throwable#printStackTrace(java.io.PrintStream) */ + @Override public void printStackTrace(PrintStream s) { super.printStackTrace(s); if (getWrapped() != null) { @@ -173,10 +176,11 @@ public abstract class MOAException extends Exception { /** * Print a stack trace of this exception, including the wrapped exception. - * + * * @param s The stream to write the stacktrace to. * @see java.lang.Throwable#printStackTrace(java.io.PrintWriter) */ + @Override public void printStackTrace(PrintWriter s) { super.printStackTrace(s); if (getWrapped() != null) { diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/MOARuntimeException.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/MOARuntimeException.java index 3a65c48..d7522ff 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/MOARuntimeException.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/MOARuntimeException.java @@ -21,8 +21,8 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss; + import java.io.PrintStream; import java.io.PrintWriter; @@ -39,30 +39,30 @@ import at.gv.egovernment.moaspss.util.Constants; /** * Base class of MOA specific runtime exceptions. - * - * This class has the ability to wrap other exceptions which may be seen - * as the root cause for this exception. A similar mechanism is in place - * since JDK1.4 (see the getClause() method) but will not be used - * because of required compatibility with JDK1.3. - * + * + * This class has the ability to wrap other exceptions which may be seen as the + * root cause for this exception. A similar mechanism is in place since JDK1.4 + * (see the getClause() method) but will not be used because of + * required compatibility with JDK1.3. + * * @author Patrick Peck * @version $Id$ */ public class MOARuntimeException extends RuntimeException { /** - * - */ - private static final long serialVersionUID = 8516197293435621864L; -/** The message ID. */ - private String messageId; + * + */ + private static final long serialVersionUID = 8516197293435621864L; + /** The message ID. */ + private final String messageId; /** The wrapped Throwable. */ private Throwable wrapped; /** * Create a MOAException. - * - * @param messageId The message ID of the message contained in the created - * MOAException. + * + * @param messageId The message ID of the message contained in the created + * MOAException. * @param parameters The parameters needed to fill in the message arguments. */ public MOARuntimeException(String messageId, Object[] parameters) { @@ -72,17 +72,17 @@ public class MOARuntimeException extends RuntimeException { /** * Create a MOAException. - * - * @param messageId The message ID of the message contained in the created - * MOAException. + * + * @param messageId The message ID of the message contained in the created + * MOAException. * @param parameters The parameters needed to fill in the message arguments. - * @param wrapped The exception wrapped by the created - * MOAException. + * @param wrapped The exception wrapped by the created + * MOAException. */ public MOARuntimeException( - String messageId, - Object[] parameters, - Throwable wrapped) { + String messageId, + Object[] parameters, + Throwable wrapped) { super(MessageProvider.getInstance().getMessage(messageId, parameters)); this.messageId = messageId; @@ -91,7 +91,7 @@ public class MOARuntimeException extends RuntimeException { /** * Returns the message ID of this exception. - * + * * @return The message ID as provided in the constructor. */ public String getMessageId() { @@ -100,20 +100,21 @@ public class MOARuntimeException extends RuntimeException { /** * Returns the exception wrapped by this MOARuntimeException. - * - * @return The exception wrapped by this exception. Possibly - * null, if none was provided at construction time. + * + * @return The exception wrapped by this exception. Possibly null, + * if none was provided at construction time. */ public Throwable getWrapped() { return wrapped; } /** - * Convert this MOARuntimeException to an ErrorResponse - * element from the MOA namespace. - * + * Convert this MOARuntimeException to an + * ErrorResponse element from the MOA namespace. + * * @return An ErrorResponse element, containing the subelements - * ErrorCode and Info required by the MOA schema. + * ErrorCode and Info required by the MOA + * schema. */ public Element toErrorResponse() { DocumentBuilder builder; @@ -127,7 +128,7 @@ public class MOARuntimeException extends RuntimeException { try { builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); impl = builder.getDOMImplementation(); - } catch (ParserConfigurationException e) { + } catch (final ParserConfigurationException e) { return null; } @@ -137,11 +138,11 @@ public class MOARuntimeException extends RuntimeException { // add MOA namespace declaration errorResponse.setAttributeNS( - Constants.XMLNS_NS_URI, - "xmlns", - Constants.MOA_NS_URI); + Constants.XMLNS_NS_URI, + "xmlns", + Constants.MOA_NS_URI); - // build the child elements + // build the child elements errorCode = doc.createElementNS(Constants.MOA_NS_URI, "ErrorCode"); errorCode.appendChild(doc.createTextNode(messageId)); info = doc.createElementNS(Constants.MOA_NS_URI, "Info"); @@ -150,22 +151,24 @@ public class MOARuntimeException extends RuntimeException { errorResponse.appendChild(info); return errorResponse; } - + /** * Print a stack trace of this exception to System.err. - * + * * @see java.lang.Throwable#printStackTrace() */ + @Override public void printStackTrace() { printStackTrace(System.err); } /** * Print a stack trace of this exception, including the wrapped exception. - * + * * @param s The stream to write the stack trace to. * @see java.lang.Throwable#printStackTrace(java.io.PrintStream) */ + @Override public void printStackTrace(PrintStream s) { super.printStackTrace(s); if (getWrapped() != null) { @@ -176,10 +179,11 @@ public class MOARuntimeException extends RuntimeException { /** * Print a stack trace of this exception, including the wrapped exception. - * + * * @param s The stream to write the stacktrace to. * @see java.lang.Throwable#printStackTrace(java.io.PrintWriter) */ + @Override public void printStackTrace(PrintWriter s) { super.printStackTrace(s); if (getWrapped() != null) { diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/MOASystemException.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/MOASystemException.java index 67c1908..aea00a8 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/MOASystemException.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/MOASystemException.java @@ -21,29 +21,29 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss; + /** * Base class of technical MOA exceptions. - * + * * Technical exceptions are exceptions that originate from system failure (e.g., * a database connection fails, a component is not available, etc.) - * + * * @author Patrick Peck * @version $Id$ */ public class MOASystemException extends MOAException { /** - * - */ - private static final long serialVersionUID = 655642019638205185L; + * + */ + private static final long serialVersionUID = 655642019638205185L; -/** + /** * Create a new MOASystemException. - * - * @param messageId The identifier of the message associated with this - * exception. + * + * @param messageId The identifier of the message associated with this + * exception. * @param parameters Additional message parameters. */ public MOASystemException(String messageId, Object[] parameters) { @@ -52,17 +52,17 @@ public class MOASystemException extends MOAException { /** * Create a new MOASystemException. - * - * @param messageId The identifier of the message associated with this - * MOASystemException. + * + * @param messageId The identifier of the message associated with this + * MOASystemException. * @param parameters Additional message parameters. - * @param wrapped The exception wrapped by this - * MOASystemException. + * @param wrapped The exception wrapped by this + * MOASystemException. */ public MOASystemException( - String messageId, - Object[] parameters, - Throwable wrapped) { + String messageId, + Object[] parameters, + Throwable wrapped) { super(messageId, parameters, wrapped); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/OutputConstants.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/OutputConstants.java index c264475..e69171c 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/OutputConstants.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/OutputConstants.java @@ -5,11 +5,10 @@ import java.lang.reflect.Field; import iaik.server.modules.resultcodes.ResultCode; public class OutputConstants { - public static void main(String[] argv) throws IllegalArgumentException, IllegalAccessException { - Field[] fields = ResultCode.class.getFields(); - for(int i = 0; i < fields.length; i++) { - Field f = fields[i]; - System.out.println(f.getName() + " : " + f.get(null)); - } - } + public static void main(String[] argv) throws IllegalArgumentException, IllegalAccessException { + final Field[] fields = ResultCode.class.getFields(); + for (final Field f : fields) { + System.out.println(f.getName() + " : " + f.get(null)); + } + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/Configurator.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/Configurator.java index bc0acbe..f2d3b89 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/Configurator.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/Configurator.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api; import at.gv.egovernment.moa.spss.MOAException; @@ -30,9 +29,9 @@ import at.gv.egovernment.moa.spss.server.init.StartupConfigurationHolder; /** * Configures the SP/SS API. - * - * Also handles dynamic configuration updates. - * + * + * Also handles dynamic configuration updates. + * * @author Patrick Peck * @version $Id$ */ @@ -40,7 +39,7 @@ public abstract class Configurator { /** The default implementation class. */ private static final String DEFAULT_IMPLEMENTATION = - "at.gv.egovernment.moa.spss.server.init.ConfiguratorImpl"; + "at.gv.egovernment.moa.spss.server.init.ConfiguratorImpl"; /** The single instance of this class. */ private static Configurator instance = null; @@ -48,14 +47,13 @@ public abstract class Configurator { public static synchronized Configurator getInstance() { if (instance == null) { try { - /*DiscoverClass discover = new DiscoverClass(); - instance = - (Configurator) discover.newInstance( - Configurator.class, - DEFAULT_IMPLEMENTATION);*/ - instance = new ConfiguratorImpl(); - } catch (Exception e) { - // this can not happen since we provide a valid default + /* + * DiscoverClass discover = new DiscoverClass(); instance = (Configurator) + * discover.newInstance( Configurator.class, DEFAULT_IMPLEMENTATION); + */ + instance = new ConfiguratorImpl(); + } catch (final Exception e) { + // this can not happen since we provide a valid default // implementation } } @@ -64,31 +62,32 @@ public abstract class Configurator { /** * Get current configuration object. - * + * * @return Configuration or null if it was not initialized yet */ public abstract StartupConfigurationHolder getCurrentConfiguration(); - + /** * Initialize the SP/SS configuration. - * - * Only a single call to this method will have an effect. Use - * update() for reflecting changes in the configuration instead. - * + * + * Only a single call to this method will have an effect. Use + * update() for reflecting changes in the configuration instead. + * * @return Configuration holder - * + * * @throws MOAException An error occurred updating the SP/SS configuration. - */ + */ public abstract StartupConfigurationHolder init() throws MOAException; - + /** * Update the SP/SS configuration. - * + * * This will only have an effect after the system has been initialized once * using init(). - * - * @return Updated Configuration holder, or null if it was not initialized - * + * + * @return Updated Configuration holder, or null if it was not + * initialized + * * @throws MOAException An error occurred updating the SP/SS configuration. */ public abstract StartupConfigurationHolder update() throws MOAException; diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/SPSSFactory.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/SPSSFactory.java index d7cd10c..d0be7d5 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/SPSSFactory.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/SPSSFactory.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api; import java.io.InputStream; @@ -81,10 +80,10 @@ import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureResponse; /** * An abstract factory for creating MOA SP/SS API objects. - * - * Use getInstance() to get a concrete factory instance. Using - * this instance, concrete MOA SP/SS API object can be created. - * + * + * Use getInstance() to get a concrete factory instance. Using this + * instance, concrete MOA SP/SS API object can be created. + * * @author Patrick Peck * @author Gregor Karlinger * @version $Id$ @@ -93,27 +92,26 @@ public abstract class SPSSFactory { /** The default implementation of this class. */ private static final String DEFAULT_IMPLEMENTATION = - "at.gv.egovernment.moa.spss.api.impl.SPSSFactoryImpl"; + "at.gv.egovernment.moa.spss.api.impl.SPSSFactoryImpl"; /** The single instance of this class. */ private static SPSSFactory instance = null; /** * Returns the single instance of this class. - * + * * @return The single instance of this class. */ public static synchronized SPSSFactory getInstance() { if (instance == null) { try { - /*DiscoverClass discover = new DiscoverClass(); - instance = - (SPSSFactory) discover.newInstance( - SPSSFactory.class, - DEFAULT_IMPLEMENTATION);*/ + /* + * DiscoverClass discover = new DiscoverClass(); instance = (SPSSFactory) + * discover.newInstance( SPSSFactory.class, DEFAULT_IMPLEMENTATION); + */ instance = new SPSSFactoryImpl(); - } catch (Exception e) { - // this can not happen since we provide a valid default + } catch (final Exception e) { + // this can not happen since we provide a valid default // implementation } } @@ -126,94 +124,94 @@ public abstract class SPSSFactory { /** * Create a new CreateXMLSignatureRequest object. - * - * @param keyIdentifier The identifier for the key group to use for signing. - * @param singleSignatureInfos A List of - * SingleSignatureInfo objects containing information about a - * single signature to be created. - * @return The CreateXMLSignatureRequest containing the above - * data. - * + * + * @param keyIdentifier The identifier for the key group to use for + * signing. + * @param singleSignatureInfos A List of + * SingleSignatureInfo objects + * containing information about a single signature + * to be created. + * @return The CreateXMLSignatureRequest containing the above data. + * * @pre keyIdentifier != null && keyIdentifier.length() > 0 * @pre singleSignatureInfos != null - * @pre forall Object o in singleSignatureInfos | - * o instanceof at.gv.egovernment.moa.spss.api.common.SingleSignatureInfo + * @pre forall Object o in singleSignatureInfos | o instanceof + * at.gv.egovernment.moa.spss.api.common.SingleSignatureInfo * @post return != null */ public abstract CreateXMLSignatureRequest createCreateXMLSignatureRequest( - String keyIdentifier, - List singleSignatureInfos); + String keyIdentifier, + List singleSignatureInfos); /** * Create a new CreateCMSSignatureRequest object. - * - * @param keyIdentifier The identifier for the key group to use for signing. - * @param singleSignatureInfos A List of - * SingleSignatureInfo objects containing information about a - * single signature to be created. - * @return The CreateCMSSignatureRequest containing the above - * data. - * + * + * @param keyIdentifier The identifier for the key group to use for + * signing. + * @param singleSignatureInfos A List of + * SingleSignatureInfo objects + * containing information about a single signature + * to be created. + * @return The CreateCMSSignatureRequest containing the above data. + * * @pre keyIdentifier != null && keyIdentifier.length() > 0 * @pre singleSignatureInfos != null - * @pre forall Object o in singleSignatureInfos | - * o instanceof at.gv.egovernment.moa.spss.api.common.SingleSignatureInfo + * @pre forall Object o in singleSignatureInfos | o instanceof + * at.gv.egovernment.moa.spss.api.common.SingleSignatureInfo * @post return != null */ public abstract CreateCMSSignatureRequest createCreateCMSSignatureRequest( - String keyIdentifier, - List singleSignatureInfos); - + String keyIdentifier, + List singleSignatureInfos); + /** * Create a new SingleSignatureInfo object. - * - * @param dataObjectInfos The data objects that will be signed (including - * transformations). - * @param createSignatureInfo Information about the signature environment. May - * be null. + * + * @param dataObjectInfos The data objects that will be signed (including + * transformations). + * @param createSignatureInfo Information about the signature environment. May + * be null. * @param securityLayerConform If true, a Security Layer conform - * signature manifest is created, otherwise not. + * signature manifest is created, otherwise not. * @return The SingleSignatureInfo containing the above data. - * + * * @pre dataObjectInfos != null && dataObjectInfos.size() > 0 - * @pre forall Object o in dataObjectInfos | - * o instanceof at.gv.egovernment.moa.spss.api.xmlsign.DataObjectInfo + * @pre forall Object o in dataObjectInfos | o instanceof + * at.gv.egovernment.moa.spss.api.xmlsign.DataObjectInfo * @post return != null */ public abstract SingleSignatureInfo createSingleSignatureInfo( - List dataObjectInfos, - CreateSignatureInfo createSignatureInfo, boolean securityLayerConform); - + List dataObjectInfos, + CreateSignatureInfo createSignatureInfo, boolean securityLayerConform); + /** * Create a new SingleSignatureInfo object. - * - * @param dataObjectInfo The data object that will be signed. + * + * @param dataObjectInfo The data object that will be signed. * @param securityLayerConform If true, a Security Layer conform - * signature manifest is created, otherwise not. - * @param isPAdESSignature + * signature manifest is created, otherwise not. + * @param isPAdESSignature * @return The SingleSignatureInfo containing the above data. - * + * * @post return != null */ - public abstract at.gv.egovernment.moa.spss.api.cmssign.SingleSignatureInfo createSingleSignatureInfoCMS( - at.gv.egovernment.moa.spss.api.cmssign.DataObjectInfo dataObjectInfo, - boolean securityLayerConform, boolean isPAdESSignature); - - - + public abstract at.gv.egovernment.moa.spss.api.cmssign.SingleSignatureInfo createSingleSignatureInfoCMS( + at.gv.egovernment.moa.spss.api.cmssign.DataObjectInfo dataObjectInfo, + boolean securityLayerConform, boolean isPAdESSignature); /** * Create a new DataObjectInfo object. - * - * @param structure The type of signature to create. - * @param childOfManifest If true, references will be returned - * as children of an XMLDsig manifest. Otherwise, they will be returned as - * children of the signature itself. - * @param dataObject The data object that will be signed. - * @param createTransformsInfoProfile Additional transformations to apply - * to the data object. + * + * @param structure The type of signature to create. + * @param childOfManifest If true, references will be + * returned as children of an XMLDsig + * manifest. Otherwise, they will be returned + * as children of the signature itself. + * @param dataObject The data object that will be signed. + * @param createTransformsInfoProfile Additional transformations to apply to the + * data object. * @return The DataObjectInfo containing the above data. - * + * * @pre DataObjectInfo.STRUCTURE_DETACHED.equals(structure) || * DataObjectInfo.STRUCTURE_ENVELOPING.equals(structure) * @pre dataObject != null @@ -221,218 +219,216 @@ public abstract class SPSSFactory { * @post return != null */ public abstract DataObjectInfo createDataObjectInfo( - String structure, - boolean childOfManifest, - Content dataObject, - CreateTransformsInfoProfile createTransformsInfoProfile); + String structure, + boolean childOfManifest, + Content dataObject, + CreateTransformsInfoProfile createTransformsInfoProfile); /** * Create a new DataObjectInfo object. - * - * @param structure The type of signature to create. + * + * @param structure The type of signature to create. * @param dataObject The data object that will be signed. * @return The DataObjectInfo containing the above data. - * + * * @pre DataObjectInfo.STRUCTURE_DETACHED.equals(structure) || * DataObjectInfo.STRUCTURE_ENVELOPING.equals(structure) * @pre dataObject != null * @post return != null */ public abstract at.gv.egovernment.moa.spss.api.cmssign.DataObjectInfo createDataObjectInfo( - String structure, - CMSDataObject dataObject); - + String structure, + CMSDataObject dataObject); + /** * Create a new CreateTransformsInfoProfile object containing a * reference to a locally stored profile. - * - * @param profileID The profile ID to resolve during signature creation. + * + * @param profileID The profile ID to resolve during signature creation. * @return The CreateTransformsInfoProfile containing the given - * profile ID. - * + * profile ID. + * * @pre profileID != null && profileID.length() > 0 * @post return != null */ public abstract CreateTransformsInfoProfile createCreateTransformsInfoProfile(String profileID); /** - * Create a new CreateTransformsInfoProfile object by providing - * the profile data explicitly. - * - * @param transformsInfo The transformations to apply to the associated - * data object. - * @param supplements Supplemental information for the transformation. May be - * null. + * Create a new CreateTransformsInfoProfile object by providing the + * profile data explicitly. + * + * @param transformsInfo The transformations to apply to the associated data + * object. + * @param supplements Supplemental information for the transformation. May be + * null. * @return The CreateTransformsInfoProfile containing the above - * data. - * + * data. + * * @pre transformsInfo != null - * @pre supplements != null implies - * forall Object o in supplements | - * o instanceof at.gv.egovernment.moa.spss.api.common.XMLDataObjectAssociation + * @pre supplements != null implies forall Object o in supplements | o + * instanceof + * at.gv.egovernment.moa.spss.api.common.XMLDataObjectAssociation * @post return != null */ public abstract CreateTransformsInfoProfile createCreateTransformsInfoProfile( - CreateTransformsInfo transformsInfo, - List supplements); + CreateTransformsInfo transformsInfo, + List supplements); /** * Create a new CreateTransformsInfo object. - * - * @param transforms The Transforms to apply to the associated - * data object. May be null. - * @param finalDataMetaInfo Information about the type of the transformed - * data. + * + * @param transforms The Transforms to apply to the + * associated data object. May be null. + * @param finalDataMetaInfo Information about the type of the transformed data. * @return The CreateTransformsInfo containing the above data. - * + * * @pre transforms != null implies transforms.size > 0 - * @pre transforms != null implies - * forall Object o in transforms | - * o instanceof at.gv.egovernment.moa.spss.api.common.Transform + * @pre transforms != null implies forall Object o in transforms | o instanceof + * at.gv.egovernment.moa.spss.api.common.Transform * @pre finalDataMetaInfo != null * @post return != null */ public abstract CreateTransformsInfo createCreateTransformsInfo( - List transforms, - MetaInfo finalDataMetaInfo); + List transforms, + MetaInfo finalDataMetaInfo); /** * Create a new CreateSignatureInfo object. - * - * @param createSignatureEnvironment The signature environment that will - * contain the signature. - * @param createSignatureEnvironmentProfile Additional information about - * the signture environment. + * + * @param createSignatureEnvironment The signature environment that will + * contain the signature. + * @param createSignatureEnvironmentProfile Additional information about the + * signture environment. * @return The CreateSignatureInfo containing the above data. - * + * * @pre createSignatureEnvironment != null * @pre createSignatureEnvironmentProfile != null * @post return != null */ public abstract CreateSignatureInfo createCreateSignatureInfo( - Content createSignatureEnvironment, - CreateSignatureEnvironmentProfile createSignatureEnvironmentProfile); + Content createSignatureEnvironment, + CreateSignatureEnvironmentProfile createSignatureEnvironmentProfile); /** - * Create a new CreateSignatureEnvironmentProfile object - * containing a reference to a locally stored profile. - * + * Create a new CreateSignatureEnvironmentProfile object containing + * a reference to a locally stored profile. + * * @param profileID The profile ID to resolve during signature creation. - * @return The CreateSignatureEnvironmentProfile containing - * the given profile ID. - * + * @return The CreateSignatureEnvironmentProfile containing the + * given profile ID. + * * @pre profileID != null && profileID.length() > 0 * @post return != null */ public abstract CreateSignatureEnvironmentProfile createCreateSignatureEnvironmentProfile(String profileID); /** - * Create a new CreateSignatureEnvironmentProfile object by - * providing the profile data explicitly. - * + * Create a new CreateSignatureEnvironmentProfile object by + * providing the profile data explicitly. + * * @param createSignatureLocation The location where the signature will be - * inserted. - * @param supplements Additional information about the signature environment. + * inserted. + * @param supplements Additional information about the signature + * environment. * @return The CreateSignatureEnvironmentProfile containing the - * above data. - * + * above data. + * * @pre createSignatureLocation != null - * @pre supplements != null - * @pre forall Object o in supplements | - * o instanceof at.gv.egovernment.moa.spss.api.common.XMLDataObjectAssociation + * @pre supplements != null + * @pre forall Object o in supplements | o instanceof + * at.gv.egovernment.moa.spss.api.common.XMLDataObjectAssociation * @post return != null */ public abstract CreateSignatureEnvironmentProfile createCreateSignatureEnvironmentProfile( - CreateSignatureLocation createSignatureLocation, - List supplements); + CreateSignatureLocation createSignatureLocation, + List supplements); /** * Create a new CreateSignatureLocation object. - * - * @param xPathExpression The XPath expression to select the signature - * parent element within the signature environment. - * @param index The index of the node, after which the signature will be - * inserted. + * + * @param xPathExpression The XPath expression to select the signature + * parent element within the signature environment. + * @param index The index of the node, after which the signature + * will be inserted. * @param namespaceDeclarations The namespace prefix to URI mapping to apply - * while evaluating the XPath expression. + * while evaluating the XPath expression. * @return The CreateSignatureLocation containing the above data. - * + * * @pre xPathExpression != null * @pre index >= 0 * @pre namespaceDeclarations != null */ public abstract CreateSignatureLocation createCreateSignatureLocation( - String xPathExpression, - int index, - Map namespaceDeclarations); + String xPathExpression, + int index, + Map namespaceDeclarations); /** * Create a new CreateXMLSignatureResponse object. - * - * @param responseElements The elements of the response, either - * SignatureEnvironmentResponse objects, or - * ErrorResponse objects. - * @return The new CreateXMLSignatureResponse containing the - * above data. - * + * + * @param responseElements The elements of the response, either + * SignatureEnvironmentResponse objects, or + * ErrorResponse objects. + * @return The new CreateXMLSignatureResponse containing the above + * data. + * * @pre responseElements != null && responseElements.size() > 0 - * @pre forall Object o in responseElements | - * o instanceof at.gv.egovernment.moa.spss.api.xmlsign.CreateSignatureResponseElement + * @pre forall Object o in responseElements | o instanceof + * at.gv.egovernment.moa.spss.api.xmlsign.CreateSignatureResponseElement * @post return != null */ public abstract CreateXMLSignatureResponse createCreateXMLSignatureResponse(List responseElements); - /** * Create a new CreateCMSSignatureResponse object. - * - * @param responseElements The elements of the response, either - * CMSSignatureResponse objects, or - * ErrorResponse objects. - * @return The new CreateCMSSignatureResponse containing the - * above data. - * + * + * @param responseElements The elements of the response, either + * CMSSignatureResponse objects, or + * ErrorResponse objects. + * @return The new CreateCMSSignatureResponse containing the above + * data. + * * @pre responseElements != null && responseElements.size() > 0 - * @pre forall Object o in responseElements | - * o instanceof at.gv.egovernment.moa.spss.api.cmssign.CMSSignatureResponse + * @pre forall Object o in responseElements | o instanceof + * at.gv.egovernment.moa.spss.api.cmssign.CMSSignatureResponse * @post return != null */ public abstract CreateCMSSignatureResponse createCreateCMSSignatureResponse(List responseElements); - - + /** * Create a new SignatureEnvironmentResponse object. - * + * * @param signatureEnvironment The signature environment containing the - * signature. + * signature. * @return The SignatureEnvironmentResponse containing the - * signatureEnvironment. - * + * signatureEnvironment. + * * @pre signatureEnvironment != null * @post return != null */ public abstract CMSSignatureResponse createCMSSignatureResponse(String base64value); - + /** * Create a new SignatureEnvironmentResponse object. - * + * * @param signatureEnvironment The signature environment containing the - * signature. + * signature. * @return The SignatureEnvironmentResponse containing the - * signatureEnvironment. - * + * signatureEnvironment. + * * @pre signatureEnvironment != null * @post return != null */ - public abstract SignatureEnvironmentResponse createSignatureEnvironmentResponse(Element signatureEnvironment); + public abstract SignatureEnvironmentResponse createSignatureEnvironmentResponse( + Element signatureEnvironment); /** * Create a new ErrorResponse object. - * + * * @param code The numerical error code. * @param info Verbose error information. * @return The new ErrorResponse containing the above data. - * + * * @pre code > 0 * @pre info != null * @post return != null @@ -445,91 +441,87 @@ public abstract class SPSSFactory { /** * Create a new VerifyCMSSignatureRequest object. - * - * @param signatories The indexes of the signatories whose signature is to - * be verified. - * @param dateTime The date for which the verification is to be performed. - * May be null. - * @param cmsSignature The CMS signature. - * @param dataObject The signed data. May be null. - * @param trustProfileID The ID of the trust profile containing the trusted - * root certificates. - * @return The VerifyCMSSignatureRequest containing the above - * data. - * + * + * @param signatories The indexes of the signatories whose signature is to be + * verified. + * @param dateTime The date for which the verification is to be performed. + * May be null. + * @param cmsSignature The CMS signature. + * @param dataObject The signed data. May be null. + * @param trustProfileID The ID of the trust profile containing the trusted root + * certificates. + * @return The VerifyCMSSignatureRequest containing the above data. + * * @pre signatories != null && signatories.length > 0 - * @pre signaturies != VerifyCMSSignatureRequest.ALL_SIGNATORIES implies - * for (int i = 0; i < signatories.length; i++) - * signatories[i] >= 1 + * @pre signaturies != VerifyCMSSignatureRequest.ALL_SIGNATORIES implies for + * (int i = 0; i < signatories.length; i++) signatories[i] >= 1 * @pre cmsSignature != null * @pre trustProfileID != null && trustProfileID.length() > 0 * @post return != null */ public abstract VerifyCMSSignatureRequest createVerifyCMSSignatureRequest( - int[] signatories, - Date dateTime, - InputStream cmsSignature, - CMSDataObject dataObject, - String trustProfileID, - boolean pdf); - + int[] signatories, + Date dateTime, + InputStream cmsSignature, + CMSDataObject dataObject, + String trustProfileID, + boolean pdf); + /** * Create a new VerifyCMSSignatureRequest object. - * - * @param signatories The indexes of the signatories whose signature is to - * be verified. - * @param dateTime The date for which the verification is to be performed. - * May be null. - * @param cmsSignature The CMS signature. - * @param dataObject The signed data. May be null. - * @param trustProfileID The ID of the trust profile containing the trusted - * root certificates. - * @return The VerifyCMSSignatureRequest containing the above - * data. - * + * + * @param signatories The indexes of the signatories whose signature is to be + * verified. + * @param dateTime The date for which the verification is to be performed. + * May be null. + * @param cmsSignature The CMS signature. + * @param dataObject The signed data. May be null. + * @param trustProfileID The ID of the trust profile containing the trusted root + * certificates. + * @return The VerifyCMSSignatureRequest containing the above data. + * * @pre signatories != null && signatories.length > 0 - * @pre signaturies != VerifyCMSSignatureRequest.ALL_SIGNATORIES implies - * for (int i = 0; i < signatories.length; i++) - * signatories[i] >= 1 + * @pre signaturies != VerifyCMSSignatureRequest.ALL_SIGNATORIES implies for + * (int i = 0; i < signatories.length; i++) signatories[i] >= 1 * @pre cmsSignature != null * @pre trustProfileID != null && trustProfileID.length() > 0 * @post return != null */ public abstract VerifyCMSSignatureRequest createVerifyCMSSignatureRequest( - int[] signatories, - Date dateTime, - InputStream cmsSignature, - CMSDataObject dataObject, - String trustProfileID, - boolean pdf, - boolean extended); + int[] signatories, + Date dateTime, + InputStream cmsSignature, + CMSDataObject dataObject, + String trustProfileID, + boolean pdf, + boolean extended); /** * Create a new CMSDataObject object from data at a given URI. - * - * @param metaInfo Type information about the CMSDataObject. - * May be null. - * @param content The CMS content containing the data. + * + * @param metaInfo Type information about the CMSDataObject. May be + * null. + * @param content The CMS content containing the data. * @return The new CMSDataObject containing the data. - * + * * @pre referenceURI != null * @pre content != null * @post return != null */ public abstract CMSDataObject createCMSDataObject( - MetaInfo metaInfo, - CMSContent content, - BigDecimal excludeByteRangeFrom, - BigDecimal excludeByteRangeTo); + MetaInfo metaInfo, + CMSContent content, + BigDecimal excludeByteRangeFrom, + BigDecimal excludeByteRangeTo); /** * Create a new CMSContent object from the data contained at the * given URI. - * + * * @param referenceURI The URI identifying the data. Must be resolvable. * @return The CMSContent containing a reference to the signed - * data. - * + * data. + * * @pre referenceURI != null * @post return != null */ @@ -537,11 +529,11 @@ public abstract class SPSSFactory { /** * Create a new CMSContent object from a byte stream. - * + * * @param binaryContent The byte stream containing the signed data. - * @return The new CMSContent containing the data from the - * byte stream. - * + * @return The new CMSContent containing the data from the byte + * stream. + * * @pre binaryContent != null * @post return != null */ @@ -549,41 +541,40 @@ public abstract class SPSSFactory { /** * Create a new VerifyCMSSignatureResponse object. - * + * * @param responseElements Verification information about each signature. - * @return The new VerifyCMSSignatureResponse containing the - * status of signature verification for each signature contained in the - * request. - * - * @pre responseElements != null && responseElements.size() > 0 - * @pre forall Object o in responseElements | - * o instanceof at.gv.egovernment.moa.spss.api.cmssign.VerifyCMSSignatureResponseElement + * @return The new VerifyCMSSignatureResponse containing the status + * of signature verification for each signature contained in the + * request. + * + * @pre responseElements != null && responseElements.size() > 0 + * @pre forall Object o in responseElements | o instanceof + * at.gv.egovernment.moa.spss.api.cmssign.VerifyCMSSignatureResponseElement * @post return != null */ public abstract VerifyCMSSignatureResponse createVerifyCMSSignatureResponse(List responseElements); /** * Create a new VerifyCMSSignatureResponseElement object. - * - * @param signerInfo Information about the signer certificate. - * @param signatureCheck Result of the signature value check. + * + * @param signerInfo Information about the signer certificate. + * @param signatureCheck Result of the signature value check. * @param certificateCheck Result of the certificate status check. - * @return The new VerifyCMSSignatureResponseElement containing - * the above data. - * - * @pre signerInfo != null && signatureCheck != null && - * certificateCheck != null + * @return The new VerifyCMSSignatureResponseElement containing the + * above data. + * + * @pre signerInfo != null && signatureCheck != null && certificateCheck != null * @post return != null */ public abstract VerifyCMSSignatureResponseElement createVerifyCMSSignatureResponseElement( - SignerInfo signerInfo, - CheckResult signatureCheck, - CheckResult certificateCheck, - List adesResult, - ExtendedCertificateCheckResult extendedCertificateCheckResult, - String usedAlgorithm, - Boolean coversFullDocument, - int[] byteRangeOfSignature); + SignerInfo signerInfo, + CheckResult signatureCheck, + CheckResult certificateCheck, + List adesResult, + ExtendedCertificateCheckResult extendedCertificateCheckResult, + String usedAlgorithm, + Boolean coversFullDocument, + int[] byteRangeOfSignature); // // Factory methods for verifying XML signatures @@ -591,114 +582,114 @@ public abstract class SPSSFactory { /** * Create a new VerifyXMLSignatureRequest object. - * - * @param dateTime The date for which the verification is to be performed. - * May be null. - * @param verifySignatureInfo Information about the signature environment and - * the location of the signature. - * @param supplementProfiles Supplemental information for the signature - * environment. May be null. + * + * @param dateTime The date for which the verification is to be + * performed. May be null. + * @param verifySignatureInfo Information about the signature environment + * and the location of the signature. + * @param supplementProfiles Supplemental information for the signature + * environment. May be null. * @param signatureManifestParams Additional information for checking the - * signature manifest. May be null. - * @param returnHashInputData If true, hash input data will - * be returned in the response, otherwise not. - * @param trustProfileID The ID of the trust profile containing the trusted - * root certificates. - * @return The new VerifyXMLSignatureRequest containing the - * above data. - * + * signature manifest. May be null. + * @param returnHashInputData If true, hash input data will be + * returned in the response, otherwise not. + * @param trustProfileID The ID of the trust profile containing the + * trusted root certificates. + * @return The new VerifyXMLSignatureRequest containing the above + * data. + * * @pre verifySignatureInfo != null - * @pre supplementProfiles != null implies - * forall Object o in supplementProfiles | - * o instanceof at.gv.egovernment.moa.spss.api.xmlverify.SupplementProfile + * @pre supplementProfiles != null implies forall Object o in supplementProfiles + * | o instanceof + * at.gv.egovernment.moa.spss.api.xmlverify.SupplementProfile * @pre trustProfileID != null && trustProfileID.length() > 0 * @post return != null */ public abstract VerifyXMLSignatureRequest createVerifyXMLSignatureRequest( - Date dateTime, - VerifySignatureInfo verifySignatureInfo, - List supplementProfiles, - SignatureManifestCheckParams signatureManifestParams, - boolean returnHashInputData, - String trustProfileID); - + Date dateTime, + VerifySignatureInfo verifySignatureInfo, + List supplementProfiles, + SignatureManifestCheckParams signatureManifestParams, + boolean returnHashInputData, + String trustProfileID); + /** * Create a new VerifyXMLSignatureRequest object. - * - * @param dateTime The date for which the verification is to be performed. - * May be null. - * @param verifySignatureInfo Information about the signature environment and - * the location of the signature. - * @param supplementProfiles Supplemental information for the signature - * environment. May be null. + * + * @param dateTime The date for which the verification is to be + * performed. May be null. + * @param verifySignatureInfo Information about the signature environment + * and the location of the signature. + * @param supplementProfiles Supplemental information for the signature + * environment. May be null. * @param signatureManifestParams Additional information for checking the - * signature manifest. May be null. - * @param returnHashInputData If true, hash input data will - * be returned in the response, otherwise not. - * @param trustProfileID The ID of the trust profile containing the trusted - * root certificates. - * @param extendedValidation Should the valdation result in forms - * @return The new VerifyXMLSignatureRequest containing the - * above data. - * + * signature manifest. May be null. + * @param returnHashInputData If true, hash input data will be + * returned in the response, otherwise not. + * @param trustProfileID The ID of the trust profile containing the + * trusted root certificates. + * @param extendedValidation Should the valdation result in forms + * @return The new VerifyXMLSignatureRequest containing the above + * data. + * * @pre verifySignatureInfo != null - * @pre supplementProfiles != null implies - * forall Object o in supplementProfiles | - * o instanceof at.gv.egovernment.moa.spss.api.xmlverify.SupplementProfile + * @pre supplementProfiles != null implies forall Object o in supplementProfiles + * | o instanceof + * at.gv.egovernment.moa.spss.api.xmlverify.SupplementProfile * @pre trustProfileID != null && trustProfileID.length() > 0 * @post return != null */ public abstract VerifyXMLSignatureRequest createVerifyXMLSignatureRequest( - Date dateTime, - VerifySignatureInfo verifySignatureInfo, - List supplementProfiles, - SignatureManifestCheckParams signatureManifestParams, - boolean returnHashInputData, - String trustProfileID, - boolean extendedValidation); + Date dateTime, + VerifySignatureInfo verifySignatureInfo, + List supplementProfiles, + SignatureManifestCheckParams signatureManifestParams, + boolean returnHashInputData, + String trustProfileID, + boolean extendedValidation); /** * Create a new VerifySignatureInfo object. - * - * @param verifySignatureEnvironment The signature environment containing - * the signature to be verified. - * @param verifySignatureLocation The location of the signature within the - * signature environment. + * + * @param verifySignatureEnvironment The signature environment containing the + * signature to be verified. + * @param verifySignatureLocation The location of the signature within the + * signature environment. * @return The new VerifySignatureInfo containing the above data. - * + * * @pre verifySignatureEnvironment != null * @pre verifySignatureLocation != null * @post return != null */ public abstract VerifySignatureInfo createVerifySignatureInfo( - Content verifySignatureEnvironment, - VerifySignatureLocation verifySignatureLocation); + Content verifySignatureEnvironment, + VerifySignatureLocation verifySignatureLocation); /** * Create a new VerifySignatureLocation object. - * - * @param xPathExpression The XPath expression to select the signature - * element within the signature environment. + * + * @param xPathExpression The XPath expression to select the signature + * element within the signature environment. * @param namespaceDeclarations The namespace prefix to URI mapping to apply - * while evaluating the XPath expression. + * while evaluating the XPath expression. * @return The new VerifySignatureLocation containing the above - * data. - * + * data. + * * @pre xPathExpression != null * @pre namespaceDeclarations != null * @post return != null */ public abstract VerifySignatureLocation createVerifySignatureLocation( - String xPathExpression, - Map namespaceDeclarations); + String xPathExpression, + Map namespaceDeclarations); /** - * Create a new SupplementProfile object containing a reference - * to a locally stored profile. - * + * Create a new SupplementProfile object containing a reference to + * a locally stored profile. + * * @param profileID The profile ID to resolve during signature verification. * @return The SupplementProfile containing the profile ID. - * + * * @pre profileID != null && profileID.length() > 0 * @post return != null */ @@ -707,7 +698,7 @@ public abstract class SPSSFactory { /** * Create a new SupplementProfile object by providing the profile * data explicitly. - * + * * @param supplementProfile The profile data. * @return The SupplementProfile containing the profile data. */ @@ -715,232 +706,227 @@ public abstract class SPSSFactory { /** * Create a new SignatureManifestCheckParams object. - * - * @param referenceInfos Information for checking the validity of a - * a reference. - * @param returnReferenceInputData If true, the input data to - * the calculation of reference digest values will be returned in the - * response, otherwise not. - * @return The SignatureManifestCheckParams containing the - * above data. - * + * + * @param referenceInfos Information for checking the validity of a a + * reference. + * @param returnReferenceInputData If true, the input data to the + * calculation of reference digest values will + * be returned in the response, otherwise not. + * @return The SignatureManifestCheckParams containing the above + * data. + * * @pre referenceInfos != null && referenceInfos.size() > 0 - * @pre forall Object o in referenceInfos | - * o instanceof at.gv.egovernment.moa.spss.api.xmlverify.ReferenceInfo + * @pre forall Object o in referenceInfos | o instanceof + * at.gv.egovernment.moa.spss.api.xmlverify.ReferenceInfo * @post return != null */ public abstract SignatureManifestCheckParams createSignatureManifestCheckParams( - List referenceInfos, - boolean returnReferenceInputData); + List referenceInfos, + boolean returnReferenceInputData); /** * Create a new ReferenceInfo object. - * - * @param verifyTransformsInfoProfiles The transformation profiles valid for - * the associated reference. - * @return The ReferenceInfo containing the transformation - * profiles. - * - * @pre verifyTransformsInfoProfiles != null && - * verifyTransformsInfoProfiles.size() > 0 - * @pre forall Object o in verifyTransformsInfoProfiles | - * o instanceof at.gv.egovernment.moa.spss.api.xmlverify.VerifyTransformsInfoProfile + * + * @param verifyTransformsInfoProfiles The transformation profiles valid for the + * associated reference. + * @return The ReferenceInfo containing the transformation + * profiles. + * + * @pre verifyTransformsInfoProfiles != null && + * verifyTransformsInfoProfiles.size() > 0 + * @pre forall Object o in verifyTransformsInfoProfiles | o instanceof + * at.gv.egovernment.moa.spss.api.xmlverify.VerifyTransformsInfoProfile * @post return != null */ public abstract ReferenceInfo createReferenceInfo(List verifyTransformsInfoProfiles); /** - * Create a new VerifyTransformsInfoProfile object containing - * a reference to a locally stored profile. - * + * Create a new VerifyTransformsInfoProfile object containing a + * reference to a locally stored profile. + * * @param profileID The profile ID to resolve during signature verification. - * @return The VerifyTransformsInfoProfile containing the - * given profile ID. - * + * @return The VerifyTransformsInfoProfile containing the given + * profile ID. + * * @pre profileID != null && profileID.length() > 0 * @post return != null */ public abstract VerifyTransformsInfoProfile createVerifyTransformsInfoProfile(String profileID); /** - * Create a new VerifyTransformsInfoProfile object by providing - * the profile data explicitly. - * - * @param transforms A valid chain of transformations for the reference. - * May be null. + * Create a new VerifyTransformsInfoProfile object by providing the + * profile data explicitly. + * + * @param transforms A valid chain of transformations for the + * reference. May be null. * @param transformParameters Additional transformation information. * @return The VerifyTransformsInfoProfile containing the above - * data. - * - * @pre transforms != null implies - * (transforms.size() > 0 && - * forall Object o in transforms | o instanceof Transform) - * @pre transformParameters != null implies - * forall Object o in transformParameters | - * o instanceof at.gv.egovernment.moa.spss.api.xmlverify.TransformParameter + * data. + * + * @pre transforms != null implies (transforms.size() > 0 && forall Object o in + * transforms | o instanceof Transform) + * @pre transformParameters != null implies forall Object o in + * transformParameters | o instanceof + * at.gv.egovernment.moa.spss.api.xmlverify.TransformParameter * @post return != null */ public abstract VerifyTransformsInfoProfile createVerifyTransformsInfoProfile( - List transforms, - List transformParameters); + List transforms, + List transformParameters); /** - * Create a new TransformParameter object with the data - * contained at the given URI. - * + * Create a new TransformParameter object with the data contained + * at the given URI. + * * @param URI The URI identifying the data. The URI will be resolved during - * signature verification. - * @return The TransformParameter containing the URI of the - * data. - * + * signature verification. + * @return The TransformParameter containing the URI of the data. + * * @pre URI != null * @post return != null */ public abstract TransformParameter createTransformParameter(String URI); /** - * Creata a new TransformParameter object containing the - * binary data. - * - * @param URI The URI identifying the data. - * @param binaryData The binary data. + * Creata a new TransformParameter object containing the binary + * data. + * + * @param URI The URI identifying the data. + * @param binaryData The binary data. * @return The TransformParameter containig the binary data. - * + * * @pre URI != null * @pre binary != null * @post return != null */ public abstract TransformParameter createTransformParameter( - String URI, - InputStream binaryData); + String URI, + InputStream binaryData); /** - * Create a new TransformParameter object containing the hash - * value of the transformation data. - * - * @param URI The URI identifying the data. It will be resolved during - * signature verification. - * @param digestMethod The digest method used for calculating the digest - * value. - * @param digestValue The hash value of the transformation data. + * Create a new TransformParameter object containing the hash value + * of the transformation data. + * + * @param URI The URI identifying the data. It will be resolved during + * signature verification. + * @param digestMethod The digest method used for calculating the digest value. + * @param digestValue The hash value of the transformation data. * @return The TransformParameter containing the above data. - * + * * @pre URI != null * @pre digestMethod != null * @pre digestValue != null */ public abstract TransformParameter createTransformParameter( - String URI, - String digestMethod, - byte[] digestValue); + String URI, + String digestMethod, + byte[] digestValue); /** * Create a new VerifyXMLSignatureResponse object. - * - * @param signerInfo Information about the signer certificate. - * @param hashInputDatas The signed data objects. May be null. - * @param referenceInputDatas The reference input data objects. - * May be null. - * @param signatureCheck Status information about the signature check. - * @param signatureManifestCheck Status information about the signature - * manifest check. - * @param xmlDsigManifestChecks Status information about each XMLDsig manifest - * check. - * @param certificateCheck Status information about the signer certificate - * check. + * + * @param signerInfo Information about the signer certificate. + * @param hashInputDatas The signed data objects. May be + * null. + * @param referenceInputDatas The reference input data objects. May be + * null. + * @param signatureCheck Status information about the signature check. + * @param signatureManifestCheck Status information about the signature manifest + * check. + * @param xmlDsigManifestChecks Status information about each XMLDsig manifest + * check. + * @param certificateCheck Status information about the signer certificate + * check. * @return The VerifyXMLSignatureResponse containing the above - * data. - * + * data. + * * @pre signerInfo != null - * @pre hashInputDatas != null implies - * forall Object o in hashInputDatas | - * o instanceof at.gv.egovernment.moa.spss.api.common.Content - * @pre referenceInputDatas != null implies - * forall Object o in referenceInputDatas | - * o instanceof at.gv.egovernment.moa.spss.api.common.Content + * @pre hashInputDatas != null implies forall Object o in hashInputDatas | o + * instanceof at.gv.egovernment.moa.spss.api.common.Content + * @pre referenceInputDatas != null implies forall Object o in + * referenceInputDatas | o instanceof + * at.gv.egovernment.moa.spss.api.common.Content * @pre signatureCheck != null - * @pre xmlDsigManifestChecks != null implies - * forall Object o in xmlDsigManifestChecks | - * o instanceof at.gv.egovernment.moa.spss.api.xmlverifyManifestRefsCheckResult + * @pre xmlDsigManifestChecks != null implies forall Object o in + * xmlDsigManifestChecks | o instanceof + * at.gv.egovernment.moa.spss.api.xmlverifyManifestRefsCheckResult * @pre certificateCheck != null * @post return != null */ public abstract VerifyXMLSignatureResponse createVerifyXMLSignatureResponse( - SignerInfo signerInfo, - List hashInputDatas, - List referenceInputDatas, - ReferencesCheckResult signatureCheck, - ReferencesCheckResult signatureManifestCheck, - List xmlDsigManifestChecks, - CheckResult certificateCheck, - List adesFormResults, - ExtendedCertificateCheckResult extCheckResult, - String signatureAlgorithm); + SignerInfo signerInfo, + List hashInputDatas, + List referenceInputDatas, + ReferencesCheckResult signatureCheck, + ReferencesCheckResult signatureManifestCheck, + List xmlDsigManifestChecks, + CheckResult certificateCheck, + List adesFormResults, + ExtendedCertificateCheckResult extCheckResult, + String signatureAlgorithm); /** * Create a new ReferencesCheckResult object. - * + * * @param code The status code. * @param info Additional information about the reference check. * @return The ReferencesCheckResult containing the above data. - * + * * @pre code >= 0 * @post return != null */ public abstract ReferencesCheckResult createReferencesCheckResult( - int code, - ReferencesCheckResultInfo info); + int code, + ReferencesCheckResultInfo info); /** * Create a new ReferencesCheckResultInfo object. - * - * @param anyOtherInfo Arbitrary XML content describing the check result. - * May be null. - * @param failedReferences The indexes of the failed references. May be - * null. - * @return The ReferencesCheckResultInfo containing the above - * data. - * + * + * @param anyOtherInfo Arbitrary XML content describing the check result. + * May be null. + * @param failedReferences The indexes of the failed references. May be + * null. + * @return The ReferencesCheckResultInfo containing the above data. + * * @post return != null */ public abstract ReferencesCheckResultInfo createReferencesCheckResultInfo( - NodeList anyOtherInfo, - int[] failedReferences); + NodeList anyOtherInfo, + int[] failedReferences); /** * Create a new ManifestRefsCheckResult object. - * + * * @param code The status code. * @param info Additional information about the manifest check. May be - * null. - * @return The ManifestRefsCheckResult containing the above - * data. - * + * null. + * @return The ManifestRefsCheckResult containing the above data. + * * @pre code >= 0 * @post return != null */ public abstract ManifestRefsCheckResult createManifestRefsCheckResult( - int code, - ManifestRefsCheckResultInfo info); + int code, + ManifestRefsCheckResultInfo info); /** * Create a new ManifestRefsCheckResultInfo object. - * - * @param anyOtherInfo Arbitrary XML content describing the check result. - * May be null. - * @param failedReferences The indexes of the failed references. May be - * null. + * + * @param anyOtherInfo Arbitrary XML content describing the check + * result. May be null. + * @param failedReferences The indexes of the failed references. May be + * null. * @param referringSigReference The index of the reference in the signature. - * @return The ManifestRefsCheckResultInfo containing the - * above data. - * + * @return The ManifestRefsCheckResultInfo containing the above + * data. + * * @pre referringSigReference > 0 * @post return != null */ public abstract ManifestRefsCheckResultInfo createManifestRefsCheckResultInfo( - NodeList anyOtherInfo, - int[] failedReferences, - int referringSigReference); + NodeList anyOtherInfo, + int[] failedReferences, + int referringSigReference); // // Factory methods for common objects @@ -948,10 +934,10 @@ public abstract class SPSSFactory { /** * Create a new Content object referencing data via a URI. - * + * * @param referenceURI The URI pointing to the content. * @return The Content object containing the reference. - * + * * @pre referenceURI != null && referenceURI.length() > 0 * @post return != null */ @@ -959,41 +945,43 @@ public abstract class SPSSFactory { /** * Create a new Content object containing binary data. - * - * @param binaryData An InputStream containing the binary data. + * + * @param binaryData An InputStream containing the binary data. * @param referenceURI An URI identifying the data. May be null. * @return The Content object containing the data. - * + * * @pre binaryData != null * @post return != null */ public abstract Content createContent( - InputStream binaryData, - String referenceURI); + InputStream binaryData, + String referenceURI); /** - * Create a new Content object containing location reference data. - * - * @param locationReferenceURI a URI pointing to the actual remote location of the content. - * - * @param referenceURI An URI identifying the data. May be null. - * - * @return The Content object containing the data. - * - * @pre locationReferenceURI != null - * @post return != null - */ - public abstract Content createContent( - String locationReferenceURI, - String referenceURI); + * Create a new Content object containing location reference data. + * + * @param locationReferenceURI a URI pointing to the actual remote location of + * the content. + * + * @param referenceURI An URI identifying the data. May be + * null. + * + * @return The Content object containing the data. + * + * @pre locationReferenceURI != null + * @post return != null + */ + public abstract Content createContent( + String locationReferenceURI, + String referenceURI); /** * Create a new Content object containing XML data. - * - * @param xmlData The XML data contained in the new Content. + * + * @param xmlData The XML data contained in the new Content. * @param referenceURI An URI identifying the data. May be null. * @return The Content object containing the data. - * + * * @pre xmlData != null * @post return != null */ @@ -1001,13 +989,11 @@ public abstract class SPSSFactory { /** * Create a new XMLDataObjectAssociation object. - * - * @param metaInfo Information about the content type. May be - * null. - * @param content The Content object containing the data. - * @return The XMLDataObjectAssociation containing the above - * data. - * + * + * @param metaInfo Information about the content type. May be null. + * @param content The Content object containing the data. + * @return The XMLDataObjectAssociation containing the above data. + * * @pre content != null * @pre content.getContentType() == Content.CONTENT_XML || * content.getContentType() == Contetn.CONTENT_BINARY @@ -1015,34 +1001,36 @@ public abstract class SPSSFactory { * @post return != null */ public abstract XMLDataObjectAssociation createXMLDataObjectAssociation( - MetaInfo metaInfo, - Content content); + MetaInfo metaInfo, + Content content); /** * Create a new MetaInfo object. - * - * @param mimeType The MIME type part of the meta information. + * + * @param mimeType The MIME type part of the meta information. * @param description Descriptive meta information. May be null. - * @param otherInfo XML meta information. May be null. - * @param type Type information for XML signature creation. May be null. + * @param otherInfo XML meta information. May be null. + * @param type Type information for XML signature creation. May be + * null. * @return The MetaInfo object containing the above data. - * + * * @pre mimeType != null && mimeType.length() > 0 - * @pre otherInfo != null implies - * forall Node n in otherInfo | n.getNodeType() == Node.ELEMENT + * @pre otherInfo != null implies forall Node n in otherInfo | n.getNodeType() + * == Node.ELEMENT */ public abstract MetaInfo createMetaInfo( - String mimeType, - String description, - NodeList otherInfo, - String type); + String mimeType, + String description, + NodeList otherInfo, + String type); /** - * Create a CanonicalizationTransform type of Transform. - * + * Create a CanonicalizationTransform type of + * Transform. + * * @param algorithmURI The algorithm URI of the canonicalization. * @return The created CanonicalizationTransform object. - * + * * @pre CanonicalizationTransform.CANONICAL_XML.equals(algorithmURI) || * CanonicalizationTransform.CANONICAL_XML_WITH_COMMENTS.equals(algorithmURI) * @post return != null @@ -1052,95 +1040,95 @@ public abstract class SPSSFactory { /** * Create an ExclusiveCanonicalizationTransform type of * Transform. - * - * @param algorithmURI The algorithm URI of the exclusive canonicalization. - * @param inclusiveNamespacePrefixes The prefixes of the namespaces to - * treat according to canonical XML. + * + * @param algorithmURI The algorithm URI of the exclusive + * canonicalization. + * @param inclusiveNamespacePrefixes The prefixes of the namespaces to treat + * according to canonical XML. * @return The new ExclusiveCanonicalizationTransform - * - * @pre ExclusiveCanonicalizationTransform.EXCLUSIVE_CANONICAL_XML.equals(algorithmURI) || + * + * @pre ExclusiveCanonicalizationTransform.EXCLUSIVE_CANONICAL_XML.equals(algorithmURI) + * || * ExclusiveCanonicalizationTransform.EXCLUSIVE_CANONICAL_XML_WITH_COMMENTS.equals(algorithmURI) * @pre inclusiveNamespacePrefixes != null - * @pre forall Object o in inclusiveNamespacePrefixes | o instanceof String + * @pre forall Object o in inclusiveNamespacePrefixes | o instanceof String * @post return != null */ public abstract Transform createExclusiveCanonicalizationTransform( - String algorithmURI, - List inclusiveNamespacePrefixes); + String algorithmURI, + List inclusiveNamespacePrefixes); /** * Create a Base64Transform type of Transform. - * + * * @return A Transform denoting a Base64 decoding. - * + * * @post return != null */ public abstract Transform createBase64Transform(); /** - * Create a EnvelopedSignatureTransform type of + * Create a EnvelopedSignatureTransform type of * Transform. - * + * * @return A Transform denoting an enveloped signature. - * + * * @post return != null */ public abstract Transform createEnvelopedSignatureTransform(); /** * Create an XSLTTransform type of Transform. - * - * @param styleSheet The XSLT stylesheet contained in the - * Transform. + * + * @param styleSheet The XSLT stylesheet contained in the + * Transform. * @return A Transform containing the XSLT stylesheet. - * + * * @post return != null */ public abstract Transform createXSLTTransform(Element styleSheet); /** * Create an XPathTransform type of Transform. - * - * @param xPathExpression The XPath expression to use in the created - * Transform. - * @param namespaceDeclarations The namespace prefix to URI mapping to - * apply on evaluation of the XPath expression. + * + * @param xPathExpression The XPath expression to use in the created + * Transform. + * @param namespaceDeclarations The namespace prefix to URI mapping to apply on + * evaluation of the XPath expression. * @return The XPathTransform containing the above data. - * + * * @pre xPathExpression != null * @pre namespaceDeclarations != null * @post return != null */ public abstract Transform createXPathTransform( - String xPathExpression, - Map namespaceDeclarations); + String xPathExpression, + Map namespaceDeclarations); /** - * Create a new XPathFilter2Transform type of - * Transform. - * + * Create a new XPathFilter2Transform type of + * Transform. + * * @param xPathFilters The filters contained in the newly created - * XPathFilter2Transform. - * @return The XPathFilter2Transform containing the given - * filters. - * - * @pre xPathFilters != null && - * forall Object o in xPathFilters | - * o instanceof at.gv.egovernment.moa.spss.api.common.XPathFilter + * XPathFilter2Transform. + * @return The XPathFilter2Transform containing the given filters. + * + * @pre xPathFilters != null && forall Object o in xPathFilters | o instanceof + * at.gv.egovernment.moa.spss.api.common.XPathFilter * @post return != null */ public abstract Transform createXPathFilter2Transform(List xPathFilters); /** * Create a new XPathFilter object. - * - * @param filterType The type of filter. - * @param xPathExpression The XPath expression contained in this filter. - * @param namespaceDeclarations The namespace prefix to URI mapping to apply - * on evaluation of the XPath expression. + * + * @param filterType The type of filter. + * @param xPathExpression The XPath expression contained in this filter. + * @param namespaceDeclarations The namespace prefix to URI mapping to apply on + * evaluation of the XPath expression. * @return The XPathFilter containing the above data. - * - * @pre XPathFilter.SUBTRACT_TYPE.equals(filterType) || + * + * @pre XPathFilter.SUBTRACT_TYPE.equals(filterType) || * XPathFilter.INTERSECT_TYPE.equals(filterType) || * XPathFilter.UNION_TYPE.equals(filterType) * @pre xPathExpression != null @@ -1148,73 +1136,76 @@ public abstract class SPSSFactory { * @post return != null */ public abstract XPathFilter createXPathFilter( - String filterType, - String xPathExpression, - Map namespaceDeclarations); + String filterType, + String xPathExpression, + Map namespaceDeclarations); /** * Create a new CheckResult object. - * + * * @param code The check code. * @param info Verbose information about the check. May be null. * @return The CheckResult containing the above data. - * + * * @pre code >= 0 * @post return != null */ public abstract CheckResult createCheckResult(int code, NodeList info); - - /** * Create a new SignerInfo object. - * - * @param signerCertificate The signer certificate in binary form. - * @param qualifiedCertificate true, if the signer certificate is - * a qualified certificate, otherwise false. - * @param qcSourceTSL true, if the QC information comes from the TSL, - * otherwise false. - * @param publicAuthority true, if the signer certificate is a - * public authority certificate, otherwise false. - * @param publicAuthorityID The identification of the public authority - * (if publicAuthority is true). May be - * null. - * @param sscd true, if the TSL check verifies the - * signature based on a SSDC, otherwise false. - * @param sscdSourceTSL true, if the SSCD information comes from the TSL, - * otherwise false. - * @param issuerCountryCode contains the signer certificate issuer country code. - * @param tslInfos contains information from Trust-Status List for the signer certificate + * + * @param signerCertificate The signer certificate in binary form. + * @param qualifiedCertificate true, if the signer certificate is a + * qualified certificate, otherwise + * false. + * @param qcSourceTSL true, if the QC information comes + * from the TSL, otherwise false. + * @param publicAuthority true, if the signer certificate is a + * public authority certificate, otherwise + * false. + * @param publicAuthorityID The identification of the public authority (if + * publicAuthority is + * true). May be null. + * @param sscd true, if the TSL check verifies the + * signature based on a SSDC, otherwise + * false. + * @param sscdSourceTSL true, if the SSCD information comes + * from the TSL, otherwise false. + * @param issuerCountryCode contains the signer certificate issuer country + * code. + * @param tslInfos contains information from Trust-Status List for + * the signer certificate * @return The SignerInfo containing the above data. - * + * * @pre signerCertSubjectName != null * @pre signerCertIssuerSerial != null * @pre signerCertificate != null */ public abstract SignerInfo createSignerInfo( - X509Certificate signerCertificate, - boolean qualifiedCertificate, - boolean qcSourceTSL, - boolean publicAuthority, - String publicAuthorityID, - boolean sscd, - boolean sscdSourceTSL, - String issuerCountryCode, - Date signingTime, - TslInfos tslInfos); - + X509Certificate signerCertificate, + boolean qualifiedCertificate, + boolean qcSourceTSL, + boolean publicAuthority, + String publicAuthorityID, + boolean sscd, + boolean sscdSourceTSL, + String issuerCountryCode, + Date signingTime, + TslInfos tslInfos); + /** * Create a new X509IssuerSerial object. - * - * @param issuerName The distinguished name of the issuer. + * + * @param issuerName The distinguished name of the issuer. * @param issuerSerial The certificate serial number. * @return The X509IssuerSerial containing the above data. - * + * * @pre issuerName != null * @pre issuerSerial != null */ public abstract X509IssuerSerial createX509IssuerSerial( - String issuerName, - BigInteger issuerSerial); + String issuerName, + BigInteger issuerSerial); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/SignatureCreationService.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/SignatureCreationService.java index 05271fb..4019ad7 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/SignatureCreationService.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/SignatureCreationService.java @@ -21,18 +21,16 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api; import at.gv.egovernment.moa.spss.MOAException; - import at.gv.egovernment.moa.spss.api.xmlsign.CreateXMLSignatureRequest; import at.gv.egovernment.moa.spss.api.xmlsign.CreateXMLSignatureResponse; import at.gv.egovernment.moa.spss.server.invoke.SignatureCreationServiceImpl; /** * Interface providing functions for signature creation. - * + * * @author Patrick Peck * @version $Id$ */ @@ -40,42 +38,40 @@ public abstract class SignatureCreationService { /** The default implementation class. */ private static final String DEFAULT_IMPLEMENTATION = - "at.gv.egovernment.moa.spss.server.invoke.SignatureCreationServiceImpl"; - - /** The single instance of this class. */ + "at.gv.egovernment.moa.spss.server.invoke.SignatureCreationServiceImpl"; + + /** The single instance of this class. */ private static SignatureCreationService instance = null; /** * Get an instance of the SignatureCreationService. - * + * * @return A concrete instance of the SignatureCreationService. */ public static synchronized SignatureCreationService getInstance() { if (instance == null) { try { - /* - DiscoverClass discover = new DiscoverClass(); - instance = - (SignatureCreationService) discover.newInstance( - SignatureCreationService.class, - DEFAULT_IMPLEMENTATION);*/ + /* + * DiscoverClass discover = new DiscoverClass(); instance = + * (SignatureCreationService) discover.newInstance( + * SignatureCreationService.class, DEFAULT_IMPLEMENTATION); + */ instance = new SignatureCreationServiceImpl(); - } catch (Exception e) { - // this can not happen since we provide a valid default + } catch (final Exception e) { + // this can not happen since we provide a valid default // implementation } } return instance; } - + /** * Create an XML signature. - * + * * @param request Information on how to create the signature. - * @return A CreateXMLSignatureResponse containing the - * signature. + * @return A CreateXMLSignatureResponse containing the signature. * @throws MOAException Error in server side MOA module. */ public abstract CreateXMLSignatureResponse createXMLSignature(CreateXMLSignatureRequest request) - throws MOAException; + throws MOAException; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/SignatureVerificationService.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/SignatureVerificationService.java index 2433e20..7d95d3a 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/SignatureVerificationService.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/SignatureVerificationService.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api; import at.gv.egovernment.moa.spss.MOAException; @@ -33,7 +32,7 @@ import at.gv.egovernment.moa.spss.server.invoke.SignatureVerificationServiceImpl /** * Interface providing functions for verifying signatures. - * + * * @author Patrick Peck * @version $Id$ */ @@ -41,28 +40,27 @@ public abstract class SignatureVerificationService { /** The default implementation class. */ private static final String DEFAULT_IMPLEMENTATION = - "at.gv.egovernment.moa.spss.server.invoke.SignatureVerificationServiceImpl"; + "at.gv.egovernment.moa.spss.server.invoke.SignatureVerificationServiceImpl"; /** The single instance of this class. */ private static SignatureVerificationService instance = null; /** * Get an instance of the SignatureVerificationService. - * - * @return A concrete instance of the - * SignatureVerificationService. + * + * @return A concrete instance of the SignatureVerificationService. */ public static synchronized SignatureVerificationService getInstance() { if (instance == null) { try { - /*DiscoverClass discover = new DiscoverClass(); - instance = - (SignatureVerificationService) discover.newInstance( - SignatureVerificationService.class, - DEFAULT_IMPLEMENTATION);*/ - instance = new SignatureVerificationServiceImpl(); - } catch (Exception e) { - // this can not happen since we provide a valid default + /* + * DiscoverClass discover = new DiscoverClass(); instance = + * (SignatureVerificationService) discover.newInstance( + * SignatureVerificationService.class, DEFAULT_IMPLEMENTATION); + */ + instance = new SignatureVerificationServiceImpl(); + } catch (final Exception e) { + // this can not happen since we provide a valid default // implementation } } @@ -71,23 +69,24 @@ public abstract class SignatureVerificationService { /** * Verify a CMS signature. - * + * * @param request Detailed information on the verification that should be - * performed. + * performed. * @return A VerifyCMSSignatureResponse object that contains - * information about the performed verification. + * information about the performed verification. * @throws MOAException Error in server side MOA module. */ public abstract VerifyCMSSignatureResponse verifyCMSSignature(VerifyCMSSignatureRequest request) - throws MOAException; + throws MOAException; + /** * Verfiy an XML Signature. - * - * @param request information on the verification that should be performed. + * + * @param request information on the verification that should be performed. * @return A VerifyXMLSignatureResponse object that contains - * information about the performed verification. + * information about the performed verification. * @throws MOAException Error in server side MOA module. */ public abstract VerifyXMLSignatureResponse verifyXMLSignature(VerifyXMLSignatureRequest request) - throws MOAException; + throws MOAException; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmssign/CMSSignatureResponse.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmssign/CMSSignatureResponse.java index 10db676..958bd7d 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmssign/CMSSignatureResponse.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmssign/CMSSignatureResponse.java @@ -21,21 +21,19 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.cmssign; - /** * Contains the signature if the signature creation was successful. - * + * * @version $Id$ */ public interface CMSSignatureResponse - extends CreateCMSSignatureResponseElement { - /** + extends CreateCMSSignatureResponseElement { + /** * Gets the CMS signature (Base64 encoded). - * + * * @return The CMS signature */ - public String getCMSSignature(); + String getCMSSignature(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmssign/CreateCMSSignatureRequest.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmssign/CreateCMSSignatureRequest.java index 9d5cd7a..c971451 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmssign/CreateCMSSignatureRequest.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmssign/CreateCMSSignatureRequest.java @@ -21,29 +21,28 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.cmssign; import java.util.List; - /** * Object that encapsulates a request to create a CMS Signature. - * - * + * + * * @version $Id$ */ public interface CreateCMSSignatureRequest { /** * Gets the identifier for the keys to be used for the signature. - * + * * @return The identifier for the keys to be used. */ - public String getKeyIdentifier(); + String getKeyIdentifier(); + /** - * Gets the information of the singleSignatureInfo elements. - * + * Gets the information of the singleSignatureInfo elements. + * * @return The information of singleSignatureInfo elements. */ - public List getSingleSignatureInfos(); + List getSingleSignatureInfos(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmssign/CreateCMSSignatureResponse.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmssign/CreateCMSSignatureResponse.java index 6062a11..e81a2bc 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmssign/CreateCMSSignatureResponse.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmssign/CreateCMSSignatureResponse.java @@ -21,22 +21,21 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.cmssign; import java.util.List; /** - * Object that encapsulates the response on to a + * Object that encapsulates the response on to a * CreateCMSSignatureRequest to create an XML signature. - * + * * @version $Id$ */ public interface CreateCMSSignatureResponse { /** * Gets the response elements. - * + * * @return The response elements. */ - public List getResponseElements(); + List getResponseElements(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmssign/CreateCMSSignatureResponseElement.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmssign/CreateCMSSignatureResponseElement.java index 8e4e611..a8d0ebd 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmssign/CreateCMSSignatureResponseElement.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmssign/CreateCMSSignatureResponseElement.java @@ -21,31 +21,29 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.cmssign; /** - * Base class for CMSSignature and - * ErrorResponse elements in a - * CreateXMLSignatureResponse. - * + * Base class for CMSSignature and ErrorResponse + * elements in a CreateXMLSignatureResponse. + * * @version $Id$ */ public interface CreateCMSSignatureResponseElement { /** * Indicates that this object contains a CMSSignature. */ - public static final int CMS_SIGNATURE = 0; + int CMS_SIGNATURE = 0; /** * Indicates that this objet contains an ErrorResponse. */ - public static final int ERROR_RESPONSE = 1; - + int ERROR_RESPONSE = 1; + /** * Gets the type of response object. - * - * @return The type of response object, either - * CMS_SIGNATURE or ERROR_RESPONSE. + * + * @return The type of response object, either CMS_SIGNATURE or + * ERROR_RESPONSE. */ - public int getResponseType(); + int getResponseType(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmssign/DataObjectInfo.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmssign/DataObjectInfo.java index b9f3630..4f97e5a 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmssign/DataObjectInfo.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmssign/DataObjectInfo.java @@ -21,38 +21,37 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.cmssign; import at.gv.egovernment.moa.spss.api.cmsverify.CMSDataObject; /** * Encapsulates information required to create a single signature. - * + * * @version $Id$ */ public interface DataObjectInfo { /** * Indicates that a detached signature will be created. */ - public static final String STRUCTURE_DETACHED = "detached"; + String STRUCTURE_DETACHED = "detached"; /** * Indicates that an enveloping signature will be created. */ - public static final String STRUCTURE_ENVELOPING = "enveloping"; + String STRUCTURE_ENVELOPING = "enveloping"; /** * Gets the structure of the signature. - * + * * @return The structure of the signature. */ - public String getStructure(); + String getStructure(); /** * Gets information related to a single data object. - * + * * @return Information related to a single data object. */ - public CMSDataObject getDataObject(); - + CMSDataObject getDataObject(); + } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmssign/SingleSignatureInfo.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmssign/SingleSignatureInfo.java index 4d56cf3..2bff558 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmssign/SingleSignatureInfo.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmssign/SingleSignatureInfo.java @@ -21,14 +21,11 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.cmssign; - - /** * Encapsulates data to create a single signature. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -36,24 +33,24 @@ package at.gv.egovernment.moa.spss.api.cmssign; public interface SingleSignatureInfo { /** * Gets the dataObjectInfo information. - * + * * @return The dataObjectInfo information. */ - public DataObjectInfo getDataObjectInfo(); - + DataObjectInfo getDataObjectInfo(); + /** * Check whether a Security Layer conform signature manifest will be created. - * - * @return true, if a Security Layer conform signature manifest - * will be created, false otherwise. + * + * @return true, if a Security Layer conform signature manifest + * will be created, false otherwise. */ - public boolean isSecurityLayerConform(); - + boolean isSecurityLayerConform(); + /** - * Check whether a PAdES conform CAdES signature will be created - * - * @return true, if a PAdES conform CAdES signature - * will be created, false otherwise. + * Check whether a PAdES conform CAdES signature will be created + * + * @return true, if a PAdES conform CAdES signature will be + * created, false otherwise. */ - public boolean isPAdESConform(); + boolean isPAdESConform(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/CMSContent.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/CMSContent.java index 4c2c1cc..f240da8 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/CMSContent.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/CMSContent.java @@ -21,12 +21,11 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.cmsverify; /** * Base class for objects containing CMS content. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -35,18 +34,18 @@ public interface CMSContent { /** * Indicates that this object contains a reference to the CMS content. */ - public static final int REFERENCE_CONTENT = 0; + int REFERENCE_CONTENT = 0; /** * Indicates that this object contains the CMS content explicitly. */ - public static final int EXPLICIT_CONTENT = 1; - + int EXPLICIT_CONTENT = 1; + /** * Gets the type of the contained content. - * + * * @return The type of content, either REFERENCE_CONTENT or - * EXPLICIT_CONTENT. + * EXPLICIT_CONTENT. */ - public int getContentType(); - + int getContentType(); + } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/CMSContentExcplicit.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/CMSContentExcplicit.java index 7fc6029..1c6506c 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/CMSContentExcplicit.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/CMSContentExcplicit.java @@ -21,14 +21,13 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.cmsverify; import java.io.InputStream; /** * Encapsulates binary CMS content. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -36,8 +35,8 @@ import java.io.InputStream; public interface CMSContentExcplicit extends CMSContent { /** * Gets the content as a stream. - * + * * @return A stream containing the binary content. */ - public InputStream getBinaryContent(); + InputStream getBinaryContent(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/CMSContentReference.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/CMSContentReference.java index ade197d..c7366ff 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/CMSContentReference.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/CMSContentReference.java @@ -21,12 +21,11 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.cmsverify; /** * Encapsulates CMS content that is referenced by an URI. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -34,8 +33,8 @@ package at.gv.egovernment.moa.spss.api.cmsverify; public interface CMSContentReference extends CMSContent { /** * Gets the reference URI from wher the content can be retrieved. - * + * * @return The reference URI. */ - public String getReference(); + String getReference(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/CMSDataObject.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/CMSDataObject.java index f9a6846..ffd31e1 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/CMSDataObject.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/CMSDataObject.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.cmsverify; import java.math.BigDecimal; @@ -30,7 +29,7 @@ import at.gv.egovernment.moa.spss.api.common.MetaInfo; /** * A data object used for verification of CMS signatures. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -38,20 +37,20 @@ import at.gv.egovernment.moa.spss.api.common.MetaInfo; public interface CMSDataObject { /** * Gets the meta information of the content. - * + * * @return An object containig the meta information. */ - public MetaInfo getMetaInfo(); + MetaInfo getMetaInfo(); + /** * Gets the actual content of the data object. - * + * * @return The actual content. */ - public CMSContent getContent(); - - - public BigDecimal getExcludeByteRangeFrom(); - - public BigDecimal getExcludeByteRangeTo(); - - } + CMSContent getContent(); + + BigDecimal getExcludeByteRangeFrom(); + + BigDecimal getExcludeByteRangeTo(); + +} diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/VerifyCMSSignatureRequest.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/VerifyCMSSignatureRequest.java index 6294fb1..5ce51cf 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/VerifyCMSSignatureRequest.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/VerifyCMSSignatureRequest.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.cmsverify; import java.io.InputStream; @@ -29,7 +28,7 @@ import java.util.Date; /** * Object that encapsulates a request to verify a CMS signature. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -38,42 +37,48 @@ public interface VerifyCMSSignatureRequest { /** * Indicates, that signature checks for all signatories must be returned. */ - public static int[] ALL_SIGNATORIES = new int[] { -1 }; + int[] ALL_SIGNATORIES = new int[] { -1 }; + /** * Gets the positions of signatories whose signature must be verified. - * + * * @return The positions of signatories. */ - public int[] getSignatories(); + int[] getSignatories(); + /** - * Gets the date and time for which the signature verification has to - * be performed. - * - * @return Date and time for which the signature verification has - * to be performed. + * Gets the date and time for which the signature verification has to be + * performed. + * + * @return Date and time for which the signature verification has to be + * performed. */ - public Date getDateTime(); + Date getDateTime(); + /** * Gets the binary CMS signature. - * - * @return An InputStream from which the binary CMS signature - * can be read. + * + * @return An InputStream from which the binary CMS signature can + * be read. */ - public InputStream getCMSSignature(); - /** + InputStream getCMSSignature(); + + /** * Gets the data object necessary for the verification. - * + * * @return The data object necessary for verification. */ - public CMSDataObject getDataObject(); + CMSDataObject getDataObject(); + /** * Gets the profile ID of trusted certificates to be used for signature * verification. - * + * * @return The profile ID of trusted certificates. */ - public String getTrustProfileId(); - - public boolean isPDF(); - public boolean isExtended(); + String getTrustProfileId(); + + boolean isPDF(); + + boolean isExtended(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/VerifyCMSSignatureResponse.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/VerifyCMSSignatureResponse.java index 33924cb..9f58c43 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/VerifyCMSSignatureResponse.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/VerifyCMSSignatureResponse.java @@ -21,16 +21,13 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.cmsverify; import java.util.List; - /** - * Object that encapsulates the response on a request to verify a CMS - * signature. - * + * Object that encapsulates the response on a request to verify a CMS signature. + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -38,8 +35,8 @@ import java.util.List; public interface VerifyCMSSignatureResponse { /** * Gets the response elements. - * - * @return The response elements. + * + * @return The response elements. */ - public List getResponseElements(); + List getResponseElements(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/VerifyCMSSignatureResponseElement.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/VerifyCMSSignatureResponseElement.java index ec540bf..35bdf6e 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/VerifyCMSSignatureResponseElement.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/cmsverify/VerifyCMSSignatureResponseElement.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.cmsverify; import java.util.List; @@ -32,7 +31,7 @@ import at.gv.egovernment.moa.spss.api.common.SignerInfo; /** * Contains detailed information about the verification of a signature. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -40,37 +39,39 @@ import at.gv.egovernment.moa.spss.api.common.SignerInfo; public interface VerifyCMSSignatureResponseElement { /** * Gets a SignerInfo element according to CMS. - * + * * @return The SignerInfo element according to CMS. */ - public SignerInfo getSignerInfo(); + SignerInfo getSignerInfo(); + /** * Gets the result of the signature verification. - * + * * @return The result of the signature verification. */ - public CheckResult getSignatureCheck(); + CheckResult getSignatureCheck(); + /** * Gets the result of the certificate verification. - * + * * @return The result of the certificate verification. */ - public CheckResult getCertificateCheck(); - + CheckResult getCertificateCheck(); + /** * Gets AdES Form results - * + * * This might be null! - * + * * @return The result of the AdES Form validation */ - public List getAdESFormResults(); - - public ExtendedCertificateCheckResult getExtendedCertificateCheck(); - - public String getSignatureAlgorithm(); - - public Boolean getCoversFullDocument(); - - public int[] getByteRangeOfSignature(); + List getAdESFormResults(); + + ExtendedCertificateCheckResult getExtendedCertificateCheck(); + + String getSignatureAlgorithm(); + + Boolean getCoversFullDocument(); + + int[] getByteRangeOfSignature(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/Base64Transform.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/Base64Transform.java index 6050d5b..e1c650f 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/Base64Transform.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/Base64Transform.java @@ -21,17 +21,16 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.common; /** * A Transform performing a Base64 decoding. - * + * * @author Patrick Peck * @version $Id$ */ public interface Base64Transform extends Transform { /** Algorithm URI of the Base64 Transform type. */ - public static final String BASE64_DECODING = - "http://www.w3.org/2000/09/xmldsig#base64"; + String BASE64_DECODING = + "http://www.w3.org/2000/09/xmldsig#base64"; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/CanonicalizationTransform.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/CanonicalizationTransform.java index 05977c5..680061d 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/CanonicalizationTransform.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/CanonicalizationTransform.java @@ -21,21 +21,20 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.common; import at.gv.egovernment.moaspss.util.Constants; /** * A canonicalization type of Transform. - * + * * @author Patrick Peck * @version $Id$ */ public interface CanonicalizationTransform extends Transform { /** Algorithm URI of canonical XML. */ - public static final String CANONICAL_XML = Constants.C14N_URI; + String CANONICAL_XML = Constants.C14N_URI; /** Algorithm URI of canonical XML with comments. */ - public static final String CANONICAL_XML_WITH_COMMENTS = - Constants.C14N_WITH_COMMENTS_URI; + String CANONICAL_XML_WITH_COMMENTS = + Constants.C14N_WITH_COMMENTS_URI; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/CheckResult.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/CheckResult.java index 5c94981..4a9ff27 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/CheckResult.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/CheckResult.java @@ -21,14 +21,13 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.common; import org.w3c.dom.NodeList; /** * Object encapsulating the result of a signature verification. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -36,14 +35,15 @@ import org.w3c.dom.NodeList; public interface CheckResult { /** * Gets the result code. - * + * * @return The result code. */ - public int getCode(); + int getCode(); + /** * Gets descriptive information. - * + * * @return Descriptive information. */ - public NodeList getInfo(); + NodeList getInfo(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/Content.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/Content.java index efde1eb..d9adb68 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/Content.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/Content.java @@ -21,12 +21,11 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.common; /** * Encapsulates content data. - * + * * @author Patrick Peck * @author Stephan Grill * @author Gregor Karlinger @@ -35,37 +34,38 @@ package at.gv.egovernment.moa.spss.api.common; public interface Content { /** - * Indicates that this object contains a URI reference to some content. + * Indicates that this object contains a URI reference to some content. */ - public static final int REFERENCE_CONTENT = 0; + int REFERENCE_CONTENT = 0; /** * Indicates that this object contains binary content. */ - public static final int BINARY_CONTENT = 1; + int BINARY_CONTENT = 1; /** * Indicates that this object contains XML content. */ - public static final int XML_CONTENT = 2; - + int XML_CONTENT = 2; + /** * Indicates that this object contains a location reference content. */ - public static final int LOCREF_CONTENT = 3; + int LOCREF_CONTENT = 3; /** * Gets the type of content contained in this object. - * - * @return The type of content, one of BINARY_CONTENT, XML_CONTENT, + * + * @return The type of content, one of BINARY_CONTENT, + * XML_CONTENT, * REFERENCE_CONTENT or LOCREF_CONTENT. */ - public int getContentType(); + int getContentType(); /** * Gets the reference to the content data (a URI). - * + * * @return The reference to the content data. */ - public String getReference(); + String getReference(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ContentBinary.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ContentBinary.java index 77ec9dd..a30c5f8 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ContentBinary.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ContentBinary.java @@ -21,14 +21,13 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.common; import java.io.InputStream; /** * Encapsulates binary content. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -36,10 +35,10 @@ import java.io.InputStream; public interface ContentBinary extends Content { /** * Get the binary content. - * - * @return An InputStream from which the binary content can - * be read. + * + * @return An InputStream from which the binary content can be + * read. */ - public InputStream getBinaryContent(); - + InputStream getBinaryContent(); + } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ContentLocRef.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ContentLocRef.java index d1ef096..59c96cb 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ContentLocRef.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ContentLocRef.java @@ -21,21 +21,20 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.common; /** * Encapsulates location reference content. - * + * * @author Gregor Karlinger * @version $Id$ */ -public interface ContentLocRef extends Content -{ +public interface ContentLocRef extends Content { /** - * Gets the location reference URI pointing to the actual remote location of the content. - * + * Gets the location reference URI pointing to the actual remote location of the + * content. + * * @return the location reference URI. */ - public String getLocationReferenceURI(); + String getLocationReferenceURI(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ContentReference.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ContentReference.java index 8c4a658..5650939 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ContentReference.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ContentReference.java @@ -21,12 +21,11 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.common; /** * Content containing a reference to content data. - * + * * @author Patrick Peck * @version $Id$ */ diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ContentXML.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ContentXML.java index d41f6a6..1f294b1 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ContentXML.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ContentXML.java @@ -21,14 +21,13 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.common; import org.w3c.dom.NodeList; /** * Encapsulates arbitrary XML content. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -36,8 +35,8 @@ import org.w3c.dom.NodeList; public interface ContentXML extends Content { /** * Gets the XML content stored in this object. - * + * * @return The XML content. */ - public NodeList getXMLContent(); + NodeList getXMLContent(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ElementSelector.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ElementSelector.java index b446c5f..9d29d9b 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ElementSelector.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ElementSelector.java @@ -21,32 +21,32 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.common; import java.util.Map; /** - * A class containing data for selecting single elements using an XPath + * A class containing data for selecting single elements using an XPath * expression. - * + * * Derived classes are used to point to the CreateSignatureLocation * and the VerifySignatureLocation. - * + * * @author Patrick Peck * @version $Id$ */ public interface ElementSelector { /** * Gets the XPath expression pointing to a single element. - * + * * @return The XPath expression to select the signature parent element. */ - public String getXPathExpression(); + String getXPathExpression(); + /** * Gets the namespace prefix to URI mapping to use when evaluating the XPath. - * + * * @return The namespace prefix to URI mapping. */ - public Map getNamespaceDeclarations(); + Map getNamespaceDeclarations(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/EnvelopedSignatureTransform.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/EnvelopedSignatureTransform.java index 8e6de87..816576a 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/EnvelopedSignatureTransform.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/EnvelopedSignatureTransform.java @@ -21,12 +21,11 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.common; /** * An enveloped signature type of Transform. - * + * * @author Patrick Peck * @version $Id$ */ @@ -34,6 +33,6 @@ public interface EnvelopedSignatureTransform extends Transform { /** * Algorithm URI of the enveloped signature type of Transform. */ - public static final String ENVELOPED_SIGNATURE = - "http://www.w3.org/2000/09/xmldsig#enveloped-signature"; + String ENVELOPED_SIGNATURE = + "http://www.w3.org/2000/09/xmldsig#enveloped-signature"; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ExclusiveCanonicalizationTransform.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ExclusiveCanonicalizationTransform.java index 557ff21..18e452c 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ExclusiveCanonicalizationTransform.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ExclusiveCanonicalizationTransform.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.common; import java.util.List; @@ -30,22 +29,22 @@ import at.gv.egovernment.moaspss.util.Constants; /** * An exclusive canonicalization type of Transform. - * + * * @author Patrick Peck * @version $Id$ */ public interface ExclusiveCanonicalizationTransform extends Transform { /** Algorithm URI of exclusive canonical XML. */ - public static final String EXCLUSIVE_CANONICAL_XML = Constants.EXC_C14N_URI; + String EXCLUSIVE_CANONICAL_XML = Constants.EXC_C14N_URI; /** Algorithm URI of exclusive canonical XML with comments. */ - public static final String EXCLUSIVE_CANONICAL_XML_WITH_COMMENTS = - Constants.EXC_C14N_WITH_COMMENTS_URI; + String EXCLUSIVE_CANONICAL_XML_WITH_COMMENTS = + Constants.EXC_C14N_WITH_COMMENTS_URI; /** * Sets the namespace prefixes that are handled in the same manner as in * canonical XML. - * + * * @return The inclusive namespace prefixes. */ - public List getInclusiveNamespacePrefixes(); + List getInclusiveNamespacePrefixes(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ExtendedCertificateCheckResult.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ExtendedCertificateCheckResult.java index 494b216..afc783e 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ExtendedCertificateCheckResult.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/ExtendedCertificateCheckResult.java @@ -1,33 +1,31 @@ package at.gv.egovernment.moa.spss.api.common; -import org.w3c.dom.NodeList; - public interface ExtendedCertificateCheckResult { - /** - * Gets the result code. - * - * @return The result code. - */ - public int getMajorCode(); + /** + * Gets the result code. + * + * @return The result code. + */ + int getMajorCode(); - /** - * Gets descriptive information. - * - * @return Descriptive information. - */ - public String getMajorInfo(); + /** + * Gets descriptive information. + * + * @return Descriptive information. + */ + String getMajorInfo(); - /** - * Gets the result code. - * - * @return The result code. - */ - public int getMinorCode(); + /** + * Gets the result code. + * + * @return The result code. + */ + int getMinorCode(); - /** - * Gets descriptive information. - * - * @return Descriptive information. - */ - public String getMinorInfo(); + /** + * Gets descriptive information. + * + * @return Descriptive information. + */ + String getMinorInfo(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/InputData.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/InputData.java index 8f8a714..b9c75bb 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/InputData.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/InputData.java @@ -21,45 +21,42 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.common; /** - * Interface specifying accessors for two attributes needed for returning - * HashInputData and ReferenceInputData information - * as part of VerifyXMLSignatureResponse. - * + * Interface specifying accessors for two attributes needed for returning + * HashInputData and ReferenceInputData information as + * part of VerifyXMLSignatureResponse. + * * @author Gregor Karlinger - * + * * @version $Id$ */ -public interface InputData extends Content -{ +public interface InputData extends Content { /** - * Possible value returned by {@link #getPartOf}. + * Possible value returned by {@link #getPartOf}. */ - public static String CONTAINER_SIGNEDINFO_ = "SignedInfo"; + String CONTAINER_SIGNEDINFO_ = "SignedInfo"; /** - * Possible value returned by {@link #getPartOf}. + * Possible value returned by {@link #getPartOf}. */ - public static String CONTAINER_XMLDSIGMANIFEST_ = "XMLDSIGManifest"; - + String CONTAINER_XMLDSIGMANIFEST_ = "XMLDSIGManifest"; + /** * Value returned by {link getReferringReferenceNumber}, signalling that the * attribute is not used. */ - public static int REFERER_NONE_ = -1; - + int REFERER_NONE_ = -1; + /** - * Returns a String signalling what kind of container the - * XMLDSIG Reference this InputData belongs - * to is part of. - * - * @return the kind of container. + * Returns a String signalling what kind of container the XMLDSIG + * Reference this InputData belongs to is part of. + * + * @return the kind of container. */ - public String getPartOf(); - + String getPartOf(); + /** * If this InputData belongs to an XMLDSIG Reference * being part of either a XMLDSIGManifest or a SignatureManifest, this method @@ -67,14 +64,14 @@ public interface InputData extends Content * of the XMLDSIG SignedInfo referring to the XMLDSIGManifest or * SignatureManifest respectively. */ - public int getReferringReferenceNumber(); - - + int getReferringReferenceNumber(); + /** - * Returns an identifier of the hash algorithm that is used to hash this {@link InputData} - * + * Returns an identifier of the hash algorithm that is used to hash this + * {@link InputData} + * * @return */ - public String getHashAlgorithm(); - + String getHashAlgorithm(); + } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/MetaInfo.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/MetaInfo.java index 2413229..8c1b270 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/MetaInfo.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/MetaInfo.java @@ -21,14 +21,13 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.common; import org.w3c.dom.NodeList; /** * Object encapsulating descriptive meta information. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -36,26 +35,29 @@ import org.w3c.dom.NodeList; public interface MetaInfo { /** * Gets the mime type of the associated object. - * + * * @return The mimetype of the associated object. */ - public String getMimeType(); + String getMimeType(); + /** * Gets the descriptive information (URI). - * + * * @return URI referencing the descriptive information. */ - public String getDescription(); + String getDescription(); + /** * Gets the elemental informations. - * + * * @return The elemental informations. - */ - public NodeList getAnyElements(); + */ + NodeList getAnyElements(); + /** * Gets the XML signature creation type information of the associated object. - * + * * @return the XML signature creation type information of the associated object. */ - public String getType(); + String getType(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/SignerInfo.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/SignerInfo.java index bb3dfdf..07b5f7f 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/SignerInfo.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/SignerInfo.java @@ -21,16 +21,14 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.common; import java.security.cert.X509Certificate; import java.util.Date; - /** * Contains information about the signer. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -38,65 +36,69 @@ import java.util.Date; public interface SignerInfo { /** * Gets the signer certificate. - * + * * @return The signer certificate. - */ - public X509Certificate getSignerCertificate(); + */ + X509Certificate getSignerCertificate(); + /** * Checks, whether the certificate contained in this object is qualified. - * + * * @return true, if the certificate is qualified, otherwise - * false. + * false. */ - public boolean isQualifiedCertificate(); - - + boolean isQualifiedCertificate(); + /** * Checks, whether the signature is based on a SSCD. - * + * * @return true, if the signature is based on a SSCD, otherwise - * false. + * false. */ - public boolean isSSCD(); - + boolean isSSCD(); + /** - * Returns the source of the SSCD check (TSL or Certificate) * + * Returns the source of the SSCD check (TSL or Certificate) * */ - public String getSSCDSource(); + String getSSCDSource(); /** - * Returns the source of the QC check (TSL or Certificate) * + * Returns the source of the QC check (TSL or Certificate) * */ - public String getQCSource(); + String getQCSource(); /** * Returns the signer certificate issuer country code + * * @return */ - public String getIssuerCountryCode(); + String getIssuerCountryCode(); + /** - * Checks, whether the certificate contained in this object is a - * public authority certificate. - * - * @return true, if the certificate is a public authority - * certificate, otherwise false. + * Checks, whether the certificate contained in this object is a public + * authority certificate. + * + * @return true, if the certificate is a public authority + * certificate, otherwise false. */ - public boolean isPublicAuthority(); + boolean isPublicAuthority(); + /** - * Gets the public authority ID, if the certificate contained in this - * object is from a public authority. - * + * Gets the public authority ID, if the certificate contained in this object is + * from a public authority. + * * @return The public authority ID. - */ - public String getPublicAuhtorityID(); + */ + String getPublicAuhtorityID(); + + Date getSigningTime(); - public Date getSigningTime(); - /** * Gets information from the Trust-Status List for this certificate - * - * @return {@link TslInfos} if the certificate is on the Trust-Status List, otherwise null + * + * @return {@link TslInfos} if the certificate is on the Trust-Status List, + * otherwise null */ - public TslInfos getTslInfos(); - + TslInfos getTslInfos(); + } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/TSLConfiguration.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/TSLConfiguration.java index be6fe4b..8d0a9fa 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/TSLConfiguration.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/TSLConfiguration.java @@ -21,67 +21,64 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.common; - -import iaik.xml.crypto.utils.URI; - import java.util.Date; import java.util.List; +import iaik.xml.crypto.utils.URI; /** * Contains TSL configuration information. - * + * * @author kstranacher */ public interface TSLConfiguration { - - /** Default URL of EU TSL */ - public String DEFAULT_EU_TSL_URL = "https://ec.europa.eu/tools/lotl/eu-lotl.xml"; - - /** Default period (1day=86400000 msec) for update schedule */ - public String DEFAULT_UPDATE_SCHEDULE_PERIOD = "86400000"; - - /** Default start time (2:00 AM) for update schedule */ - public String DEFAULT_UPDATE_SCHEDULE_STARTTIME = "02:00:00"; - - public String DEFAULT_WORKING_DIR = "tslworking"; - + + /** Default URL of EU TSL */ + String DEFAULT_EU_TSL_URL = "https://ec.europa.eu/tools/lotl/eu-lotl.xml"; + + /** Default period (1day=86400000 msec) for update schedule */ + String DEFAULT_UPDATE_SCHEDULE_PERIOD = "86400000"; + + /** Default start time (2:00 AM) for update schedule */ + String DEFAULT_UPDATE_SCHEDULE_STARTTIME = "02:00:00"; + + String DEFAULT_WORKING_DIR = "tslworking"; + /** * Gets the EU TSL URL. - * + * * @return The EU TSL URL. - */ - public String getEuTSLUrl(); + */ + String getEuTSLUrl(); /** - * + * * @return */ - public Date getUpdateScheduleStartTime(); - + Date getUpdateScheduleStartTime(); + /** - * + * * @return */ - public long getUpdateSchedulePeriod(); - + long getUpdateSchedulePeriod(); + /** - * + * * @return */ - public String getWorkingDirectory(); - + String getWorkingDirectory(); + /** - * + * * @return */ - public URI getWorkingDirectoryAsURI(); - - public List getQualifierForQC(); + URI getWorkingDirectoryAsURI(); + + List getQualifierForQC(); - public List getQualifierForSSCD(); + List getQualifierForSSCD(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/Transform.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/Transform.java index ad050b4..5b924c3 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/Transform.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/Transform.java @@ -21,20 +21,19 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.common; /** * Base class for XMLDsig Transform elements. - * + * * @author Patrick Peck * @version $Id$ */ public interface Transform { /** * Gets the algorithm URI of this Transform. - * + * * @return The algorithm URI of this Transform. */ - public String getAlgorithmURI(); + String getAlgorithmURI(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/TslInfos.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/TslInfos.java index 2a04f96..34d28c4 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/TslInfos.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/TslInfos.java @@ -3,47 +3,49 @@ package at.gv.egovernment.moa.spss.api.common; import java.util.List; /** - * Trust-Status list information for a specific certificate - * All informations and identifiers are according to the Trust-Status List specification - * + * Trust-Status list information for a specific certificate All informations and + * identifiers are according to the Trust-Status List specification + * * @author tlenz * */ public interface TslInfos { - /** - * Gets the issuer country of the TSL - * - * @return - */ - public String getTslIssuerCountry(); - - /** - * Gets the Service-Type Status of the TSP, which issues the analyzed certificate - * - * @return - */ - public String getServiceTypeStatus(); - - /** - * Gets the Service-Type Identifier of the TSP, which issues the analyzed certificate - * - * @return - */ - public String getServiceTypeIdentifier(); - - /** - * Gets additional qualifiers for the analyzed certificate - * - * @return - */ - public List getQualifiers(); - - /** - * Gets additional service information for the analyzed certificate - * - * @return - */ - public List getAdditionalServiceInformation(); - + /** + * Gets the issuer country of the TSL + * + * @return + */ + String getTslIssuerCountry(); + + /** + * Gets the Service-Type Status of the TSP, which issues the analyzed + * certificate + * + * @return + */ + String getServiceTypeStatus(); + + /** + * Gets the Service-Type Identifier of the TSP, which issues the analyzed + * certificate + * + * @return + */ + String getServiceTypeIdentifier(); + + /** + * Gets additional qualifiers for the analyzed certificate + * + * @return + */ + List getQualifiers(); + + /** + * Gets additional service information for the analyzed certificate + * + * @return + */ + List getAdditionalServiceInformation(); + } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/X509IssuerSerial.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/X509IssuerSerial.java index 39ec807..007fbe8 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/X509IssuerSerial.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/X509IssuerSerial.java @@ -21,14 +21,13 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.common; import java.math.BigInteger; /** * Contains an X.509 issuer distinguished name/serial number pair. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -36,14 +35,15 @@ import java.math.BigInteger; public interface X509IssuerSerial { /** * Gets the issuer distinguished name. - * + * * @return The issuer distinguished name. */ - public String getX509IssuerName(); + String getX509IssuerName(); + /** * Gets the issuer serial number. - * + * * @return The issuer serial number. */ - public BigInteger getX509SerialNumber(); + BigInteger getX509SerialNumber(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/XMLDataObjectAssociation.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/XMLDataObjectAssociation.java index fe2a795..7b3f830 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/XMLDataObjectAssociation.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/XMLDataObjectAssociation.java @@ -21,14 +21,12 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.common; - /** * Object encapsulating arbitrary content and optional descriptive meta * information. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -36,14 +34,15 @@ package at.gv.egovernment.moa.spss.api.common; public interface XMLDataObjectAssociation { /** * Gets descriptive meta information. - * + * * @return The descriptive meta information. */ - public MetaInfo getMetaInfo(); + MetaInfo getMetaInfo(); + /** * Gets the actual content. - * + * * @return The content of this association. */ - public Content getContent(); + Content getContent(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/XPathFilter.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/XPathFilter.java index 06a49a2..f3a12dc 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/XPathFilter.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/XPathFilter.java @@ -21,42 +21,43 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.common; import java.util.Map; /** * An XPath expression set operation. - * + * * @author Patrick Peck * @version $Id$ */ public interface XPathFilter { /** Subtract this filter's node set from the resulting node set. */ - public static final String SUBTRACT_TYPE = "subtract"; + String SUBTRACT_TYPE = "subtract"; /** Intersect this filter's node set with the resulting node set. */ - public static final String INTERSECT_TYPE = "intersect"; + String INTERSECT_TYPE = "intersect"; /** Compute the union of this filter's node set and the resulting node set. */ - public static final String UNION_TYPE = "union"; - + String UNION_TYPE = "union"; + /** * Gets the type of this XPathFilter. - * + * * @return The type of this XPathFilter. */ - public String getFilterType(); + String getFilterType(); + /** * Gets the XPath expression for selecting the nodes. - * + * * @return The XPath expression for selecting the nodes. */ - public String getXPathExpression(); + String getXPathExpression(); + /** - * Gets The namespace prefix to URI mapping used during evaluation of the - * XPath expression. - * + * Gets The namespace prefix to URI mapping used during evaluation of the XPath + * expression. + * * @return The namespace prefix to URI mapping. */ - public Map getNamespaceDeclarations(); + Map getNamespaceDeclarations(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/XPathFilter2Transform.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/XPathFilter2Transform.java index 6f05710..b5899a4 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/XPathFilter2Transform.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/XPathFilter2Transform.java @@ -21,29 +21,28 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.common; import java.util.List; /** * An XPath type of Transform containing multiple filters for - * performing set operations on XPath selections. - * + * performing set operations on XPath selections. + * * @author Patrick Peck * @version $Id$ */ public interface XPathFilter2Transform extends Transform { /** Algorithm URI for the XPath Filter2 Transform. */ - public static final String XPATH_FILTER2 = - "http://www.w3.org/2002/06/xmldsig-filter2"; + String XPATH_FILTER2 = + "http://www.w3.org/2002/06/xmldsig-filter2"; /** - * Gets the XPathFilters contained in this + * Gets the XPathFilters contained in this * XPathFilter2Transform. - * + * * @return The XPathFilters. */ - public List getFilters(); + List getFilters(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/XPathTransform.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/XPathTransform.java index 99eda2a..41227c5 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/XPathTransform.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/XPathTransform.java @@ -21,34 +21,34 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.common; import java.util.Map; /** * A Transform performing an XPath selection. - * + * * @author Patrick Peck * @version $Id$ */ public interface XPathTransform extends Transform { /** Algorithm URI of the XPath Transform. */ - public static final String XPATH = - "http://www.w3.org/TR/1999/REC-xpath-19991116"; + String XPATH = + "http://www.w3.org/TR/1999/REC-xpath-19991116"; /** * Gets the XPath expression used for selection. - * + * * @return The XPath expression used for selection. */ - public String getXPathExpression(); + String getXPathExpression(); + /** - * Gets The namespace prefix to URI mapping used during evaluation of the - * XPath expression. - * + * Gets The namespace prefix to URI mapping used during evaluation of the XPath + * expression. + * * @return The namespace prefix to URI mapping. */ - public Map getNamespaceDeclarations(); - + Map getNamespaceDeclarations(); + } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/XSLTTransform.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/XSLTTransform.java index 8cb6c8e..bdfd2eb 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/XSLTTransform.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/common/XSLTTransform.java @@ -21,27 +21,26 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.common; import org.w3c.dom.Element; /** * A Transform containing an XSLT stylesheet. - * + * * @author Patrick Peck * @version $Id$ */ public interface XSLTTransform extends Transform { /** Algorithm URI for the XSLT type of Transform. */ - public static final String XSLT = - "http://www.w3.org/TR/1999/REC-xslt-19991116"; + String XSLT = + "http://www.w3.org/TR/1999/REC-xslt-19991116"; /** * Gets the XSLT stylesheet element used for the transformation. - * + * * @return The XSLT stylesheet element used for the transformation. */ - public Element getStylesheet(); + Element getStylesheet(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/AdESFormResultsImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/AdESFormResultsImpl.java index c186c54..46710c0 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/AdESFormResultsImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/AdESFormResultsImpl.java @@ -4,39 +4,39 @@ import at.gv.egovernment.moa.spss.api.xmlverify.AdESFormResults; public class AdESFormResultsImpl implements AdESFormResults { - private Integer code; - private String info; - private String name; - - public synchronized void setCode(Integer code) { - this.code = code; - } - - public synchronized void setInfo(String info) { - this.info = info; - } - - public synchronized void setName(String name) { - this.name = name; - } - - @Override - public Integer getCode() { - return this.code; - } - - @Override - public String getInfo() { - return this.info; - } - - @Override - public String getName() { - return this.name; - } - - @Override - public String toString() { - return "AdESFormResultsImpl [code=" + code + ", info=" + info + ", name=" + name + "]"; - } + private Integer code; + private String info; + private String name; + + public synchronized void setCode(Integer code) { + this.code = code; + } + + public synchronized void setInfo(String info) { + this.info = info; + } + + public synchronized void setName(String name) { + this.name = name; + } + + @Override + public Integer getCode() { + return this.code; + } + + @Override + public String getInfo() { + return this.info; + } + + @Override + public String getName() { + return this.name; + } + + @Override + public String toString() { + return "AdESFormResultsImpl [code=" + code + ", info=" + info + ", name=" + name + "]"; + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/Base64TransformImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/Base64TransformImpl.java index f708bab..b08c74c 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/Base64TransformImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/Base64TransformImpl.java @@ -21,20 +21,19 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.common.Base64Transform; /** * Default implementation of Base64Transform. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class Base64TransformImpl - extends TransformImpl - implements Base64Transform { + extends TransformImpl + implements Base64Transform { /** * Create a new Base64TransformImpl object. diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CMSContentExplicitImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CMSContentExplicitImpl.java index 8dede90..f6c1574 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CMSContentExplicitImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CMSContentExplicitImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.io.InputStream; @@ -30,33 +29,35 @@ import at.gv.egovernment.moa.spss.api.cmsverify.CMSContentExcplicit; /** * Default implementation of CMSContentExplicit. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class CMSContentExplicitImpl implements CMSContentExcplicit { - + /** The binary content, as a stream. */ private InputStream binaryContent; /** * Sets the binary content as a stream. - * + * * @param content The binary content as a stream. */ public void setBinaryContent(InputStream content) { this.binaryContent = content; } + @Override public InputStream getBinaryContent() { return binaryContent; } /** * Gets the type of content. - * + * * @return EXPLICIT_CONTENT */ + @Override public int getContentType() { return EXPLICIT_CONTENT; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CMSContentReferenceImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CMSContentReferenceImpl.java index fb90c5f..a14ea90 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CMSContentReferenceImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CMSContentReferenceImpl.java @@ -21,40 +21,41 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.cmsverify.CMSContentReference; /** * Default implementation of CMSContentReference. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class CMSContentReferenceImpl implements CMSContentReference { - + /** The reference pointing to the actual data. */ private String reference; /** * Sets the reference URI. - * + * * @param referenceURI The URI pointing to the content data. */ public void setReference(String referenceURI) { this.reference = referenceURI; } + @Override public String getReference() { return reference; } /** * Gets the content type. - * + * * @return REFERENCE_CONTENT */ + @Override public int getContentType() { return REFERENCE_CONTENT; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CMSDataObjectImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CMSDataObjectImpl.java index 20a9b56..e9b4fea 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CMSDataObjectImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CMSDataObjectImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.math.BigDecimal; @@ -32,60 +31,64 @@ import at.gv.egovernment.moa.spss.api.common.MetaInfo; /** * Default implementation of CMLSDataObject. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class CMSDataObjectImpl implements CMSDataObject { - + /** The MetaInfo associated with the CMS data object. */ private MetaInfo metaInfo; /** The CMSContent contained in this data object. */ private CMSContent cmsContent; - + private BigDecimal excludeByteRangeFrom; private BigDecimal excludeByteRangeTo; /** * Sets the meta information associated with the CMS data object. - * + * * @param metaInfo The meta information. */ public void setMetaInfo(MetaInfo metaInfo) { this.metaInfo = metaInfo; } + @Override public MetaInfo getMetaInfo() { return metaInfo; } /** * Sets the data of this CMSDataObject. - * + * * @param cmsContent The actual data of this CMSDataObject. */ public void setContent(CMSContent cmsContent) { this.cmsContent = cmsContent; } + @Override public CMSContent getContent() { return cmsContent; } public void setExcludeByteRangeFrom(BigDecimal excludeByteRangeFrom) { - this.excludeByteRangeFrom = excludeByteRangeFrom; + this.excludeByteRangeFrom = excludeByteRangeFrom; } - + + @Override public BigDecimal getExcludeByteRangeFrom() { - return excludeByteRangeFrom; + return excludeByteRangeFrom; } - + public void setExcludeByteRangeTo(BigDecimal excludeByteRangeTo) { - this.excludeByteRangeTo = excludeByteRangeTo; + this.excludeByteRangeTo = excludeByteRangeTo; } - + + @Override public BigDecimal getExcludeByteRangeTo() { - return excludeByteRangeTo; - } - + return excludeByteRangeTo; + } + } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CMSSignatureResponseImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CMSSignatureResponseImpl.java index b512dd0..77ef137 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CMSSignatureResponseImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CMSSignatureResponseImpl.java @@ -21,42 +21,41 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; -import org.w3c.dom.Element; - import at.gv.egovernment.moa.spss.api.cmssign.CMSSignatureResponse; /** * Default implementation of CMSSignatureResponse. - * + * * @version $Id$ */ public class CMSSignatureResponseImpl - implements CMSSignatureResponse { + implements CMSSignatureResponse { /** The base64 value of the CMS signature. */ private String cmsSignature; - /** + /** * Sets the CMS signature. - * + * * @param cmsSignature The Base64 encoded value CMS signature. */ public void setCMSSignature(String cmsSignature) { this.cmsSignature = cmsSignature; } + @Override public String getCMSSignature() { return cmsSignature; } /** * Gets the type of CreateCMSSignatureResponseElement. - * + * * @return CMS_SIGNATURE */ + @Override public int getResponseType() { return CMS_SIGNATURE; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CanonicalizationTransformImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CanonicalizationTransformImpl.java index f8efe26..e931c4b 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CanonicalizationTransformImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CanonicalizationTransformImpl.java @@ -21,26 +21,25 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.common.CanonicalizationTransform; /** * Default implementation of CanonicalizationTransform. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class CanonicalizationTransformImpl - extends TransformImpl - implements CanonicalizationTransform { - + extends TransformImpl + implements CanonicalizationTransform { + /** * Create a new CanonicalizationTransformImpl object. - * - * @param algorithmURI Algorithm URI of the canonicalization - * Transform type. + * + * @param algorithmURI Algorithm URI of the canonicalization + * Transform type. */ public CanonicalizationTransformImpl(String algorithmURI) { setAlgorithmURI(algorithmURI); diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CheckResultImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CheckResultImpl.java index 5bb6e60..a57c4e6 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CheckResultImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CheckResultImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import org.w3c.dom.NodeList; @@ -30,20 +29,20 @@ import at.gv.egovernment.moa.spss.api.common.CheckResult; /** * Default implementation of CheckResult. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class CheckResultImpl implements CheckResult { /** The result code. */ private int code; - - /** Additional information. */ + + /** Additional information. */ private NodeList info; /** * Sets a result code. - * + * * @param code The result code. */ public void setCode(int code) { @@ -53,13 +52,14 @@ public class CheckResultImpl implements CheckResult { /** * @see at.gv.egovernment.moa.spss.api.common.CheckResult#getCode() */ + @Override public int getCode() { return code; } /** * Sets a descriptive information. - * + * * @param info The descriptive information. */ public void setInfo(NodeList info) { @@ -69,6 +69,7 @@ public class CheckResultImpl implements CheckResult { /** * @see at.gv.egovernment.moa.spss.api.common.CheckResult#getInfo() */ + @Override public NodeList getInfo() { return info; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ContentBinaryImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ContentBinaryImpl.java index 7fe1cf9..aa49375 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ContentBinaryImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ContentBinaryImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.io.InputStream; @@ -30,33 +29,35 @@ import at.gv.egovernment.moa.spss.api.common.ContentBinary; /** * Default implementation of ContentBinary. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class ContentBinaryImpl extends ContentImpl implements ContentBinary { - /** The binary content as a stream. */ + /** The binary content as a stream. */ private InputStream binaryContent; /** * Sets the binary content as a stream. - * + * * @param binaryContent The binary content as a stream. */ public void setBinaryContent(InputStream binaryContent) { this.binaryContent = binaryContent; } + @Override public InputStream getBinaryContent() { return binaryContent; } /** * Gets the type of content. - * + * * @return BINARY_CONTENT */ + @Override public int getContentType() { return BINARY_CONTENT; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ContentImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ContentImpl.java index d061747..4c73795 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ContentImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ContentImpl.java @@ -21,14 +21,13 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.common.Content; /** * Default base class for Content implementations. - * + * * @author Patrick Peck * @version $Id$ */ @@ -38,13 +37,14 @@ public abstract class ContentImpl implements Content { /** * Sets the reference pointing to the content data. - * + * * @param referenceURI The URI of the content data. */ public void setReference(String referenceURI) { this.reference = referenceURI; } + @Override public String getReference() { return reference; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ContentLocRefImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ContentLocRefImpl.java index aa01a93..7d763c1 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ContentLocRefImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ContentLocRefImpl.java @@ -21,47 +21,47 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.common.ContentLocRef; /** * Default implementation of ContentLocRef. - * + * * @author Gregor Karlinger * @version $Id$ */ -public class ContentLocRefImpl extends ContentImpl implements ContentLocRef -{ +public class ContentLocRefImpl extends ContentImpl implements ContentLocRef { /** - * The location reference URI pointing to the actual remote location of the content. + * The location reference URI pointing to the actual remote location of the + * content. */ private String locationReferenceURI_; - - /** + + /** * @see at.gv.egovernment.moa.spss.api.common.ContentLocRef#getLocationReferenceURI() */ - public String getLocationReferenceURI() - { + @Override + public String getLocationReferenceURI() { return locationReferenceURI_; } - + /** - * Sets the location reference URI pointing to the actual remote location of the content. - * + * Sets the location reference URI pointing to the actual remote location of the + * content. + * * @param locationReferenceURI the location reference URI. */ - public void setLocationReferenceURI(String locationReferenceURI) - { + public void setLocationReferenceURI(String locationReferenceURI) { locationReferenceURI_ = locationReferenceURI; } - + /** * Gets the type of content. - * + * * @return LOCREF_CONTENT. */ + @Override public int getContentType() { return LOCREF_CONTENT; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ContentReferenceImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ContentReferenceImpl.java index ab5c3b4..de0e1cf 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ContentReferenceImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ContentReferenceImpl.java @@ -21,26 +21,26 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.common.ContentReference; /** * Default implementation of ContentReference. - * + * * @author Patrick Peck * @version $Id$ */ public class ContentReferenceImpl - extends ContentImpl - implements ContentReference { + extends ContentImpl + implements ContentReference { /** * Gets the type of content. - * + * * @return REFERENCE_CONTENT */ + @Override public int getContentType() { return REFERENCE_CONTENT; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ContentXMLImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ContentXMLImpl.java index dcc1935..496550f 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ContentXMLImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ContentXMLImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import org.w3c.dom.NodeList; @@ -30,7 +29,7 @@ import at.gv.egovernment.moa.spss.api.common.ContentXML; /** * Default implementation of ContentXML. - * + * * @author Fatemeh Philippi * @version $Id$ */ @@ -38,25 +37,27 @@ public class ContentXMLImpl extends ContentImpl implements ContentXML { /** The nodes making up the XML content. */ private NodeList xmlContent; - + /** * Sets the nodes making up the XML content. - * + * * @param xmlContent The XML content. */ public void setXMLContent(NodeList xmlContent) { this.xmlContent = xmlContent; } + @Override public NodeList getXMLContent() { return xmlContent; } /** * Gets the type of content. - * + * * @return XML_CONTENT */ + @Override public int getContentType() { return XML_CONTENT; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateCMSSignatureRequestImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateCMSSignatureRequestImpl.java index e8408bc..dcdb77f 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateCMSSignatureRequestImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateCMSSignatureRequestImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.util.ArrayList; @@ -32,44 +31,46 @@ import at.gv.egovernment.moa.spss.api.cmssign.CreateCMSSignatureRequest; /** * Default implementation of CreateCMSSignatureRequest. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class CreateCMSSignatureRequestImpl - implements CreateCMSSignatureRequest { + implements CreateCMSSignatureRequest { - /** The identifier for selecting the private keys for creating the signature.*/ + /** The identifier for selecting the private keys for creating the signature. */ private String keyIdentifier; /** Information for creating a single signature. */ private List singleSignatureInfos = new ArrayList(); /** - * Sets the identifier for selecting the private keys for creating the + * Sets the identifier for selecting the private keys for creating the * signature. - * + * * @param keyIdentifier The identifier for selecting the private keys. */ public void setKeyIdentifier(String keyIdentifier) { this.keyIdentifier = keyIdentifier; } + @Override public String getKeyIdentifier() { return keyIdentifier; } /** * Sets the information for creating single signatures. - * + * * @param singleSignaureInfos The information for creating single signatures. */ public void setSingleSignatureInfos(List singleSignaureInfos) { this.singleSignatureInfos = - singleSignaureInfos != null - ? Collections.unmodifiableList(new ArrayList(singleSignaureInfos)) - : null; + singleSignaureInfos != null + ? Collections.unmodifiableList(new ArrayList(singleSignaureInfos)) + : null; } + @Override public List getSingleSignatureInfos() { return singleSignatureInfos; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateCMSSignatureResponseImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateCMSSignatureResponseImpl.java index d596058..ae64195 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateCMSSignatureResponseImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateCMSSignatureResponseImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.util.ArrayList; @@ -32,27 +31,28 @@ import at.gv.egovernment.moa.spss.api.cmssign.CreateCMSSignatureResponse; /** * Default implementation of CreateCMSSignatureResponse. - * + * * @version $Id$ */ public class CreateCMSSignatureResponseImpl - implements CreateCMSSignatureResponse { + implements CreateCMSSignatureResponse { /** The elements contained in the response. */ private List responseElements = new ArrayList(); /** * Sets the elements contained in the response. - * + * * @param responseElements The response elements. */ public void setResponseElements(List responseElements) { this.responseElements = - responseElements != null - ? Collections.unmodifiableList(new ArrayList(responseElements)) - : null; + responseElements != null + ? Collections.unmodifiableList(new ArrayList(responseElements)) + : null; } + @Override public List getResponseElements() { return responseElements; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateSignatureEnvironmentProfileExplicitImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateSignatureEnvironmentProfileExplicitImpl.java index 9fe8eaf..3d5279f 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateSignatureEnvironmentProfileExplicitImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateSignatureEnvironmentProfileExplicitImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.util.ArrayList; @@ -32,14 +31,14 @@ import at.gv.egovernment.moa.spss.api.xmlsign.CreateSignatureEnvironmentProfileE import at.gv.egovernment.moa.spss.api.xmlsign.CreateSignatureLocation; /** - * Default implementation of + * Default implementation of * . - * + * * @author Patrick Peck * @version $Id$ */ public class CreateSignatureEnvironmentProfileExplicitImpl - implements CreateSignatureEnvironmentProfileExplicit { + implements CreateSignatureEnvironmentProfileExplicit { /** The insertion location of the signature to be created. */ private CreateSignatureLocation createSignatureLocation; @@ -49,40 +48,42 @@ public class CreateSignatureEnvironmentProfileExplicitImpl /** * Sets the insertion location of the signature to be created. - * - * @param createSignatureLocation The insertion location of the signature to - * be created. + * + * @param createSignatureLocation The insertion location of the signature to be + * created. */ public void setCreateSignatureLocation(CreateSignatureLocation createSignatureLocation) { this.createSignatureLocation = createSignatureLocation; } + @Override public CreateSignatureLocation getCreateSignatureLocation() { return createSignatureLocation; } /** - * Sets the supplemental information for evaluating the signature - * environment. - * + * Sets the supplemental information for evaluating the signature environment. + * * @param supplements The supplemental information. */ public void setSupplements(List supplements) { this.supplements = - supplements != null - ? Collections.unmodifiableList(new ArrayList(supplements)) - : null; + supplements != null + ? Collections.unmodifiableList(new ArrayList(supplements)) + : null; } + @Override public List getSupplements() { return supplements; } /** * Gets the type of profile. - * + * * @return EXPLICIT_CREATESIGNATUREENVIRONMENTPROFILE */ + @Override public int getCreateSignatureEnvironmentProfileType() { return EXPLICIT_CREATESIGNATUREENVIRONMENTPROFILE; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateSignatureEnvironmentProfileIDImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateSignatureEnvironmentProfileIDImpl.java index 5edbf4f..4818f9e 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateSignatureEnvironmentProfileIDImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateSignatureEnvironmentProfileIDImpl.java @@ -21,41 +21,42 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.xmlsign.CreateSignatureEnvironmentProfileID; /** * Default implementation of CreateSignatureEnvironmentProfileID. - * + * * @author Patrick Peck * @version $Id$ */ public class CreateSignatureEnvironmentProfileIDImpl - implements CreateSignatureEnvironmentProfileID { + implements CreateSignatureEnvironmentProfileID { /** The profile ID. */ private String createSignatureEnvironmentProfileID; /** * Sets the profile ID. - * + * * @param profileID The profile ID. */ public void setCreateSignatureEnvironmentProfileID(String profileID) { this.createSignatureEnvironmentProfileID = profileID; } + @Override public String getCreateSignatureEnvironmentProfileID() { return createSignatureEnvironmentProfileID; } /** * Gets the type of profile. - * + * * @return ID_CREATESIGNATUREENVIRONMENTPROFILE */ + @Override public int getCreateSignatureEnvironmentProfileType() { return ID_CREATESIGNATUREENVIRONMENTPROFILE; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateSignatureInfoImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateSignatureInfoImpl.java index 7111633..7a97cd5 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateSignatureInfoImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateSignatureInfoImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.common.Content; @@ -30,29 +29,30 @@ import at.gv.egovernment.moa.spss.api.xmlsign.CreateSignatureInfo; /** * Default implementation of CreateSignatureInfo. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class CreateSignatureInfoImpl implements CreateSignatureInfo { - - /** The signature environment that will contain the newly created - * signature. */ + + /** + * The signature environment that will contain the newly created signature. + */ private Content createSignatureEnvironment; /** Additional information about the signature environment. */ private CreateSignatureEnvironmentProfile createSignatureEnvironmentProfile; /** - * Sets the signature environment that will contain the newly created - * signature. - * + * Sets the signature environment that will contain the newly created signature. + * * @param createSignatureEnvironment The signature environment. */ public void setCreateSignatureEnvironment(Content createSignatureEnvironment) { this.createSignatureEnvironment = createSignatureEnvironment; } + @Override public Content getCreateSignatureEnvironment() { return createSignatureEnvironment; } @@ -60,13 +60,14 @@ public class CreateSignatureInfoImpl implements CreateSignatureInfo { /** * Sets the signature environment profile containing additional information * about the signature environment. - * + * * @param profile The signature environment profile. */ public void setCreateSignatureEnvironmentProfile(CreateSignatureEnvironmentProfile profile) { this.createSignatureEnvironmentProfile = profile; } + @Override public CreateSignatureEnvironmentProfile getCreateSignatureEnvironmentProfile() { return createSignatureEnvironmentProfile; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateSignatureLocationImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateSignatureLocationImpl.java index 6f3101f..121dcf0 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateSignatureLocationImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateSignatureLocationImpl.java @@ -21,33 +21,33 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.xmlsign.CreateSignatureLocation; /** * Default implementation of CreateSignatureLocation. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class CreateSignatureLocationImpl - extends ElementSelectorImpl - implements CreateSignatureLocation { + extends ElementSelectorImpl + implements CreateSignatureLocation { /** The index of the newly created signature. */ private int index; /** * Sets the index of the newly created signature. - * + * * @param index The index of the newly created signature. */ public void setIndex(int index) { this.index = index; } + @Override public int getIndex() { return index; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateTransformsInfoImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateTransformsInfoImpl.java index d53f103..24e4abc 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateTransformsInfoImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateTransformsInfoImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.util.ArrayList; @@ -33,7 +32,7 @@ import at.gv.egovernment.moa.spss.api.xmlsign.CreateTransformsInfo; /** * Default implementation of CreateTransformsInfo. - * + * * @author Fatemeh Philippi * @version $Id$ */ @@ -45,29 +44,31 @@ public class CreateTransformsInfoImpl implements CreateTransformsInfo { /** * Sets the transforms. - * + * * @param transforms The transforms. */ public void setTransforms(List transforms) { this.transforms = - transforms != null - ? Collections.unmodifiableList(new ArrayList(transforms)) - : null; + transforms != null + ? Collections.unmodifiableList(new ArrayList(transforms)) + : null; } + @Override public List getTransforms() { return transforms; } /** * Sets the meta information about the data resulting from the transforms. - * + * * @param finalDataMetaInfo The meta information. */ public void setFinalDataMetaInfo(MetaInfo finalDataMetaInfo) { this.finalDataMetaInfo = finalDataMetaInfo; } + @Override public MetaInfo getFinalDataMetaInfo() { return finalDataMetaInfo; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateTransformsInfoProfileExplicitImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateTransformsInfoProfileExplicitImpl.java index b6b9d52..3ffc8e3 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateTransformsInfoProfileExplicitImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateTransformsInfoProfileExplicitImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.util.ArrayList; @@ -33,12 +32,12 @@ import at.gv.egovernment.moa.spss.api.xmlsign.CreateTransformsInfoProfileExplici /** * Default implementation of CreateTransformsInfoProfileExplicit. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class CreateTransformsInfoProfileExplicitImpl - implements CreateTransformsInfoProfileExplicit { + implements CreateTransformsInfoProfileExplicit { /** Transformation information. */ private CreateTransformsInfo transformsInfo; @@ -47,38 +46,41 @@ public class CreateTransformsInfoProfileExplicitImpl /** * Sets the transformation information. - * + * * @param transformsInfo The transformation information. */ public void setCreateTransformsInfo(CreateTransformsInfo transformsInfo) { this.transformsInfo = transformsInfo; } + @Override public CreateTransformsInfo getCreateTransformsInfo() { return transformsInfo; } /** * Sets the additional data for the transformations. - * + * * @param supplements The additional data. */ public void setSupplements(List supplements) { this.supplements = - supplements != null - ? Collections.unmodifiableList(new ArrayList(supplements)) - : null; + supplements != null + ? Collections.unmodifiableList(new ArrayList(supplements)) + : null; } + @Override public List getSupplements() { return supplements; } /** * Gets the type of profile. - * + * * @return EXPLICIT_CREATETRANSFORMSINFOPROFILE */ + @Override public int getCreateTransformsInfoProfileType() { return EXPLICIT_CREATETRANSFORMSINFOPROFILE; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateTransformsInfoProfileIDImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateTransformsInfoProfileIDImpl.java index 55d0ca6..e86c7de 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateTransformsInfoProfileIDImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateTransformsInfoProfileIDImpl.java @@ -21,40 +21,42 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.xmlsign.CreateTransformsInfoProfileID; /** * Default implementation of CreateTransformsInfoProfileID. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class CreateTransformsInfoProfileIDImpl - implements CreateTransformsInfoProfileID { + implements CreateTransformsInfoProfileID { /** The profile ID. */ private String createTransformsID; /** * Sets the profile ID. + * * @param createTransformsID The profile ID. */ public void setCreateTransformsInfoProfileID(String createTransformsID) { this.createTransformsID = createTransformsID; } + @Override public String getCreateTransformsInfoProfileID() { return createTransformsID; } /** * Gets the type of profile. - * + * * @return ID_CREATETRANSFORMSINFOPROFILE */ + @Override public int getCreateTransformsInfoProfileType() { return ID_CREATETRANSFORMSINFOPROFILE; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateXMLSignatureRequestImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateXMLSignatureRequestImpl.java index aaffaa7..30779a3 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateXMLSignatureRequestImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateXMLSignatureRequestImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.util.ArrayList; @@ -32,44 +31,46 @@ import at.gv.egovernment.moa.spss.api.xmlsign.CreateXMLSignatureRequest; /** * Default implementation of CreateXMLSignatureRequest. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class CreateXMLSignatureRequestImpl - implements CreateXMLSignatureRequest { + implements CreateXMLSignatureRequest { - /** The identifier for selecting the private keys for creating the signature.*/ + /** The identifier for selecting the private keys for creating the signature. */ private String keyIdentifier; /** Information for creating a single signature. */ private List singleSignatureInfos = new ArrayList(); /** - * Sets the identifier for selecting the private keys for creating the + * Sets the identifier for selecting the private keys for creating the * signature. - * + * * @param keyIdentifier The identifier for selecting the private keys. */ public void setKeyIdentifier(String keyIdentifier) { this.keyIdentifier = keyIdentifier; } + @Override public String getKeyIdentifier() { return keyIdentifier; } /** * Sets the information for creating single signatures. - * + * * @param singleSignaureInfos The information for creating single signatures. */ public void setSingleSignatureInfos(List singleSignaureInfos) { this.singleSignatureInfos = - singleSignaureInfos != null - ? Collections.unmodifiableList(new ArrayList(singleSignaureInfos)) - : null; + singleSignaureInfos != null + ? Collections.unmodifiableList(new ArrayList(singleSignaureInfos)) + : null; } + @Override public List getSingleSignatureInfos() { return singleSignatureInfos; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateXMLSignatureResponseImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateXMLSignatureResponseImpl.java index 7a8359f..80cd6dc 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateXMLSignatureResponseImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/CreateXMLSignatureResponseImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.util.ArrayList; @@ -32,28 +31,29 @@ import at.gv.egovernment.moa.spss.api.xmlsign.CreateXMLSignatureResponse; /** * Default implementation of CreateXMLSignatureResponse. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class CreateXMLSignatureResponseImpl - implements CreateXMLSignatureResponse { + implements CreateXMLSignatureResponse { /** The elements contained in the response. */ private List responseElements = new ArrayList(); /** * Sets the elements contained in the response. - * + * * @param responseElements The response elements. */ public void setResponseElements(List responseElements) { this.responseElements = - responseElements != null - ? Collections.unmodifiableList(new ArrayList(responseElements)) - : null; + responseElements != null + ? Collections.unmodifiableList(new ArrayList(responseElements)) + : null; } + @Override public List getResponseElements() { return responseElements; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/DataObjectInfoCMSImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/DataObjectInfoCMSImpl.java index 702086b..f65816a 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/DataObjectInfoCMSImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/DataObjectInfoCMSImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.cmssign.DataObjectInfo; @@ -29,7 +28,7 @@ import at.gv.egovernment.moa.spss.api.cmsverify.CMSDataObject; /** * Default implementation of DataObjectInfo for CMS. - * + * * @author Fatemeh Philippi * @version $Id$ */ @@ -41,27 +40,28 @@ public class DataObjectInfoCMSImpl implements DataObjectInfo { /** * Sets the signature structure type. - * + * * @param structure The signature structure type. */ public void setStructure(String structure) { this.stucture = structure; } + @Override public String getStructure() { return stucture; } - /** * Sets the data object to be signed. - * + * * @param dataObject The data object to be signed. */ public void setDataObject(CMSDataObject dataObject) { this.dataObject = dataObject; } + @Override public CMSDataObject getDataObject() { return dataObject; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/DataObjectInfoImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/DataObjectInfoImpl.java index 7a25a97..4099d89 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/DataObjectInfoImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/DataObjectInfoImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.common.Content; @@ -30,15 +29,16 @@ import at.gv.egovernment.moa.spss.api.xmlsign.DataObjectInfo; /** * Default implementation of DataObjectInfo. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class DataObjectInfoImpl implements DataObjectInfo { /** The signature structure type. */ private String stucture; - /** Whether a reference will be placed in the signature itself or in the - * manifest */ + /** + * Whether a reference will be placed in the signature itself or in the manifest + */ private boolean childOfManifest; /** The data object to be signed. */ private Content dataObject; @@ -47,13 +47,14 @@ public class DataObjectInfoImpl implements DataObjectInfo { /** * Sets the signature structure type. - * + * * @param structure The signature structure type. */ public void setStructure(String structure) { this.stucture = structure; } + @Override public String getStructure() { return stucture; } @@ -61,41 +62,44 @@ public class DataObjectInfoImpl implements DataObjectInfo { /** * Sets whether a reference will be placed in the signature itself or in the * manifest. - * - * @param childOfManifest Whether to put the reference in the signature of - * in the manifest. + * + * @param childOfManifest Whether to put the reference in the signature of in + * the manifest. */ public void setChildOfManifest(boolean childOfManifest) { this.childOfManifest = childOfManifest; } + @Override public boolean isChildOfManifest() { return childOfManifest; } /** * Sets the data object to be signed. - * + * * @param dataObject The data object to be signed. */ public void setDataObject(Content dataObject) { this.dataObject = dataObject; } + @Override public Content getDataObject() { return dataObject; } /** * Sets additional information for the transformations. - * + * * @param profile The profile containing additional information for the - * transformations. + * transformations. */ public void setCreateTransformsInfoProfile(CreateTransformsInfoProfile profile) { this.createTransformsInfoProfile = profile; } + @Override public CreateTransformsInfoProfile getCreateTransformsInfoProfile() { return createTransformsInfoProfile; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ElementSelectorImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ElementSelectorImpl.java index 7de0660..e505440 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ElementSelectorImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ElementSelectorImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.util.HashMap; @@ -31,7 +30,7 @@ import at.gv.egovernment.moa.spss.api.common.ElementSelector; /** * Default implementation of ElementSelector. - * + * * @author Fatemeh Philippi * @version $Id$ */ @@ -43,27 +42,29 @@ public class ElementSelectorImpl implements ElementSelector { /** * Sets the XPath expression pointing to the element. - * + * * @param xPathExpression XPath expression pointing to the element. */ public void setXPathExpression(String xPathExpression) { this.xPathExpression = xPathExpression; } + @Override public String getXPathExpression() { return xPathExpression; } /** * Sets namespace declarations to apply for evaluating the XPath. - * - * @param namespaceDeclarations The namespace declarations to apply for - * evaluating the XPath. + * + * @param namespaceDeclarations The namespace declarations to apply for + * evaluating the XPath. */ public void setNamespaceDeclarations(Map namespaceDeclarations) { this.namespaceDeclarations = namespaceDeclarations; } + @Override public Map getNamespaceDeclarations() { return namespaceDeclarations; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/EnvelopedSignatureTransformImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/EnvelopedSignatureTransformImpl.java index 121037f..40a579b 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/EnvelopedSignatureTransformImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/EnvelopedSignatureTransformImpl.java @@ -21,20 +21,19 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.common.EnvelopedSignatureTransform; /** * Default implementation of EnvelopedSignatureTransform. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class EnvelopedSignatureTransformImpl - extends TransformImpl - implements EnvelopedSignatureTransform { + extends TransformImpl + implements EnvelopedSignatureTransform { /** * Create a EnvelopedSignatureTransformImpl. diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ErrorResponseImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ErrorResponseImpl.java index a2a59a7..e55b69b 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ErrorResponseImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ErrorResponseImpl.java @@ -21,14 +21,13 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.xmlsign.ErrorResponse; /** * Default implementation of ErrorResponse. - * + * * @author Fatemeh Philippi * @version $Id$ */ @@ -40,35 +39,38 @@ public class ErrorResponseImpl implements ErrorResponse { /** * Sets the error code. - * + * * @param code The error code. */ public void setErrorCode(int code) { this.code = code; } + @Override public int getErrorCode() { return code; } /** * Sets the verbose error information. - * + * * @param info The verbose error information. */ public void setInfo(String info) { this.info = info; } + @Override public String getInfo() { return info; } /** * Gets the response type. - * - * @return ERROR_RESPONSE + * + * @return ERROR_RESPONSE */ + @Override public int getResponseType() { return ERROR_RESPONSE; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ExclusiveCanonicalizationTransformImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ExclusiveCanonicalizationTransformImpl.java index eea09c0..fd0e276 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ExclusiveCanonicalizationTransformImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ExclusiveCanonicalizationTransformImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.util.ArrayList; @@ -32,22 +31,22 @@ import at.gv.egovernment.moa.spss.api.common.ExclusiveCanonicalizationTransform; /** * Default implementation of ExclusiveCanonicalizationTransform. - * + * * @author Patrick Peck * @version $Id$ */ public class ExclusiveCanonicalizationTransformImpl - extends TransformImpl - implements ExclusiveCanonicalizationTransform { + extends TransformImpl + implements ExclusiveCanonicalizationTransform { /** The namespaces to treat according to canonical XML. */ private List inclusiveNamespacePrefixes; - - /** + + /** * Create a ExclusiveCanonicalizationTransformImpl object. - * + * * @param algorithmURI The algorithm URI identifying the transformation - * algorithm. + * algorithm. */ public ExclusiveCanonicalizationTransformImpl(String algorithmURI) { setAlgorithmURI(algorithmURI); @@ -55,16 +54,18 @@ public class ExclusiveCanonicalizationTransformImpl /** * Sets the namespaces to treat according to canonical XML. - * @param inclusiveNamespacePrefixes The namespaces to treat according to - * canonical XML. + * + * @param inclusiveNamespacePrefixes The namespaces to treat according to + * canonical XML. */ public void setInclusiveNamespacePrefixes(List inclusiveNamespacePrefixes) { this.inclusiveNamespacePrefixes = - inclusiveNamespacePrefixes != null - ? Collections.unmodifiableList(new ArrayList(inclusiveNamespacePrefixes)) - : null; + inclusiveNamespacePrefixes != null + ? Collections.unmodifiableList(new ArrayList(inclusiveNamespacePrefixes)) + : null; } + @Override public List getInclusiveNamespacePrefixes() { return inclusiveNamespacePrefixes; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ExtendedCertificateCheckResultImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ExtendedCertificateCheckResultImpl.java index f36760c..21db8e0 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ExtendedCertificateCheckResultImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ExtendedCertificateCheckResultImpl.java @@ -3,42 +3,42 @@ package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.common.ExtendedCertificateCheckResult; public class ExtendedCertificateCheckResultImpl implements ExtendedCertificateCheckResult { - private int majorCode; - private String majorInfo; - - private int minorCode; - private String minorInfo; - - public ExtendedCertificateCheckResultImpl(int majorCode, String majorInfo) { - this(majorCode, majorInfo, -1, ""); - } - - public ExtendedCertificateCheckResultImpl(int majorCode, String majorInfo, - int minorCode, String minorInfo) { - this.majorCode = majorCode; - this.majorInfo = majorInfo; - this.minorCode = minorCode; - this.minorInfo = minorInfo; - } - - @Override - public int getMajorCode() { - return this.majorCode; - } - - @Override - public String getMajorInfo() { - return this.majorInfo; - } - - @Override - public int getMinorCode() { - return this.minorCode; - } - - @Override - public String getMinorInfo() { - return this.minorInfo; - } + private final int majorCode; + private final String majorInfo; + + private final int minorCode; + private final String minorInfo; + + public ExtendedCertificateCheckResultImpl(int majorCode, String majorInfo) { + this(majorCode, majorInfo, -1, ""); + } + + public ExtendedCertificateCheckResultImpl(int majorCode, String majorInfo, + int minorCode, String minorInfo) { + this.majorCode = majorCode; + this.majorInfo = majorInfo; + this.minorCode = minorCode; + this.minorInfo = minorInfo; + } + + @Override + public int getMajorCode() { + return this.majorCode; + } + + @Override + public String getMajorInfo() { + return this.majorInfo; + } + + @Override + public int getMinorCode() { + return this.minorCode; + } + + @Override + public String getMinorInfo() { + return this.minorInfo; + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/InputDataBinaryImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/InputDataBinaryImpl.java index 4b5659e..a806f16 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/InputDataBinaryImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/InputDataBinaryImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.io.InputStream; @@ -32,102 +31,104 @@ import at.gv.egovernment.moa.spss.api.common.ContentBinary; import at.gv.egovernment.moa.spss.api.common.InputData; /** - * Content wrapper decorating a binary content with two additional attributes + * Content wrapper decorating a binary content with two additional attributes * needed for returning HashInputData and ReferenceInputData * information as part of VerifyXMLSignatureResponse. - * + * * @author Gregor Karlinger - * + * * @version $Id$ */ -public class InputDataBinaryImpl implements ContentBinary, InputData -{ +public class InputDataBinaryImpl implements ContentBinary, InputData { /** * The wrapped Content. */ protected ContentBinary wrapped_; - + /** - * This attribute signals what kind of container the XMLDSIG Reference - * this InputData belongs to is part of. + * This attribute signals what kind of container the XMLDSIG + * Reference this InputData belongs to is part of. */ protected String partOf_; - + /** * If this InputData belongs to an XMLDSIG Reference * being part of either a XMLDSIGManifest or a SignatureManifest, this attribute - * (a positive int) signals the particular Reference of the XMLDSIG + * (a positive int) signals the particular Reference of the XMLDSIG * SignedInfo referring to the XMLDSIGManifest or SignatureManifest * respectively. */ protected int referringReferenceNumber_; - + protected String hashAlg = null; - + /** * Creates a new instance. - * - * @param wrapped The wrapped Content. Must be of type {@link Content#BINARY_CONTENT}. - * - * @param partOf see {@link InputData} - * + * + * @param wrapped The wrapped Content. Must be of + * type {@link Content#BINARY_CONTENT}. + * + * @param partOf see {@link InputData} + * * @param referringReferenceNumber see {@link InputData} - * - * @param hashAlg see {@link InputData} + * + * @param hashAlg see {@link InputData} */ - public InputDataBinaryImpl(Content wrapped, String partOf, int referringReferenceNumber, String hashAlg) throws MOARuntimeException - { - if (wrapped.getContentType() != Content.BINARY_CONTENT) throw new MOARuntimeException("9901", null); - + public InputDataBinaryImpl(Content wrapped, String partOf, int referringReferenceNumber, String hashAlg) + throws MOARuntimeException { + if (wrapped.getContentType() != Content.BINARY_CONTENT) { + throw new MOARuntimeException("9901", null); + } + wrapped_ = (ContentBinary) wrapped; - partOf_ = partOf; + partOf_ = partOf; referringReferenceNumber_ = referringReferenceNumber; - this.hashAlg = hashAlg; + this.hashAlg = hashAlg; } - - /** + + /** * @see at.gv.egovernment.moa.spss.api.common.Content#getContentType() */ - public int getContentType() - { + @Override + public int getContentType() { return wrapped_.getContentType(); } /** * @see at.gv.egovernment.moa.spss.api.common.Content#getReference() */ - public String getReference() - { + @Override + public String getReference() { return wrapped_.getReference(); } /** * @see at.gv.egovernment.moa.spss.api.common.ContentBinary#getBinaryContent() */ - public InputStream getBinaryContent() - { + @Override + public InputStream getBinaryContent() { return wrapped_.getBinaryContent(); } /** * @see at.gv.egovernment.moa.spss.api.common.InputData#getPartOf() */ - public String getPartOf() - { + @Override + public String getPartOf() { return partOf_; } /** * @see at.gv.egovernment.moa.spss.api.common.InputData#getReferringReferenceNumber() */ - public int getReferringReferenceNumber() - { + @Override + public int getReferringReferenceNumber() { return referringReferenceNumber_; } -@Override -public String getHashAlgorithm() { - return this.hashAlg; -} + @Override + public String getHashAlgorithm() { + return this.hashAlg; + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/InputDataXMLImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/InputDataXMLImpl.java index e89976e..fd97bf8 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/InputDataXMLImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/InputDataXMLImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import org.w3c.dom.NodeList; @@ -32,102 +31,103 @@ import at.gv.egovernment.moa.spss.api.common.ContentXML; import at.gv.egovernment.moa.spss.api.common.InputData; /** - * Content wrapper decorating an XML content with two additional attributes + * Content wrapper decorating an XML content with two additional attributes * needed for returning HashInputData and ReferenceInputData * information as part of VerifyXMLSignatureResponse. - * + * * @author Gregor Karlinger - * + * * @version $Id$ */ -public class InputDataXMLImpl implements ContentXML, InputData -{ +public class InputDataXMLImpl implements ContentXML, InputData { /** * The wrapped ContentXML. */ protected ContentXML wrapped_; - + /** - * This attribute signals what kind of container the XMLDSIG Reference - * this InputData belongs to is part of. + * This attribute signals what kind of container the XMLDSIG + * Reference this InputData belongs to is part of. */ protected String partOf_; - + /** * If this InputData belongs to an XMLDSIG Reference * being part of either a XMLDSIGManifest or a SignatureManifest, this attribute - * (a positive int) signals the particular Reference of the XMLDSIG + * (a positive int) signals the particular Reference of the XMLDSIG * SignedInfo referring to the XMLDSIGManifest or SignatureManifest * respectively. */ protected int referringReferenceNumber_; - + protected String hashAlg = null; - + /** * Creates a new instance. - * - * @param wrapped The wrapped ContentBinary. Must be of type {@link Content#XML_CONTENT}. - * - * @param partOf see {@link InputData} - * + * + * @param wrapped The wrapped ContentBinary. Must + * be of type {@link Content#XML_CONTENT}. + * + * @param partOf see {@link InputData} + * * @param referringReferenceNumber see {@link InputData} - * - * @param hashAlg see {@link InputData} + * + * @param hashAlg see {@link InputData} */ - public InputDataXMLImpl(Content wrapped, String partOf, int referringReferenceNumber, String hashAlg) - { - if (wrapped.getContentType() != Content.XML_CONTENT) throw new MOARuntimeException("9901", null); + public InputDataXMLImpl(Content wrapped, String partOf, int referringReferenceNumber, String hashAlg) { + if (wrapped.getContentType() != Content.XML_CONTENT) { + throw new MOARuntimeException("9901", null); + } wrapped_ = (ContentXML) wrapped; - partOf_ = partOf; + partOf_ = partOf; referringReferenceNumber_ = referringReferenceNumber; this.hashAlg = hashAlg; } - - /** + + /** * @see at.gv.egovernment.moa.spss.api.common.Content#getContentType() */ - public int getContentType() - { + @Override + public int getContentType() { return wrapped_.getContentType(); } /** * @see at.gv.egovernment.moa.spss.api.common.Content#getReference() */ - public String getReference() - { + @Override + public String getReference() { return wrapped_.getReference(); } /** * @see at.gv.egovernment.moa.spss.api.common.ContentXML#getXMLContent() */ - public NodeList getXMLContent() - { + @Override + public NodeList getXMLContent() { return wrapped_.getXMLContent(); } /** * @see at.gv.egovernment.moa.spss.api.common.InputData#getPartOf() */ - public String getPartOf() - { + @Override + public String getPartOf() { return partOf_; } /** * @see at.gv.egovernment.moa.spss.api.common.InputData#getReferringReferenceNumber() */ - public int getReferringReferenceNumber() - { + @Override + public int getReferringReferenceNumber() { return referringReferenceNumber_; } -@Override -public String getHashAlgorithm() { - return this.hashAlg; -} + @Override + public String getHashAlgorithm() { + return this.hashAlg; + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ManifestRefsCheckResultImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ManifestRefsCheckResultImpl.java index e5b7f40..752fec0 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ManifestRefsCheckResultImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ManifestRefsCheckResultImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.xmlverify.ManifestRefsCheckResult; @@ -29,7 +28,7 @@ import at.gv.egovernment.moa.spss.api.xmlverify.ManifestRefsCheckResultInfo; /** * Default implementation of ManifestRefsCheckResult. - * + * * @author Fatemeh Philippi * @version $Id$ */ @@ -41,26 +40,28 @@ public class ManifestRefsCheckResultImpl implements ManifestRefsCheckResult { /** * Sets the check code. - * + * * @param code A numerical representation of the result of the manifest check. */ public void setCode(int code) { this.code = code; } + @Override public int getCode() { return code; } /** * Sets a reference to the manifest. - * + * * @param info The reference to the manifest. */ public void setInfo(ManifestRefsCheckResultInfo info) { this.info = info; } + @Override public ManifestRefsCheckResultInfo getInfo() { return info; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ManifestRefsCheckResultInfoImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ManifestRefsCheckResultInfoImpl.java index f0ef1c5..68405a1 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ManifestRefsCheckResultInfoImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ManifestRefsCheckResultInfoImpl.java @@ -21,34 +21,37 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.xmlverify.ManifestRefsCheckResultInfo; /** * Default implementation of ManifestRefsCheckResultInfo. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class ManifestRefsCheckResultInfoImpl - extends ReferencesCheckResultInfoImpl - implements ManifestRefsCheckResultInfo { + extends ReferencesCheckResultInfoImpl + implements ManifestRefsCheckResultInfo { - /** The position of the signature reference containing the reference to the - * manifest being described by this object.*/ + /** + * The position of the signature reference containing the reference to the + * manifest being described by this object. + */ private int referringSignatureReference; /** - * Sets the position of the signature reference containing the reference to - * the manifest being described by this object. + * Sets the position of the signature reference containing the reference to the + * manifest being described by this object. + * * @param referringSignatureReference The position of the signature reference. */ public void setReferringSignatureReference(int referringSignatureReference) { this.referringSignatureReference = referringSignatureReference; } + @Override public int getReferringSignatureReference() { return referringSignatureReference; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/MetaInfoImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/MetaInfoImpl.java index e3a06c6..9f6d882 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/MetaInfoImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/MetaInfoImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import org.w3c.dom.NodeList; @@ -30,6 +29,7 @@ import at.gv.egovernment.moa.spss.api.common.MetaInfo; /** * Default implementation of MetaInfo. + * * @author Fatemeh Philippi * @version $Id$ */ @@ -45,55 +45,58 @@ public class MetaInfoImpl implements MetaInfo { /** * Sets the MIME type. - * + * * @param mimeType The MIME type to set. */ public void setMimeType(String mimeType) { this.mimeType = mimeType; } + @Override public String getMimeType() { return mimeType; } /** * Sets the URI pointing to a description of the content. - * + * * @param description The URI pointing to a description of the content. */ public void setDescription(String description) { this.description = description; } + @Override public String getDescription() { return description; } /** * Sets descriptive XML content. - * + * * @param anyElements The elements to set. */ public void setAnyElements(NodeList anyElements) { - this.anyElements = anyElements; + this.anyElements = anyElements; } + @Override public NodeList getAnyElements() { return anyElements; } /** * Sets the XML signature creation type information. - * + * * @param type the XML signature creation type information to set. */ public void setType(String type) { this.type = type; } + @Override public String getType() { return type; } - } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ReferenceInfoImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ReferenceInfoImpl.java index 8bd81a7..c9e44f1 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ReferenceInfoImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ReferenceInfoImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.util.ArrayList; @@ -32,7 +31,7 @@ import at.gv.egovernment.moa.spss.api.xmlverify.ReferenceInfo; /** * Default implementation of ReferenceInfo. - * + * * @author Fatemeh Philippi * @version $Id$ */ @@ -41,20 +40,21 @@ public class ReferenceInfoImpl implements ReferenceInfo { private List verifyTransformsInfoProfiles; /** - * Sets the transforms profile used for verifying the transforms contained - * in the signature. - * + * Sets the transforms profile used for verifying the transforms contained in + * the signature. + * * @param verifyTransformsInfoProfiles The profiles containing the transforms - * allowed in the signature. + * allowed in the signature. */ public void setVerifyTransformsInfoProfiles(List verifyTransformsInfoProfiles) { this.verifyTransformsInfoProfiles = - verifyTransformsInfoProfiles != null - ? Collections.unmodifiableList( - new ArrayList(verifyTransformsInfoProfiles)) - : null; + verifyTransformsInfoProfiles != null + ? Collections.unmodifiableList( + new ArrayList(verifyTransformsInfoProfiles)) + : null; } + @Override public List getVerifyTransformsInfoProfiles() { return verifyTransformsInfoProfiles; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ReferencesCheckResultImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ReferencesCheckResultImpl.java index d4cbab0..02e8634 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ReferencesCheckResultImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ReferencesCheckResultImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.xmlverify.ReferencesCheckResult; @@ -29,7 +28,7 @@ import at.gv.egovernment.moa.spss.api.xmlverify.ReferencesCheckResultInfo; /** * Default implementation of ReferencesCheckResult. - * + * * @author Patrick Peck * @version $Id$ */ @@ -41,30 +40,31 @@ public class ReferencesCheckResultImpl implements ReferencesCheckResult { /** * Sets the check code. - * - * @param code A numerical representation of the result of the reference - * check. + * + * @param code A numerical representation of the result of the reference check. */ public void setCode(int code) { this.code = code; } - + + @Override public int getCode() { return code; } /** * Sets additional information about the reference check. - * - * @param manifestRefsCheckResultInfo Additional information about the - * reference check. + * + * @param manifestRefsCheckResultInfo Additional information about the reference + * check. */ public void setInfo(ReferencesCheckResultInfo manifestRefsCheckResultInfo) { this.info = manifestRefsCheckResultInfo; } - + + @Override public ReferencesCheckResultInfo getInfo() { return info; - } + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ReferencesCheckResultInfoImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ReferencesCheckResultInfoImpl.java index a696988..a9073ed 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ReferencesCheckResultInfoImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/ReferencesCheckResultInfoImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import org.w3c.dom.NodeList; @@ -30,39 +29,42 @@ import at.gv.egovernment.moa.spss.api.xmlverify.ReferencesCheckResultInfo; /** * Default implementation of ReferencesCheckResultInfo. - * + * * @author Patrick Peck * @version $Id$ */ public class ReferencesCheckResultInfoImpl - implements ReferencesCheckResultInfo { + implements ReferencesCheckResultInfo { /** Additional information about the references check. */ private NodeList anyOtherInfo; /** The indexes of the failed references. */ private int[] failedReferences = new int[0]; - + /** * Sets additional information about the references check. + * * @param anyOtherInfo Additional information about the references check. */ public void setAnyOtherInfo(NodeList anyOtherInfo) { this.anyOtherInfo = anyOtherInfo; } - + + @Override public NodeList getAnyOtherInfo() { return anyOtherInfo; } /** * Sets the indexes of the failed references. - * + * * @param failedReferences The indexes of the failed references. */ public void setFailedReferences(int[] failedReferences) { this.failedReferences = failedReferences; } + @Override public int[] getFailedReferences() { return failedReferences; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SPSSFactoryImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SPSSFactoryImpl.java index 2525a2f..0831aec 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SPSSFactoryImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SPSSFactoryImpl.java @@ -80,491 +80,577 @@ import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureResponse; /** * Default implementation of SPSSFactory. - * + * * @author Patrick Peck * @version $Id$ */ public class SPSSFactoryImpl extends SPSSFactory { - public CreateXMLSignatureRequest createCreateXMLSignatureRequest(String keyIdentifier, List singleSignatureInfos) { - CreateXMLSignatureRequestImpl createXMLSignatureRequest = new CreateXMLSignatureRequestImpl(); - createXMLSignatureRequest.setKeyIdentifier(keyIdentifier); - createXMLSignatureRequest.setSingleSignatureInfos(singleSignatureInfos); - return createXMLSignatureRequest; - } - - public CreateCMSSignatureRequest createCreateCMSSignatureRequest(String keyIdentifier, List singleSignatureInfos) { - CreateCMSSignatureRequestImpl createCMSSignatureRequest = new CreateCMSSignatureRequestImpl(); - createCMSSignatureRequest.setKeyIdentifier(keyIdentifier); - createCMSSignatureRequest.setSingleSignatureInfos(singleSignatureInfos); - return createCMSSignatureRequest; - - } - - public CreateCMSSignatureResponse createCreateCMSSignatureResponse(List responseElements) { - CreateCMSSignatureResponseImpl createCMSSignatureResponse = new CreateCMSSignatureResponseImpl(); - createCMSSignatureResponse.setResponseElements(responseElements); - return createCMSSignatureResponse; - } - - public CMSSignatureResponse createCMSSignatureResponse(String base64value) { - CMSSignatureResponseImpl cmsSignatureResponse = new CMSSignatureResponseImpl(); - cmsSignatureResponse.setCMSSignature(base64value); - - return cmsSignatureResponse; - } - - public SingleSignatureInfo createSingleSignatureInfo(List dataObjectInfos, CreateSignatureInfo createSignatureInfo, - boolean securityLayerConform) { - SingleSignatureInfoImpl singleSignatureInfo = new SingleSignatureInfoImpl(); - singleSignatureInfo.setDataObjectInfos(dataObjectInfos); - singleSignatureInfo.setCreateSignatureInfo(createSignatureInfo); - singleSignatureInfo.setSecurityLayerConform(securityLayerConform); - return singleSignatureInfo; - } - - public at.gv.egovernment.moa.spss.api.cmssign.SingleSignatureInfo createSingleSignatureInfoCMS( - at.gv.egovernment.moa.spss.api.cmssign.DataObjectInfo dataObjectInfo, boolean securityLayerConform, boolean isPAdESConform) { - SingleSignatureInfoCMSImpl singleSignatureInfo = new SingleSignatureInfoCMSImpl(); - singleSignatureInfo.setDataObjectInfo(dataObjectInfo); - singleSignatureInfo.setSecurityLayerConform(securityLayerConform); - singleSignatureInfo.setPAdESConform(isPAdESConform); - return singleSignatureInfo; - } - - public DataObjectInfo createDataObjectInfo(String structure, boolean childOfManifest, Content dataObject, - CreateTransformsInfoProfile createTransformsInfoProfile) { - DataObjectInfoImpl dataObjectInfo = new DataObjectInfoImpl(); - dataObjectInfo.setStructure(structure); - dataObjectInfo.setChildOfManifest(childOfManifest); - dataObjectInfo.setDataObject(dataObject); - dataObjectInfo.setCreateTransformsInfoProfile(createTransformsInfoProfile); - return dataObjectInfo; - } - - public at.gv.egovernment.moa.spss.api.cmssign.DataObjectInfo createDataObjectInfo(String structure, - CMSDataObject dataObject) { - DataObjectInfoCMSImpl dataObjectInfo = new DataObjectInfoCMSImpl(); - dataObjectInfo.setStructure(structure); - dataObjectInfo.setDataObject(dataObject); - return dataObjectInfo; - } - - public CreateTransformsInfoProfile createCreateTransformsInfoProfile(String profileID) { - - CreateTransformsInfoProfileIDImpl createTransformsInfoProfile = new CreateTransformsInfoProfileIDImpl(); - createTransformsInfoProfile.setCreateTransformsInfoProfileID(profileID); - return createTransformsInfoProfile; - } - - public CreateTransformsInfoProfile createCreateTransformsInfoProfile(CreateTransformsInfo transformsInfo, - List supplements) { - CreateTransformsInfoProfileExplicitImpl createTransformsInfoProfile = new CreateTransformsInfoProfileExplicitImpl(); - createTransformsInfoProfile.setCreateTransformsInfo(transformsInfo); - createTransformsInfoProfile.setSupplements(supplements); - return createTransformsInfoProfile; - } - - public CreateTransformsInfo createCreateTransformsInfo(List transforms, MetaInfo finalDataMetaInfo) { - CreateTransformsInfoImpl createTransformsInfo = new CreateTransformsInfoImpl(); - - createTransformsInfo.setTransforms(transforms); - createTransformsInfo.setFinalDataMetaInfo(finalDataMetaInfo); - return createTransformsInfo; - } - - public CreateSignatureInfo createCreateSignatureInfo(Content createSignatureEnvironment, - CreateSignatureEnvironmentProfile createSignatureEnvironmentProfile) { - CreateSignatureInfoImpl createSignatureInfo = new CreateSignatureInfoImpl(); - createSignatureInfo.setCreateSignatureEnvironment(createSignatureEnvironment); - createSignatureInfo.setCreateSignatureEnvironmentProfile(createSignatureEnvironmentProfile); - return createSignatureInfo; - } - - public CreateSignatureEnvironmentProfile createCreateSignatureEnvironmentProfile( - CreateSignatureLocation createSignatureLocation, List supplements) { - CreateSignatureEnvironmentProfileExplicitImpl createSignatureEnvironmentProfile = new CreateSignatureEnvironmentProfileExplicitImpl(); - createSignatureEnvironmentProfile.setCreateSignatureLocation(createSignatureLocation); - createSignatureEnvironmentProfile.setSupplements(supplements); - return createSignatureEnvironmentProfile; - } - - public CreateSignatureLocation createCreateSignatureLocation(String signatureLocationXPath, - int signatureLocationIndex, Map namespaceDeclarations) { - CreateSignatureLocationImpl createSignatureLocation = new CreateSignatureLocationImpl(); - createSignatureLocation.setIndex(signatureLocationIndex); - createSignatureLocation.setNamespaceDeclarations(namespaceDeclarations); - createSignatureLocation.setXPathExpression(signatureLocationXPath); - return createSignatureLocation; - } - - public CreateSignatureEnvironmentProfile createCreateSignatureEnvironmentProfile(String profileID) { - CreateSignatureEnvironmentProfileIDImpl createSignatureEnvironmentProfile = new CreateSignatureEnvironmentProfileIDImpl(); - createSignatureEnvironmentProfile.setCreateSignatureEnvironmentProfileID(profileID); - return createSignatureEnvironmentProfile; - } - - public CreateXMLSignatureResponse createCreateXMLSignatureResponse(List responseElements) { - CreateXMLSignatureResponseImpl createXMLSignatureResponse = new CreateXMLSignatureResponseImpl(); - createXMLSignatureResponse.setResponseElements(responseElements); - return createXMLSignatureResponse; - } - - public SignatureEnvironmentResponse createSignatureEnvironmentResponse(Element signatureEnvironment) { - SignatureEnvironmentResponseImpl signatureEnvironmentResponse = new SignatureEnvironmentResponseImpl(); - signatureEnvironmentResponse.setSignatureEnvironment(signatureEnvironment); - return signatureEnvironmentResponse; - } - - public ErrorResponse createErrorResponse(int code, String info) { - ErrorResponseImpl errorResponse = new ErrorResponseImpl(); - errorResponse.setErrorCode(code); - errorResponse.setInfo(info); - return errorResponse; - } - - public VerifyCMSSignatureRequest createVerifyCMSSignatureRequest(int[] signatories, Date dateTime, - InputStream cmsSignature, CMSDataObject dataObject, String trustProfileID, boolean pdf) { - return this.createVerifyCMSSignatureRequest(signatories, dateTime, cmsSignature, dataObject, trustProfileID, pdf, false); - } - - public VerifyCMSSignatureRequest createVerifyCMSSignatureRequest(int[] signatories, Date dateTime, - InputStream cmsSignature, CMSDataObject dataObject, String trustProfileID, boolean pdf, boolean extended) { - VerifyCMSSignatureRequestImpl verifyCMSSignatureRequest = new VerifyCMSSignatureRequestImpl(); - verifyCMSSignatureRequest.setDateTime(dateTime); - verifyCMSSignatureRequest.setCMSSignature(cmsSignature); - verifyCMSSignatureRequest.setDataObject(dataObject); - verifyCMSSignatureRequest.setTrustProfileId(trustProfileID); - verifyCMSSignatureRequest.setSignatories(signatories); - verifyCMSSignatureRequest.setPDF(pdf); - verifyCMSSignatureRequest.setExtended(extended); - return verifyCMSSignatureRequest; - } - - public CMSDataObject createCMSDataObject(MetaInfo metaInfo, CMSContent content, BigDecimal excludeByteRangeFrom, - BigDecimal excludeByteRangeTo) { - - CMSDataObjectImpl cmsDataObject = new CMSDataObjectImpl(); - cmsDataObject.setMetaInfo(metaInfo); - cmsDataObject.setContent(content); - cmsDataObject.setExcludeByteRangeFrom(excludeByteRangeFrom); - cmsDataObject.setExcludeByteRangeTo(excludeByteRangeTo); - - return cmsDataObject; - } - - public CMSContent createCMSContent(InputStream binaryContent) { - CMSContentExplicitImpl cmsContent = new CMSContentExplicitImpl(); - - cmsContent.setBinaryContent(binaryContent); - return cmsContent; - } - - public CMSContent createCMSContent(String referenceURI) { - CMSContentReferenceImpl cmsContent = new CMSContentReferenceImpl(); - - cmsContent.setReference(referenceURI); - return cmsContent; - } - - public CMSDataObject createCMSDataObject(MetaInfo metaInfo, String referenceURI) { - CMSDataObjectImpl cmsDataObject = new CMSDataObjectImpl(); - CMSContentReferenceImpl cmsContent = new CMSContentReferenceImpl(); - cmsDataObject.setMetaInfo(metaInfo); - cmsContent.setReference(referenceURI); - return cmsDataObject; - } - - public VerifyCMSSignatureResponse createVerifyCMSSignatureResponse(List responseElements) { - VerifyCMSSinatureResponseImpl verifyCMSSignatureResponse = new VerifyCMSSinatureResponseImpl(); - verifyCMSSignatureResponse.setResponseElements(responseElements); - return verifyCMSSignatureResponse; - } - - public VerifyCMSSignatureResponseElement createVerifyCMSSignatureResponseElement(SignerInfo signerInfo, - CheckResult signatureCheck, CheckResult certificateCheck, List adesResult, - ExtendedCertificateCheckResult extendedCertificateCheckResult, String usedAlgorithm, Boolean coversFullDocument, - int[] byteRangeOfSignature) { - VerifyCMSSignatureResponseElementImpl verifyCMSSignatureResponseElement = new VerifyCMSSignatureResponseElementImpl(); - verifyCMSSignatureResponseElement.setSignerInfo(signerInfo); - verifyCMSSignatureResponseElement.setSignatureCheck(signatureCheck); - verifyCMSSignatureResponseElement.setCertificateCheck(certificateCheck); - verifyCMSSignatureResponseElement.setAdESFormResults(adesResult); - verifyCMSSignatureResponseElement.setExtendedCertificateCheck(extendedCertificateCheckResult); - verifyCMSSignatureResponseElement.setSignatureAlgorithm(usedAlgorithm); - verifyCMSSignatureResponseElement.setCoversFullDocument(coversFullDocument); - verifyCMSSignatureResponseElement.setByteRangeOfSignature(byteRangeOfSignature); - return verifyCMSSignatureResponseElement; - } - - public VerifyXMLSignatureRequest createVerifyXMLSignatureRequest(Date dateTime, - VerifySignatureInfo verifySignatureInfo, List supplementProfiles, - SignatureManifestCheckParams signatureManifestParams, boolean returnHashInputData, String trustProfileID) { - return this.createVerifyXMLSignatureRequest(dateTime, verifySignatureInfo, supplementProfiles, - signatureManifestParams, returnHashInputData, trustProfileID, false); - } - - public VerifySignatureInfo createVerifySignatureInfo(Content verifySignatureEnvironment, - VerifySignatureLocation verifySignatureLocation) { - VerifySignatureInfoImpl verifySignatureInfo = new VerifySignatureInfoImpl(); - verifySignatureInfo.setVerifySignatureEnvironment(verifySignatureEnvironment); - verifySignatureInfo.setVerifySignatureLocation(verifySignatureLocation); - return verifySignatureInfo; - } - - public VerifySignatureLocation createVerifySignatureLocation(String xPathExpression, Map namespaceDeclarations) { - VerifySignatureLocationImpl verifySignatureLocation = new VerifySignatureLocationImpl(); - verifySignatureLocation.setXPathExpression(xPathExpression); - verifySignatureLocation.setNamespaceDeclarations(namespaceDeclarations); - return verifySignatureLocation; - } - - public SupplementProfile createSupplementProfile(String profileID) { - SupplementProfileIDImpl supplementProfileID = new SupplementProfileIDImpl(); - supplementProfileID.setSupplementProfileID(profileID); - return supplementProfileID; - } - - public SupplementProfile createSupplementProfile(XMLDataObjectAssociation supplementProfile) { - SupplementProfileExplicitImpl supplementProfileExplicit = new SupplementProfileExplicitImpl(); - supplementProfileExplicit.setSupplementProfile(supplementProfile); - return supplementProfileExplicit; - } - - public SignatureManifestCheckParams createSignatureManifestCheckParams(List referenceInfos, - boolean returnReferenceInputData) { - SignatureManifestCheckParamsImpl signatureManifestCheckParams = new SignatureManifestCheckParamsImpl(); - signatureManifestCheckParams.setReferenceInfos(referenceInfos); - signatureManifestCheckParams.setReturnReferenceInputData(returnReferenceInputData); - return signatureManifestCheckParams; - } - - public ReferenceInfo createReferenceInfo(List verifyTransformsInfoProfiles) { - ReferenceInfoImpl referenceInfo = new ReferenceInfoImpl(); - referenceInfo.setVerifyTransformsInfoProfiles(verifyTransformsInfoProfiles); - return referenceInfo; - } - - public VerifyTransformsInfoProfile createVerifyTransformsInfoProfile(List transforms, List transformParameters) { - VerifyTransformsInfoProfileExplicitImpl verifyTransformsInfoProfile = new VerifyTransformsInfoProfileExplicitImpl(); - - verifyTransformsInfoProfile.setTransforms(transforms); - verifyTransformsInfoProfile.setTransformParameters(transformParameters); - - return verifyTransformsInfoProfile; - } - - public VerifyTransformsInfoProfile createVerifyTransformsInfoProfile(String profileID) { - VerifyTransformsInfoProfileIDImpl verifyTransformsInfoProfile = new VerifyTransformsInfoProfileIDImpl(); - verifyTransformsInfoProfile.setVerifyTransformsInfoProfileID(profileID); - return verifyTransformsInfoProfile; - } - - public TransformParameter createTransformParameter(String URI, String digestMethod, byte[] digestValue) { - TransformPatameterHashImpl transformParameter = new TransformPatameterHashImpl(); - transformParameter.setURI(URI); - transformParameter.setDigestMethod(digestMethod); - transformParameter.setDigestValue(digestValue); - return transformParameter; - } - - public TransformParameter createTransformParameter(String URI, InputStream binaryData) { - TransformParameterBinaryImpl transformParameter = new TransformParameterBinaryImpl(); - transformParameter.setURI(URI); - transformParameter.setBinaryContent(binaryData); - return transformParameter; - } - - public TransformParameter createTransformParameter(String URI) { - TransformParameterURIImpl transformParameter = new TransformParameterURIImpl(); - transformParameter.setURI(URI); - return transformParameter; - } - - public VerifyXMLSignatureResponse createVerifyXMLSignatureResponse(SignerInfo signerInfo, List hashInputDatas, - List referenceInputDatas, ReferencesCheckResult signatureCheck, - ReferencesCheckResult signatureManifestCheck, List xmlDsigManifestChecks, CheckResult certificateCheck, - List adesFormResults, ExtendedCertificateCheckResult extCheckResult, String signatureAlgorithm) { - VerifyXMLSignatureResponseImpl verifyXMLSignatureResponse = new VerifyXMLSignatureResponseImpl(); - verifyXMLSignatureResponse.setSignerInfo(signerInfo); - verifyXMLSignatureResponse.setHashInputDatas(hashInputDatas); - verifyXMLSignatureResponse.setReferenceInputDatas(referenceInputDatas); - verifyXMLSignatureResponse.setSignatureAlgorithm(signatureAlgorithm); - verifyXMLSignatureResponse.setSignatureCheck(signatureCheck); - verifyXMLSignatureResponse.setSignatureManifestCheck(signatureManifestCheck); - verifyXMLSignatureResponse.setXMLDsigManifestChecks(xmlDsigManifestChecks); - verifyXMLSignatureResponse.setCertificateCheck(certificateCheck); - verifyXMLSignatureResponse.setAdESFormResults(adesFormResults); - verifyXMLSignatureResponse.setExtendedCertificateCheck(extCheckResult); - return verifyXMLSignatureResponse; - } - - public ReferencesCheckResult createReferencesCheckResult(int code, ReferencesCheckResultInfo info) { - ReferencesCheckResultImpl referencesCheckResult = new ReferencesCheckResultImpl(); - referencesCheckResult.setCode(code); - referencesCheckResult.setInfo(info); - return referencesCheckResult; - } - - public ReferencesCheckResultInfo createReferencesCheckResultInfo(NodeList anyOtherInfo, int[] failedReferences) { - ReferencesCheckResultInfoImpl referencesCheckResultInfo = new ReferencesCheckResultInfoImpl(); - referencesCheckResultInfo.setAnyOtherInfo(anyOtherInfo); - referencesCheckResultInfo.setFailedReferences(failedReferences); - return referencesCheckResultInfo; - } - - public ManifestRefsCheckResult createManifestRefsCheckResult(int code, ManifestRefsCheckResultInfo info) { - ManifestRefsCheckResultImpl manifestRefsCheckResult = new ManifestRefsCheckResultImpl(); - manifestRefsCheckResult.setCode(code); - manifestRefsCheckResult.setInfo(info); - return manifestRefsCheckResult; - } - - public ManifestRefsCheckResultInfo createManifestRefsCheckResultInfo(NodeList anyOtherInfo, int[] failedReferences, - int referringSigReference) { - ManifestRefsCheckResultInfoImpl manifestRefsCheckResultInfo = new ManifestRefsCheckResultInfoImpl(); - manifestRefsCheckResultInfo.setAnyOtherInfo(anyOtherInfo); - manifestRefsCheckResultInfo.setReferringSignatureReference(referringSigReference); - manifestRefsCheckResultInfo.setFailedReferences(failedReferences); - return manifestRefsCheckResultInfo; - } - - public Content createContent(InputStream binaryData, String referenceURI) { - ContentBinaryImpl content = new ContentBinaryImpl(); - content.setBinaryContent(binaryData); - content.setReference(referenceURI); - return content; - } - - public Content createContent(String locationReferenceURI, String referenceURI) { - ContentLocRefImpl content = new ContentLocRefImpl(); - content.setLocationReferenceURI(locationReferenceURI); - content.setReference(referenceURI); - return content; - } - - public Content createContent(String referenceURI) { - ContentReferenceImpl content = new ContentReferenceImpl(); - content.setReference(referenceURI); - return content; - } - - public Content createContent(NodeList xmlData, String referenceURI) { - ContentXMLImpl content = new ContentXMLImpl(); - content.setXMLContent(xmlData); - content.setReference(referenceURI); - return content; - } - - public XMLDataObjectAssociation createXMLDataObjectAssociation(MetaInfo metaInfo, Content xmlContent) { - XMLDataObjectAssociationImpl xmlDataObjectAssociation = new XMLDataObjectAssociationImpl(); - xmlDataObjectAssociation.setMetaInfo(metaInfo); - xmlDataObjectAssociation.setContent(xmlContent); - return xmlDataObjectAssociation; - } - - public MetaInfo createMetaInfo(String mimeType, String description, NodeList otherInfo, String type) { - MetaInfoImpl metaInfo = new MetaInfoImpl(); - metaInfo.setMimeType(mimeType); - metaInfo.setDescription(description); - metaInfo.setAnyElements(otherInfo); - metaInfo.setType(type); - return metaInfo; - } - - public Transform createCanonicalizationTransform(String algorithmURI) { - CanonicalizationTransformImpl transform = new CanonicalizationTransformImpl(algorithmURI); - return transform; - } - - public Transform createExclusiveCanonicalizationTransform(String algorithmURI, List inclusiveNamespacePrefixes) { - ExclusiveCanonicalizationTransformImpl transform = new ExclusiveCanonicalizationTransformImpl(algorithmURI); - transform.setInclusiveNamespacePrefixes(inclusiveNamespacePrefixes); - return transform; - } - - public Transform createBase64Transform() { - Base64TransformImpl transform = new Base64TransformImpl(); - return transform; - } - - public Transform createEnvelopedSignatureTransform() { - EnvelopedSignatureTransformImpl transform = new EnvelopedSignatureTransformImpl(); - return transform; - } - - public Transform createXSLTTransform(Element styleSheet) { - XSLTransformImpl transform = new XSLTransformImpl(); - transform.setStylesheet(styleSheet); - return transform; - } - - public Transform createXPathTransform(String xPathExpression, Map namespaceDeclarations) { - XPathTransformImpl transform = new XPathTransformImpl(); - transform.setXPathExpression(xPathExpression); - transform.setNamespaceDelcarations(namespaceDeclarations); - return transform; - } - - public Transform createXPathFilter2Transform(List xPathFilters) { - XPathFilter2TransformImpl transform = new XPathFilter2TransformImpl(); - transform.setFilters(xPathFilters); - return transform; - } - - public XPathFilter createXPathFilter(String filterType, String xPathExpression, Map namespaceDeclarations) { - XPathFilterImpl xPathFilter = new XPathFilterImpl(); - xPathFilter.setFilterType(filterType); - xPathFilter.setXPathExpression(xPathExpression); - xPathFilter.setNamespaceDelcarations(namespaceDeclarations); - return xPathFilter; - } - - public CheckResult createCheckResult(int code, NodeList info) { - CheckResultImpl checkResult = new CheckResultImpl(); - checkResult.setCode(code); - checkResult.setInfo(info); - return checkResult; - } - - public SignerInfo createSignerInfo(X509Certificate signerCertificate, boolean qualifiedCertificate, - boolean qcSourceTSL, boolean publicAuthority, String publicAuthorityID, boolean sscd, boolean sscdSourceTSL, - String issuerCountryCode, Date signingTime, TslInfos tslInfos) { - SignerInfoImpl signerInfo = new SignerInfoImpl(); - signerInfo.setSignerCertificate(signerCertificate); - signerInfo.setQualifiedCertificate(qualifiedCertificate); - signerInfo.setQCSourceTSL(qcSourceTSL); - signerInfo.setPublicAuthority(publicAuthority); - signerInfo.setPublicAuhtorityID(publicAuthorityID); - signerInfo.setSSCD(sscd); - signerInfo.setSSCDSourceTSL(sscdSourceTSL); - signerInfo.setIssuerCountryCode(issuerCountryCode); - signerInfo.setSigningTime(signingTime); - signerInfo.setTslInfos(tslInfos); - return signerInfo; - } - - public X509IssuerSerial createX509IssuerSerial(String issuerName, BigInteger serialNumber) { - X509IssuerSerialImpl x509IssuerSerial = new X509IssuerSerialImpl(); - x509IssuerSerial.setX509IssuerName(issuerName); - x509IssuerSerial.setX509SerialNumber(serialNumber); - return x509IssuerSerial; - } - - @Override - public VerifyXMLSignatureRequest createVerifyXMLSignatureRequest(Date dateTime, - VerifySignatureInfo verifySignatureInfo, List supplementProfiles, - SignatureManifestCheckParams signatureManifestParams, boolean returnHashInputData, String trustProfileID, - boolean extendedValidation) { - VerifyXMLSignatureRequestImpl verifyXMLSignatureRequest = new VerifyXMLSignatureRequestImpl(); - verifyXMLSignatureRequest.setDateTime(dateTime); - verifyXMLSignatureRequest.setSignatureInfo(verifySignatureInfo); - verifyXMLSignatureRequest.setSupplementProfiles(supplementProfiles); - verifyXMLSignatureRequest.setSignatureManifestCheckParams(signatureManifestParams); - verifyXMLSignatureRequest.setReturnHashInputData(returnHashInputData); - verifyXMLSignatureRequest.setTrustProfileId(trustProfileID); - verifyXMLSignatureRequest.setExtendedValidation(extendedValidation); - return verifyXMLSignatureRequest; - } + @Override + public CreateXMLSignatureRequest createCreateXMLSignatureRequest(String keyIdentifier, + List singleSignatureInfos) { + final CreateXMLSignatureRequestImpl createXMLSignatureRequest = new CreateXMLSignatureRequestImpl(); + createXMLSignatureRequest.setKeyIdentifier(keyIdentifier); + createXMLSignatureRequest.setSingleSignatureInfos(singleSignatureInfos); + return createXMLSignatureRequest; + } + + @Override + public CreateCMSSignatureRequest createCreateCMSSignatureRequest(String keyIdentifier, + List singleSignatureInfos) { + final CreateCMSSignatureRequestImpl createCMSSignatureRequest = new CreateCMSSignatureRequestImpl(); + createCMSSignatureRequest.setKeyIdentifier(keyIdentifier); + createCMSSignatureRequest.setSingleSignatureInfos(singleSignatureInfos); + return createCMSSignatureRequest; + + } + + @Override + public CreateCMSSignatureResponse createCreateCMSSignatureResponse(List responseElements) { + final CreateCMSSignatureResponseImpl createCMSSignatureResponse = new CreateCMSSignatureResponseImpl(); + createCMSSignatureResponse.setResponseElements(responseElements); + return createCMSSignatureResponse; + } + + @Override + public CMSSignatureResponse createCMSSignatureResponse(String base64value) { + final CMSSignatureResponseImpl cmsSignatureResponse = new CMSSignatureResponseImpl(); + cmsSignatureResponse.setCMSSignature(base64value); + + return cmsSignatureResponse; + } + + @Override + public SingleSignatureInfo createSingleSignatureInfo(List dataObjectInfos, + CreateSignatureInfo createSignatureInfo, + boolean securityLayerConform) { + final SingleSignatureInfoImpl singleSignatureInfo = new SingleSignatureInfoImpl(); + singleSignatureInfo.setDataObjectInfos(dataObjectInfos); + singleSignatureInfo.setCreateSignatureInfo(createSignatureInfo); + singleSignatureInfo.setSecurityLayerConform(securityLayerConform); + return singleSignatureInfo; + } + + @Override + public at.gv.egovernment.moa.spss.api.cmssign.SingleSignatureInfo createSingleSignatureInfoCMS( + at.gv.egovernment.moa.spss.api.cmssign.DataObjectInfo dataObjectInfo, boolean securityLayerConform, + boolean isPAdESConform) { + final SingleSignatureInfoCMSImpl singleSignatureInfo = new SingleSignatureInfoCMSImpl(); + singleSignatureInfo.setDataObjectInfo(dataObjectInfo); + singleSignatureInfo.setSecurityLayerConform(securityLayerConform); + singleSignatureInfo.setPAdESConform(isPAdESConform); + return singleSignatureInfo; + } + + @Override + public DataObjectInfo createDataObjectInfo(String structure, boolean childOfManifest, Content dataObject, + CreateTransformsInfoProfile createTransformsInfoProfile) { + final DataObjectInfoImpl dataObjectInfo = new DataObjectInfoImpl(); + dataObjectInfo.setStructure(structure); + dataObjectInfo.setChildOfManifest(childOfManifest); + dataObjectInfo.setDataObject(dataObject); + dataObjectInfo.setCreateTransformsInfoProfile(createTransformsInfoProfile); + return dataObjectInfo; + } + + @Override + public at.gv.egovernment.moa.spss.api.cmssign.DataObjectInfo createDataObjectInfo(String structure, + CMSDataObject dataObject) { + final DataObjectInfoCMSImpl dataObjectInfo = new DataObjectInfoCMSImpl(); + dataObjectInfo.setStructure(structure); + dataObjectInfo.setDataObject(dataObject); + return dataObjectInfo; + } + + @Override + public CreateTransformsInfoProfile createCreateTransformsInfoProfile(String profileID) { + + final CreateTransformsInfoProfileIDImpl createTransformsInfoProfile = + new CreateTransformsInfoProfileIDImpl(); + createTransformsInfoProfile.setCreateTransformsInfoProfileID(profileID); + return createTransformsInfoProfile; + } + + @Override + public CreateTransformsInfoProfile createCreateTransformsInfoProfile(CreateTransformsInfo transformsInfo, + List supplements) { + final CreateTransformsInfoProfileExplicitImpl createTransformsInfoProfile = + new CreateTransformsInfoProfileExplicitImpl(); + createTransformsInfoProfile.setCreateTransformsInfo(transformsInfo); + createTransformsInfoProfile.setSupplements(supplements); + return createTransformsInfoProfile; + } + + @Override + public CreateTransformsInfo createCreateTransformsInfo(List transforms, MetaInfo finalDataMetaInfo) { + final CreateTransformsInfoImpl createTransformsInfo = new CreateTransformsInfoImpl(); + + createTransformsInfo.setTransforms(transforms); + createTransformsInfo.setFinalDataMetaInfo(finalDataMetaInfo); + return createTransformsInfo; + } + + @Override + public CreateSignatureInfo createCreateSignatureInfo(Content createSignatureEnvironment, + CreateSignatureEnvironmentProfile createSignatureEnvironmentProfile) { + final CreateSignatureInfoImpl createSignatureInfo = new CreateSignatureInfoImpl(); + createSignatureInfo.setCreateSignatureEnvironment(createSignatureEnvironment); + createSignatureInfo.setCreateSignatureEnvironmentProfile(createSignatureEnvironmentProfile); + return createSignatureInfo; + } + + @Override + public CreateSignatureEnvironmentProfile createCreateSignatureEnvironmentProfile( + CreateSignatureLocation createSignatureLocation, List supplements) { + final CreateSignatureEnvironmentProfileExplicitImpl createSignatureEnvironmentProfile = + new CreateSignatureEnvironmentProfileExplicitImpl(); + createSignatureEnvironmentProfile.setCreateSignatureLocation(createSignatureLocation); + createSignatureEnvironmentProfile.setSupplements(supplements); + return createSignatureEnvironmentProfile; + } + + @Override + public CreateSignatureLocation createCreateSignatureLocation(String signatureLocationXPath, + int signatureLocationIndex, Map namespaceDeclarations) { + final CreateSignatureLocationImpl createSignatureLocation = new CreateSignatureLocationImpl(); + createSignatureLocation.setIndex(signatureLocationIndex); + createSignatureLocation.setNamespaceDeclarations(namespaceDeclarations); + createSignatureLocation.setXPathExpression(signatureLocationXPath); + return createSignatureLocation; + } + + @Override + public CreateSignatureEnvironmentProfile createCreateSignatureEnvironmentProfile(String profileID) { + final CreateSignatureEnvironmentProfileIDImpl createSignatureEnvironmentProfile = + new CreateSignatureEnvironmentProfileIDImpl(); + createSignatureEnvironmentProfile.setCreateSignatureEnvironmentProfileID(profileID); + return createSignatureEnvironmentProfile; + } + + @Override + public CreateXMLSignatureResponse createCreateXMLSignatureResponse(List responseElements) { + final CreateXMLSignatureResponseImpl createXMLSignatureResponse = new CreateXMLSignatureResponseImpl(); + createXMLSignatureResponse.setResponseElements(responseElements); + return createXMLSignatureResponse; + } + + @Override + public SignatureEnvironmentResponse createSignatureEnvironmentResponse(Element signatureEnvironment) { + final SignatureEnvironmentResponseImpl signatureEnvironmentResponse = + new SignatureEnvironmentResponseImpl(); + signatureEnvironmentResponse.setSignatureEnvironment(signatureEnvironment); + return signatureEnvironmentResponse; + } + + @Override + public ErrorResponse createErrorResponse(int code, String info) { + final ErrorResponseImpl errorResponse = new ErrorResponseImpl(); + errorResponse.setErrorCode(code); + errorResponse.setInfo(info); + return errorResponse; + } + + @Override + public VerifyCMSSignatureRequest createVerifyCMSSignatureRequest(int[] signatories, Date dateTime, + InputStream cmsSignature, CMSDataObject dataObject, String trustProfileID, boolean pdf) { + return this.createVerifyCMSSignatureRequest(signatories, dateTime, cmsSignature, dataObject, + trustProfileID, pdf, false); + } + + @Override + public VerifyCMSSignatureRequest createVerifyCMSSignatureRequest(int[] signatories, Date dateTime, + InputStream cmsSignature, CMSDataObject dataObject, String trustProfileID, boolean pdf, + boolean extended) { + final VerifyCMSSignatureRequestImpl verifyCMSSignatureRequest = new VerifyCMSSignatureRequestImpl(); + verifyCMSSignatureRequest.setDateTime(dateTime); + verifyCMSSignatureRequest.setCMSSignature(cmsSignature); + verifyCMSSignatureRequest.setDataObject(dataObject); + verifyCMSSignatureRequest.setTrustProfileId(trustProfileID); + verifyCMSSignatureRequest.setSignatories(signatories); + verifyCMSSignatureRequest.setPDF(pdf); + verifyCMSSignatureRequest.setExtended(extended); + return verifyCMSSignatureRequest; + } + + @Override + public CMSDataObject createCMSDataObject(MetaInfo metaInfo, CMSContent content, + BigDecimal excludeByteRangeFrom, + BigDecimal excludeByteRangeTo) { + + final CMSDataObjectImpl cmsDataObject = new CMSDataObjectImpl(); + cmsDataObject.setMetaInfo(metaInfo); + cmsDataObject.setContent(content); + cmsDataObject.setExcludeByteRangeFrom(excludeByteRangeFrom); + cmsDataObject.setExcludeByteRangeTo(excludeByteRangeTo); + + return cmsDataObject; + } + + @Override + public CMSContent createCMSContent(InputStream binaryContent) { + final CMSContentExplicitImpl cmsContent = new CMSContentExplicitImpl(); + + cmsContent.setBinaryContent(binaryContent); + return cmsContent; + } + + @Override + public CMSContent createCMSContent(String referenceURI) { + final CMSContentReferenceImpl cmsContent = new CMSContentReferenceImpl(); + + cmsContent.setReference(referenceURI); + return cmsContent; + } + + public CMSDataObject createCMSDataObject(MetaInfo metaInfo, String referenceURI) { + final CMSDataObjectImpl cmsDataObject = new CMSDataObjectImpl(); + final CMSContentReferenceImpl cmsContent = new CMSContentReferenceImpl(); + cmsDataObject.setMetaInfo(metaInfo); + cmsContent.setReference(referenceURI); + return cmsDataObject; + } + + @Override + public VerifyCMSSignatureResponse createVerifyCMSSignatureResponse(List responseElements) { + final VerifyCMSSinatureResponseImpl verifyCMSSignatureResponse = new VerifyCMSSinatureResponseImpl(); + verifyCMSSignatureResponse.setResponseElements(responseElements); + return verifyCMSSignatureResponse; + } + + @Override + public VerifyCMSSignatureResponseElement createVerifyCMSSignatureResponseElement(SignerInfo signerInfo, + CheckResult signatureCheck, CheckResult certificateCheck, List adesResult, + ExtendedCertificateCheckResult extendedCertificateCheckResult, String usedAlgorithm, + Boolean coversFullDocument, + int[] byteRangeOfSignature) { + final VerifyCMSSignatureResponseElementImpl verifyCMSSignatureResponseElement = + new VerifyCMSSignatureResponseElementImpl(); + verifyCMSSignatureResponseElement.setSignerInfo(signerInfo); + verifyCMSSignatureResponseElement.setSignatureCheck(signatureCheck); + verifyCMSSignatureResponseElement.setCertificateCheck(certificateCheck); + verifyCMSSignatureResponseElement.setAdESFormResults(adesResult); + verifyCMSSignatureResponseElement.setExtendedCertificateCheck(extendedCertificateCheckResult); + verifyCMSSignatureResponseElement.setSignatureAlgorithm(usedAlgorithm); + verifyCMSSignatureResponseElement.setCoversFullDocument(coversFullDocument); + verifyCMSSignatureResponseElement.setByteRangeOfSignature(byteRangeOfSignature); + return verifyCMSSignatureResponseElement; + } + + @Override + public VerifyXMLSignatureRequest createVerifyXMLSignatureRequest(Date dateTime, + VerifySignatureInfo verifySignatureInfo, List supplementProfiles, + SignatureManifestCheckParams signatureManifestParams, boolean returnHashInputData, + String trustProfileID) { + return this.createVerifyXMLSignatureRequest(dateTime, verifySignatureInfo, supplementProfiles, + signatureManifestParams, returnHashInputData, trustProfileID, false); + } + + @Override + public VerifySignatureInfo createVerifySignatureInfo(Content verifySignatureEnvironment, + VerifySignatureLocation verifySignatureLocation) { + final VerifySignatureInfoImpl verifySignatureInfo = new VerifySignatureInfoImpl(); + verifySignatureInfo.setVerifySignatureEnvironment(verifySignatureEnvironment); + verifySignatureInfo.setVerifySignatureLocation(verifySignatureLocation); + return verifySignatureInfo; + } + + @Override + public VerifySignatureLocation createVerifySignatureLocation(String xPathExpression, + Map namespaceDeclarations) { + final VerifySignatureLocationImpl verifySignatureLocation = new VerifySignatureLocationImpl(); + verifySignatureLocation.setXPathExpression(xPathExpression); + verifySignatureLocation.setNamespaceDeclarations(namespaceDeclarations); + return verifySignatureLocation; + } + + @Override + public SupplementProfile createSupplementProfile(String profileID) { + final SupplementProfileIDImpl supplementProfileID = new SupplementProfileIDImpl(); + supplementProfileID.setSupplementProfileID(profileID); + return supplementProfileID; + } + + @Override + public SupplementProfile createSupplementProfile(XMLDataObjectAssociation supplementProfile) { + final SupplementProfileExplicitImpl supplementProfileExplicit = new SupplementProfileExplicitImpl(); + supplementProfileExplicit.setSupplementProfile(supplementProfile); + return supplementProfileExplicit; + } + + @Override + public SignatureManifestCheckParams createSignatureManifestCheckParams(List referenceInfos, + boolean returnReferenceInputData) { + final SignatureManifestCheckParamsImpl signatureManifestCheckParams = + new SignatureManifestCheckParamsImpl(); + signatureManifestCheckParams.setReferenceInfos(referenceInfos); + signatureManifestCheckParams.setReturnReferenceInputData(returnReferenceInputData); + return signatureManifestCheckParams; + } + + @Override + public ReferenceInfo createReferenceInfo(List verifyTransformsInfoProfiles) { + final ReferenceInfoImpl referenceInfo = new ReferenceInfoImpl(); + referenceInfo.setVerifyTransformsInfoProfiles(verifyTransformsInfoProfiles); + return referenceInfo; + } + + @Override + public VerifyTransformsInfoProfile createVerifyTransformsInfoProfile(List transforms, + List transformParameters) { + final VerifyTransformsInfoProfileExplicitImpl verifyTransformsInfoProfile = + new VerifyTransformsInfoProfileExplicitImpl(); + + verifyTransformsInfoProfile.setTransforms(transforms); + verifyTransformsInfoProfile.setTransformParameters(transformParameters); + + return verifyTransformsInfoProfile; + } + + @Override + public VerifyTransformsInfoProfile createVerifyTransformsInfoProfile(String profileID) { + final VerifyTransformsInfoProfileIDImpl verifyTransformsInfoProfile = + new VerifyTransformsInfoProfileIDImpl(); + verifyTransformsInfoProfile.setVerifyTransformsInfoProfileID(profileID); + return verifyTransformsInfoProfile; + } + + @Override + public TransformParameter createTransformParameter(String URI, String digestMethod, byte[] digestValue) { + final TransformPatameterHashImpl transformParameter = new TransformPatameterHashImpl(); + transformParameter.setURI(URI); + transformParameter.setDigestMethod(digestMethod); + transformParameter.setDigestValue(digestValue); + return transformParameter; + } + + @Override + public TransformParameter createTransformParameter(String URI, InputStream binaryData) { + final TransformParameterBinaryImpl transformParameter = new TransformParameterBinaryImpl(); + transformParameter.setURI(URI); + transformParameter.setBinaryContent(binaryData); + return transformParameter; + } + + @Override + public TransformParameter createTransformParameter(String URI) { + final TransformParameterURIImpl transformParameter = new TransformParameterURIImpl(); + transformParameter.setURI(URI); + return transformParameter; + } + + @Override + public VerifyXMLSignatureResponse createVerifyXMLSignatureResponse(SignerInfo signerInfo, + List hashInputDatas, + List referenceInputDatas, ReferencesCheckResult signatureCheck, + ReferencesCheckResult signatureManifestCheck, List xmlDsigManifestChecks, CheckResult certificateCheck, + List adesFormResults, ExtendedCertificateCheckResult extCheckResult, String signatureAlgorithm) { + final VerifyXMLSignatureResponseImpl verifyXMLSignatureResponse = new VerifyXMLSignatureResponseImpl(); + verifyXMLSignatureResponse.setSignerInfo(signerInfo); + verifyXMLSignatureResponse.setHashInputDatas(hashInputDatas); + verifyXMLSignatureResponse.setReferenceInputDatas(referenceInputDatas); + verifyXMLSignatureResponse.setSignatureAlgorithm(signatureAlgorithm); + verifyXMLSignatureResponse.setSignatureCheck(signatureCheck); + verifyXMLSignatureResponse.setSignatureManifestCheck(signatureManifestCheck); + verifyXMLSignatureResponse.setXMLDsigManifestChecks(xmlDsigManifestChecks); + verifyXMLSignatureResponse.setCertificateCheck(certificateCheck); + verifyXMLSignatureResponse.setAdESFormResults(adesFormResults); + verifyXMLSignatureResponse.setExtendedCertificateCheck(extCheckResult); + return verifyXMLSignatureResponse; + } + + @Override + public ReferencesCheckResult createReferencesCheckResult(int code, ReferencesCheckResultInfo info) { + final ReferencesCheckResultImpl referencesCheckResult = new ReferencesCheckResultImpl(); + referencesCheckResult.setCode(code); + referencesCheckResult.setInfo(info); + return referencesCheckResult; + } + + @Override + public ReferencesCheckResultInfo createReferencesCheckResultInfo(NodeList anyOtherInfo, + int[] failedReferences) { + final ReferencesCheckResultInfoImpl referencesCheckResultInfo = new ReferencesCheckResultInfoImpl(); + referencesCheckResultInfo.setAnyOtherInfo(anyOtherInfo); + referencesCheckResultInfo.setFailedReferences(failedReferences); + return referencesCheckResultInfo; + } + + @Override + public ManifestRefsCheckResult createManifestRefsCheckResult(int code, ManifestRefsCheckResultInfo info) { + final ManifestRefsCheckResultImpl manifestRefsCheckResult = new ManifestRefsCheckResultImpl(); + manifestRefsCheckResult.setCode(code); + manifestRefsCheckResult.setInfo(info); + return manifestRefsCheckResult; + } + + @Override + public ManifestRefsCheckResultInfo createManifestRefsCheckResultInfo(NodeList anyOtherInfo, + int[] failedReferences, + int referringSigReference) { + final ManifestRefsCheckResultInfoImpl manifestRefsCheckResultInfo = new ManifestRefsCheckResultInfoImpl(); + manifestRefsCheckResultInfo.setAnyOtherInfo(anyOtherInfo); + manifestRefsCheckResultInfo.setReferringSignatureReference(referringSigReference); + manifestRefsCheckResultInfo.setFailedReferences(failedReferences); + return manifestRefsCheckResultInfo; + } + + @Override + public Content createContent(InputStream binaryData, String referenceURI) { + final ContentBinaryImpl content = new ContentBinaryImpl(); + content.setBinaryContent(binaryData); + content.setReference(referenceURI); + return content; + } + + @Override + public Content createContent(String locationReferenceURI, String referenceURI) { + final ContentLocRefImpl content = new ContentLocRefImpl(); + content.setLocationReferenceURI(locationReferenceURI); + content.setReference(referenceURI); + return content; + } + + @Override + public Content createContent(String referenceURI) { + final ContentReferenceImpl content = new ContentReferenceImpl(); + content.setReference(referenceURI); + return content; + } + + @Override + public Content createContent(NodeList xmlData, String referenceURI) { + final ContentXMLImpl content = new ContentXMLImpl(); + content.setXMLContent(xmlData); + content.setReference(referenceURI); + return content; + } + + @Override + public XMLDataObjectAssociation createXMLDataObjectAssociation(MetaInfo metaInfo, Content xmlContent) { + final XMLDataObjectAssociationImpl xmlDataObjectAssociation = new XMLDataObjectAssociationImpl(); + xmlDataObjectAssociation.setMetaInfo(metaInfo); + xmlDataObjectAssociation.setContent(xmlContent); + return xmlDataObjectAssociation; + } + + @Override + public MetaInfo createMetaInfo(String mimeType, String description, NodeList otherInfo, String type) { + final MetaInfoImpl metaInfo = new MetaInfoImpl(); + metaInfo.setMimeType(mimeType); + metaInfo.setDescription(description); + metaInfo.setAnyElements(otherInfo); + metaInfo.setType(type); + return metaInfo; + } + + @Override + public Transform createCanonicalizationTransform(String algorithmURI) { + final CanonicalizationTransformImpl transform = new CanonicalizationTransformImpl(algorithmURI); + return transform; + } + + @Override + public Transform createExclusiveCanonicalizationTransform(String algorithmURI, + List inclusiveNamespacePrefixes) { + final ExclusiveCanonicalizationTransformImpl transform = new ExclusiveCanonicalizationTransformImpl( + algorithmURI); + transform.setInclusiveNamespacePrefixes(inclusiveNamespacePrefixes); + return transform; + } + + @Override + public Transform createBase64Transform() { + final Base64TransformImpl transform = new Base64TransformImpl(); + return transform; + } + + @Override + public Transform createEnvelopedSignatureTransform() { + final EnvelopedSignatureTransformImpl transform = new EnvelopedSignatureTransformImpl(); + return transform; + } + + @Override + public Transform createXSLTTransform(Element styleSheet) { + final XSLTransformImpl transform = new XSLTransformImpl(); + transform.setStylesheet(styleSheet); + return transform; + } + + @Override + public Transform createXPathTransform(String xPathExpression, Map namespaceDeclarations) { + final XPathTransformImpl transform = new XPathTransformImpl(); + transform.setXPathExpression(xPathExpression); + transform.setNamespaceDelcarations(namespaceDeclarations); + return transform; + } + + @Override + public Transform createXPathFilter2Transform(List xPathFilters) { + final XPathFilter2TransformImpl transform = new XPathFilter2TransformImpl(); + transform.setFilters(xPathFilters); + return transform; + } + + @Override + public XPathFilter createXPathFilter(String filterType, String xPathExpression, Map namespaceDeclarations) { + final XPathFilterImpl xPathFilter = new XPathFilterImpl(); + xPathFilter.setFilterType(filterType); + xPathFilter.setXPathExpression(xPathExpression); + xPathFilter.setNamespaceDelcarations(namespaceDeclarations); + return xPathFilter; + } + + @Override + public CheckResult createCheckResult(int code, NodeList info) { + final CheckResultImpl checkResult = new CheckResultImpl(); + checkResult.setCode(code); + checkResult.setInfo(info); + return checkResult; + } + + @Override + public SignerInfo createSignerInfo(X509Certificate signerCertificate, boolean qualifiedCertificate, + boolean qcSourceTSL, boolean publicAuthority, String publicAuthorityID, boolean sscd, + boolean sscdSourceTSL, + String issuerCountryCode, Date signingTime, TslInfos tslInfos) { + final SignerInfoImpl signerInfo = new SignerInfoImpl(); + signerInfo.setSignerCertificate(signerCertificate); + signerInfo.setQualifiedCertificate(qualifiedCertificate); + signerInfo.setQCSourceTSL(qcSourceTSL); + signerInfo.setPublicAuthority(publicAuthority); + signerInfo.setPublicAuhtorityID(publicAuthorityID); + signerInfo.setSSCD(sscd); + signerInfo.setSSCDSourceTSL(sscdSourceTSL); + signerInfo.setIssuerCountryCode(issuerCountryCode); + signerInfo.setSigningTime(signingTime); + signerInfo.setTslInfos(tslInfos); + return signerInfo; + } + + @Override + public X509IssuerSerial createX509IssuerSerial(String issuerName, BigInteger serialNumber) { + final X509IssuerSerialImpl x509IssuerSerial = new X509IssuerSerialImpl(); + x509IssuerSerial.setX509IssuerName(issuerName); + x509IssuerSerial.setX509SerialNumber(serialNumber); + return x509IssuerSerial; + } + + @Override + public VerifyXMLSignatureRequest createVerifyXMLSignatureRequest(Date dateTime, + VerifySignatureInfo verifySignatureInfo, List supplementProfiles, + SignatureManifestCheckParams signatureManifestParams, boolean returnHashInputData, + String trustProfileID, + boolean extendedValidation) { + final VerifyXMLSignatureRequestImpl verifyXMLSignatureRequest = new VerifyXMLSignatureRequestImpl(); + verifyXMLSignatureRequest.setDateTime(dateTime); + verifyXMLSignatureRequest.setSignatureInfo(verifySignatureInfo); + verifyXMLSignatureRequest.setSupplementProfiles(supplementProfiles); + verifyXMLSignatureRequest.setSignatureManifestCheckParams(signatureManifestParams); + verifyXMLSignatureRequest.setReturnHashInputData(returnHashInputData); + verifyXMLSignatureRequest.setTrustProfileId(trustProfileID); + verifyXMLSignatureRequest.setExtendedValidation(extendedValidation); + return verifyXMLSignatureRequest; + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SignatureEnvironmentResponseImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SignatureEnvironmentResponseImpl.java index 4b50d89..1fc3cdc 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SignatureEnvironmentResponseImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SignatureEnvironmentResponseImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import org.w3c.dom.Element; @@ -30,34 +29,36 @@ import at.gv.egovernment.moa.spss.api.xmlsign.SignatureEnvironmentResponse; /** * Default implementation of SignatureEnvironmentResponse. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class SignatureEnvironmentResponseImpl - implements SignatureEnvironmentResponse { + implements SignatureEnvironmentResponse { /** The signature environment containing the XML signature. */ private Element signatureEnvironment; - /** + /** * Sets the XML structure which contains the signature. - * + * * @param signatureEnvironment A general XML structure containing the signature. */ public void setSignatureEnvironment(Element signatureEnvironment) { this.signatureEnvironment = signatureEnvironment; } + @Override public Element getSignatureEnvironment() { return signatureEnvironment; } /** * Gets the type of CreateXMLSignatureResponseElement. - * + * * @return SIGNATURE_ENVIRONMENT_RESPONSE */ + @Override public int getResponseType() { return SIGNATURE_ENVIRONMENT_RESPONSE; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SignatureManifestCheckParamsImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SignatureManifestCheckParamsImpl.java index 40e87e7..4d4fb64 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SignatureManifestCheckParamsImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SignatureManifestCheckParamsImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.util.ArrayList; @@ -32,12 +31,12 @@ import at.gv.egovernment.moa.spss.api.xmlverify.SignatureManifestCheckParams; /** * Default implementation of SignatureManifestCheckParams. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class SignatureManifestCheckParamsImpl - implements SignatureManifestCheckParams { + implements SignatureManifestCheckParams { /** Referential information. */ private List referenceInfos; @@ -46,29 +45,31 @@ public class SignatureManifestCheckParamsImpl /** * Sets the referantial information. - * + * * @param referenceInfos The referential information. */ public void setReferenceInfos(List referenceInfos) { this.referenceInfos = - referenceInfos != null - ? Collections.unmodifiableList(new ArrayList(referenceInfos)) - : null; + referenceInfos != null + ? Collections.unmodifiableList(new ArrayList(referenceInfos)) + : null; } + @Override public List getReferenceInfos() { return referenceInfos; } - + /** * Sets whether to return signature source data. - * + * * @param returnReferenceInputData Whether to return signature source data. */ public void setReturnReferenceInputData(boolean returnReferenceInputData) { this.returnReferenceInputData = returnReferenceInputData; } + @Override public boolean getReturnReferenceInputData() { return returnReferenceInputData; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SignerInfoImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SignerInfoImpl.java index 57a60a6..988ae00 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SignerInfoImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SignerInfoImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.security.cert.X509Certificate; @@ -32,7 +31,7 @@ import at.gv.egovernment.moa.spss.api.common.TslInfos; /** * Default implementation of SignerInfo. - * + * * @author Fatemeh Philippi * @version $Id$ */ @@ -40,145 +39,161 @@ public class SignerInfoImpl implements SignerInfo { /** The signer certificate. */ private X509Certificate signerCertificate; - /** Determines, whether signerCertificate is a qualified - * certificate. */ + /** + * Determines, whether signerCertificate is a qualified + * certificate. + */ private boolean qualifiedCertificate; - /** Determines, whether signerCertificate is from a public - * authority. */ + /** + * Determines, whether signerCertificate is from a public + * authority. + */ private boolean publicAuthority; /** The public authority ID of the signerCertificate. */ private String publicAuthorityID; /** Determines, whether the signature is based on an SSCD */ private boolean sscd; - + /** Determines, if the SSCD check bases upon on TSL */ private boolean sscdSourceTSL; - + /** Determines, if the QC check bases upon on TSL */ private boolean qcSourceTSL; - + /** The certificate issuer country code */ private String issuerCountryCode; - private Date signingTime; - private TslInfos tslInfos; + private Date signingTime; + private TslInfos tslInfos; /** - * Sets the signer certificate. - * - * @param signerCertificate The signer certificate. - */ + * Sets the signer certificate. + * + * @param signerCertificate The signer certificate. + */ public void setSignerCertificate(X509Certificate signerCertificate) { this.signerCertificate = signerCertificate; } + @Override public X509Certificate getSignerCertificate() { return signerCertificate; } /** * Sets, whether the certificate contained in this object is qualified or not. - * - * @param qualifiedCertificate Is true, if the certificate is - * qualified, otherwise false. + * + * @param qualifiedCertificate Is true, if the certificate is + * qualified, otherwise false. */ public void setQualifiedCertificate(boolean qualifiedCertificate) { this.qualifiedCertificate = qualifiedCertificate; } + @Override public boolean isQualifiedCertificate() { return qualifiedCertificate; } /** * Sets, whether the signature is based on an SSCS or not. - * - * @param sscd Is true, if the signature is - * based on an SSCD, otherwise false. + * + * @param sscd Is true, if the signature is based on an SSCD, + * otherwise false. */ public void setSSCD(boolean sscd) { this.sscd = sscd; } + + @Override public boolean isSSCD() { - return sscd; + return sscd; } - + public void setSSCDSourceTSL(boolean sscdSourceTSL) { - this.sscdSourceTSL = sscdSourceTSL; + this.sscdSourceTSL = sscdSourceTSL; } - + + @Override public String getSSCDSource() { - if (sscdSourceTSL) - return "TSL"; - else - return "Certificate"; + if (sscdSourceTSL) { + return "TSL"; + } else { + return "Certificate"; + } } - public Date getSigningTime() { - return signingTime; - } + @Override + public Date getSigningTime() { + return signingTime; + } - public void setSigningTime(Date signingTime) { - this.signingTime = signingTime; - } + public void setSigningTime(Date signingTime) { + this.signingTime = signingTime; + } - public void setQCSourceTSL(boolean qcSourceTSL) { - this.qcSourceTSL = qcSourceTSL; + public void setQCSourceTSL(boolean qcSourceTSL) { + this.qcSourceTSL = qcSourceTSL; } - + + @Override public String getQCSource() { - if (this.qcSourceTSL) - return "TSL"; - else - return "Certificate"; + if (this.qcSourceTSL) { + return "TSL"; + } else { + return "Certificate"; + } } - + public void setIssuerCountryCode(String issuerCountryCode) { - this.issuerCountryCode = issuerCountryCode; + this.issuerCountryCode = issuerCountryCode; } - public String getIssuerCountryCode() { - return issuerCountryCode; - } - + + @Override + public String getIssuerCountryCode() { + return issuerCountryCode; + } + /** - * Sets, whether the certificate contained in this object is an - * e-government certificate or not. - * - * @param publicAuthority Is true, if the certificate is - * public authority certificate, otherwise false. + * Sets, whether the certificate contained in this object is an e-government + * certificate or not. + * + * @param publicAuthority Is true, if the certificate is public + * authority certificate, otherwise false. */ public void setPublicAuthority(boolean publicAuthority) { this.publicAuthority = publicAuthority; } + @Override public boolean isPublicAuthority() { return publicAuthority; } /** * Sets the public authority ID of the signer certificate. - * + * * @param publicAuhtorityID The public authority ID of the signer certificate. */ public void setPublicAuhtorityID(String publicAuhtorityID) { this.publicAuthorityID = publicAuhtorityID; } + @Override public String getPublicAuhtorityID() { return publicAuthorityID; } @Override public TslInfos getTslInfos() { - return this.tslInfos; - - } + return this.tslInfos; + } public void setTslInfos(TslInfos tslInfos) { - this.tslInfos = tslInfos; - + this.tslInfos = tslInfos; + } - - } + +} diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SingleSignatureInfoCMSImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SingleSignatureInfoCMSImpl.java index c8558dc..bbe3ea5 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SingleSignatureInfoCMSImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SingleSignatureInfoCMSImpl.java @@ -21,13 +21,8 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - import at.gv.egovernment.moa.spss.api.cmssign.DataObjectInfo; import at.gv.egovernment.moa.spss.api.cmssign.SingleSignatureInfo; @@ -38,7 +33,6 @@ public class SingleSignatureInfoCMSImpl implements SingleSignatureInfo { private DataObjectInfo dataObjectInfo = null; - private boolean securityLayerConform = true; private boolean padesConform = false; @@ -46,22 +40,25 @@ public class SingleSignatureInfoCMSImpl implements SingleSignatureInfo { this.dataObjectInfo = dataObjectInfo; } + @Override public DataObjectInfo getDataObjectInfo() { return dataObjectInfo; } + @Override public boolean isPAdESConform() { - return padesConform; + return padesConform; } public void setPAdESConform(boolean padesConform) { - this.padesConform = padesConform; + this.padesConform = padesConform; } -public void setSecurityLayerConform(boolean securityLayerConform) { + public void setSecurityLayerConform(boolean securityLayerConform) { this.securityLayerConform = securityLayerConform; } + @Override public boolean isSecurityLayerConform() { return securityLayerConform; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SingleSignatureInfoImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SingleSignatureInfoImpl.java index 3d43068..1fc20a0 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SingleSignatureInfoImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SingleSignatureInfoImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.util.ArrayList; @@ -45,11 +44,12 @@ public class SingleSignatureInfoImpl implements SingleSignatureInfo { public void setDataObjectInfos(List dataObjectInfos) { this.dataObjectInfos = - dataObjectInfos != null - ? Collections.unmodifiableList(new ArrayList(dataObjectInfos)) - : null; + dataObjectInfos != null + ? Collections.unmodifiableList(new ArrayList(dataObjectInfos)) + : null; } + @Override public List getDataObjectInfos() { return dataObjectInfos; } @@ -58,6 +58,7 @@ public class SingleSignatureInfoImpl implements SingleSignatureInfo { this.createSignatureInfo = createSignatureInfo; } + @Override public CreateSignatureInfo getCreateSignatureInfo() { return createSignatureInfo; } @@ -66,6 +67,7 @@ public class SingleSignatureInfoImpl implements SingleSignatureInfo { this.securityLayerConform = securityLayerConform; } + @Override public boolean isSecurityLayerConform() { return securityLayerConform; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SupplementProfileExplicitImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SupplementProfileExplicitImpl.java index 7f80388..82a1a0d 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SupplementProfileExplicitImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SupplementProfileExplicitImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.common.XMLDataObjectAssociation; @@ -29,7 +28,7 @@ import at.gv.egovernment.moa.spss.api.xmlverify.SupplementProfileExplicit; /** * Default implementation of SupplementProfileExplicit. - * + * * @author Fatemeh Philippi * @version $Id$ */ @@ -40,22 +39,24 @@ public class SupplementProfileExplicitImpl implements SupplementProfileExplicit /** * Sets the supplemental information for verifying a signature. - * + * * @param supplement The supplemental information for verifying a signature. */ public void setSupplementProfile(XMLDataObjectAssociation supplement) { this.supplement = supplement; } - + + @Override public XMLDataObjectAssociation getSupplementProfile() { return supplement; } /** * Gets the type of SupplementProfile. - * + * * @return EXPLICIT_SUPPLEMENTPROFILE */ + @Override public int getSupplementProfileType() { return EXPLICIT_SUPPLEMENTPROFILE; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SupplementProfileIDImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SupplementProfileIDImpl.java index e73ce60..7e64c93 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SupplementProfileIDImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/SupplementProfileIDImpl.java @@ -21,39 +21,40 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.xmlverify.SupplementProfileID; /** * Default implementation of SupplementProfileID. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class SupplementProfileIDImpl implements SupplementProfileID { /** The profile ID. */ private String profileID; - + /** * Sets the SupplementProfile profile ID. - * + * * @param profileID The profile ID. */ public void setSupplementProfileID(String profileID) { this.profileID = profileID; } + @Override public String getSupplementProfileID() { return profileID; } /** * Gets the type of SupplementProfile. - * + * * @return ID_SUPPLEMENTPROFILE */ + @Override public int getSupplementProfileType() { return ID_SUPPLEMENTPROFILE; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TSLConfigurationImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TSLConfigurationImpl.java index 6fa813f..cf3bfc7 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TSLConfigurationImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TSLConfigurationImpl.java @@ -21,99 +21,101 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; -import iaik.xml.crypto.utils.URI; - import java.util.ArrayList; import java.util.Date; import java.util.List; import at.gv.egovernment.moa.spss.api.common.TSLConfiguration; +import iaik.xml.crypto.utils.URI; /** * Default implementation of TSLConfiguration. - * + * * @author kstranacher */ public class TSLConfigurationImpl implements TSLConfiguration { - - - /** The EU TSL URL. */ - private String euTSLUrl; - - /** update period in milliseconds */ - private long updateSchedulePeriod; - - /** Time of the first update */ - private Date updateScheduleStartTime; - - /** Working directory */ - private String workingDirectory; - - /** Working directory */ - private URI workingDirectoryAsURI; - - private List qualifierForQC = new ArrayList(); - private List qualifierForSSCD = new ArrayList(); - + /** The EU TSL URL. */ + private String euTSLUrl; + + /** update period in milliseconds */ + private long updateSchedulePeriod; + + /** Time of the first update */ + private Date updateScheduleStartTime; + + /** Working directory */ + private String workingDirectory; + + /** Working directory */ + private URI workingDirectoryAsURI; + + private final List qualifierForQC = new ArrayList<>(); + private final List qualifierForSSCD = new ArrayList<>(); + + @Override public String getEuTSLUrl() { - return this.euTSLUrl; + return this.euTSLUrl; } + @Override public long getUpdateSchedulePeriod() { - return this.updateSchedulePeriod; + return this.updateSchedulePeriod; } + @Override public Date getUpdateScheduleStartTime() { - return this.updateScheduleStartTime; + return this.updateScheduleStartTime; } + @Override public String getWorkingDirectory() { - return this.workingDirectory; + return this.workingDirectory; } - + + @Override public URI getWorkingDirectoryAsURI() { - return this.workingDirectoryAsURI; + return this.workingDirectoryAsURI; } - public void setEuTSLUrl(String euTSLUrl) { - this.euTSLUrl = euTSLUrl; - } - - public void setUpdateSchedulePeriod(long updateSchedulePeriod) { - this.updateSchedulePeriod = updateSchedulePeriod; - } - - public void setUpdateScheduleStartTime(Date updateScheduleStartTime) { - this.updateScheduleStartTime = updateScheduleStartTime; - } - - public void setWorkingDirectory(String workingDirectory) { - this.workingDirectory = workingDirectory; - } - - public void setWorkingDirectoryURI(URI workingDirectoryAsURI) { - this.workingDirectoryAsURI = workingDirectoryAsURI; - } - - public List getQualifierForQC() { - return qualifierForQC; - } - - public List getQualifierForSSCD() { - return qualifierForSSCD; - } - - public void addQualifierForQC(java.net.URI qualifier) { - qualifierForQC.add(qualifier); - } - - public void addQualifierForSSCD(java.net.URI qualifier) { - qualifierForSSCD.add(qualifier); - } - + public void setEuTSLUrl(String euTSLUrl) { + this.euTSLUrl = euTSLUrl; + } + + public void setUpdateSchedulePeriod(long updateSchedulePeriod) { + this.updateSchedulePeriod = updateSchedulePeriod; + } + + public void setUpdateScheduleStartTime(Date updateScheduleStartTime) { + this.updateScheduleStartTime = updateScheduleStartTime; + } + + public void setWorkingDirectory(String workingDirectory) { + this.workingDirectory = workingDirectory; + } + + public void setWorkingDirectoryURI(URI workingDirectoryAsURI) { + this.workingDirectoryAsURI = workingDirectoryAsURI; + } + + @Override + public List getQualifierForQC() { + return qualifierForQC; + } + + @Override + public List getQualifierForSSCD() { + return qualifierForSSCD; + } + + public void addQualifierForQC(java.net.URI qualifier) { + qualifierForQC.add(qualifier); + } + + public void addQualifierForSSCD(java.net.URI qualifier) { + qualifierForSSCD.add(qualifier); + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TransformImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TransformImpl.java index 37a05f9..c72a445 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TransformImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TransformImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.common.Transform; @@ -36,13 +35,14 @@ public class TransformImpl implements Transform { /** * Sets the URI identifying the transformation algorithm. - * + * * @param algorithmURI The URI identifying the transformation algorithm. */ public void setAlgorithmURI(String algorithmURI) { this.algorithmURI = algorithmURI; } + @Override public String getAlgorithmURI() { return algorithmURI; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TransformParameterBinaryImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TransformParameterBinaryImpl.java index 691f3a9..915aff3 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TransformParameterBinaryImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TransformParameterBinaryImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.io.InputStream; @@ -30,35 +29,37 @@ import at.gv.egovernment.moa.spss.api.xmlverify.TransformParameterBinary; /** * Default implementation of TransformParameterBinary. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class TransformParameterBinaryImpl - extends TransformParameterImpl - implements TransformParameterBinary { - + extends TransformParameterImpl + implements TransformParameterBinary { + /** The binary content as a stream. */ private InputStream binaryContent; /** * Sets the binary content as a stream. - * + * * @param binaryContent The binary content as a stream. */ public void setBinaryContent(InputStream binaryContent) { this.binaryContent = binaryContent; } + @Override public InputStream getBinaryContent() { return binaryContent; } /** * Gets the TransformParameter type. - * + * * @return BINARY_TRANSFORMPARAMETER */ + @Override public int getTransformParameterType() { return BINARY_TRANSFORMPARAMETER; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TransformParameterImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TransformParameterImpl.java index 1399c6e..1837d0f 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TransformParameterImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TransformParameterImpl.java @@ -21,12 +21,11 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; /** * Default base implementation of TransformParameter. - * + * * @author Patrick Peck * @version $Id$ */ @@ -36,6 +35,7 @@ public abstract class TransformParameterImpl { /** * Sets the URI identifying the TransformParameter. + * * @param uri The URI identifying the TransformParameter. */ public void setURI(String uri) { diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TransformParameterURIImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TransformParameterURIImpl.java index 77810be..2671623 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TransformParameterURIImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TransformParameterURIImpl.java @@ -21,26 +21,26 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.xmlverify.TransformParameterURI; /** * Default implementation of TransformParameterURI. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class TransformParameterURIImpl - extends TransformParameterImpl - implements TransformParameterURI { + extends TransformParameterImpl + implements TransformParameterURI { /** * Gets the type of TransformParameter. - * + * * @return URI_TRANSFORMPARAMETER */ + @Override public int getTransformParameterType() { return URI_TRANSFORMPARAMETER; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TransformPatameterHashImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TransformPatameterHashImpl.java index 7fcd72c..79fd640 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TransformPatameterHashImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TransformPatameterHashImpl.java @@ -21,20 +21,19 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.xmlverify.TransformParameterHash; /** * Default implementation of TransformParameterHash - * + * * @author Fatemeh Philippi * @version $Id$ */ public class TransformPatameterHashImpl - extends TransformParameterImpl - implements TransformParameterHash { + extends TransformParameterImpl + implements TransformParameterHash { /** The method used to calculate the digest value. */ private String digestMethod; @@ -43,34 +42,38 @@ public class TransformPatameterHashImpl /** * Sets method used to calculate the digest value. + * * @param digestMethod The method used to calculate the digest value. */ public void setDigestMethod(String digestMethod) { this.digestMethod = digestMethod; } + @Override public String getDigestMethod() { return digestMethod; } /** * Sets the digest value. - * + * * @param digestValue The digest value. */ public void setDigestValue(byte[] digestValue) { this.digestValue = digestValue; } - + + @Override public byte[] getDigestValue() { return digestValue; } /** * Gets the type of TransformParameter. - * + * * @return HASH_TRANSFORMPARAMETER */ + @Override public int getTransformParameterType() { return HASH_TRANSFORMPARAMETER; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TslInfosImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TslInfosImpl.java index fad42e6..26905c2 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TslInfosImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/TslInfosImpl.java @@ -8,55 +8,55 @@ import at.gv.egovernment.moa.spss.api.common.TslInfos; public class TslInfosImpl implements TslInfos { - private String tslServiceTypeIdentifier; - private String tslServiceTypeStatus; - private List tslServiceQualifier = new ArrayList(); - private List tslAdditionalServiceInformation = new ArrayList(); - private String tslCountry; - - public TslInfosImpl(String country, String tslServiceTypeStatus, String tslServiceTypeIdentifier, - List tslCertificateQualifier, List additionalServiceInformation) { - this.tslCountry = country; - this.tslServiceTypeStatus = tslServiceTypeStatus; - this.tslServiceTypeIdentifier = tslServiceTypeIdentifier; - - if (tslCertificateQualifier != null) { - for (URI el : tslCertificateQualifier) - this.tslServiceQualifier.add(el.toString()); - - } - - if (additionalServiceInformation != null) - this.tslAdditionalServiceInformation.addAll(additionalServiceInformation); - - } - - - @Override - public String getTslIssuerCountry() { - return tslCountry; - } - - @Override - public String getServiceTypeStatus() { - return tslServiceTypeStatus; - } - - @Override - public String getServiceTypeIdentifier() { - return tslServiceTypeIdentifier; - } - - @Override - public List getQualifiers() { - return tslServiceQualifier; - } - - - @Override - public List getAdditionalServiceInformation() { - return this.tslAdditionalServiceInformation; - - } + private final String tslServiceTypeIdentifier; + private final String tslServiceTypeStatus; + private final List tslServiceQualifier = new ArrayList<>(); + private final List tslAdditionalServiceInformation = new ArrayList<>(); + private final String tslCountry; + + public TslInfosImpl(String country, String tslServiceTypeStatus, String tslServiceTypeIdentifier, + List tslCertificateQualifier, List additionalServiceInformation) { + this.tslCountry = country; + this.tslServiceTypeStatus = tslServiceTypeStatus; + this.tslServiceTypeIdentifier = tslServiceTypeIdentifier; + + if (tslCertificateQualifier != null) { + for (final URI el : tslCertificateQualifier) { + this.tslServiceQualifier.add(el.toString()); + } + + } + + if (additionalServiceInformation != null) { + this.tslAdditionalServiceInformation.addAll(additionalServiceInformation); + } + + } + + @Override + public String getTslIssuerCountry() { + return tslCountry; + } + + @Override + public String getServiceTypeStatus() { + return tslServiceTypeStatus; + } + + @Override + public String getServiceTypeIdentifier() { + return tslServiceTypeIdentifier; + } + + @Override + public List getQualifiers() { + return tslServiceQualifier; + } + + @Override + public List getAdditionalServiceInformation() { + return this.tslAdditionalServiceInformation; + + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyCMSSignatureRequestImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyCMSSignatureRequestImpl.java index e16717d..f041835 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyCMSSignatureRequestImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyCMSSignatureRequestImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.io.InputStream; @@ -32,12 +31,12 @@ import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureRequest; /** * Default implementation of VerifyCMSSignatureRequest. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class VerifyCMSSignatureRequestImpl - implements VerifyCMSSignatureRequest { + implements VerifyCMSSignatureRequest { /** The indexes of the signatories whose signature should be verified. */ private int[] signatories; @@ -49,39 +48,42 @@ public class VerifyCMSSignatureRequestImpl private InputStream cmsSignature; /** The date for which to verify the signature. */ private Date dateTime; - + private boolean pdf = false; private boolean extended = false; /** * Sets the indexes of the signatories whose signature should be verified. - * - * @param signatories The indexes of the signatories whose signature should be - * verified. + * + * @param signatories The indexes of the signatories whose signature should be + * verified. */ public void setSignatories(int[] signatories) { this.signatories = signatories; } + @Override public int[] getSignatories() { return signatories; } /** * Sets the date for which to verify the signature. - * + * * @param dateTime The date for which to verify the signature. */ public void setDateTime(Date dateTime) { this.dateTime = dateTime; } + @Override public Date getDateTime() { return dateTime; } /** * Sets the CMS signature to verify. + * * @param signature The CMS signature to verify. */ public void setCMSSignature(InputStream signature) { @@ -89,48 +91,55 @@ public class VerifyCMSSignatureRequestImpl } + @Override public InputStream getCMSSignature() { return cmsSignature; } /** * Sets the data object necessary for signature verification. + * * @param dataObject The data object necessary for signature verification. */ public void setDataObject(CMSDataObject dataObject) { this.dataObject = dataObject; } + @Override public CMSDataObject getDataObject() { return dataObject; } /** * Sets the profile ID of trusted certificates. + * * @param trustProfileId The profile ID of trusted certificates. */ public void setTrustProfileId(String trustProfileId) { this.trustProfileId = trustProfileId; } + @Override public String getTrustProfileId() { return trustProfileId; } public void setPDF(boolean value) { - this.pdf = value; + this.pdf = value; } - + + @Override public boolean isPDF() { - return this.pdf; + return this.pdf; } -public synchronized boolean isExtended() { - return extended; -} + @Override + public synchronized boolean isExtended() { + return extended; + } -public synchronized void setExtended(boolean extended) { - this.extended = extended; -} + public synchronized void setExtended(boolean extended) { + this.extended = extended; + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyCMSSignatureResponseElementImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyCMSSignatureResponseElementImpl.java index 3ea504b..f9e8e4d 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyCMSSignatureResponseElementImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyCMSSignatureResponseElementImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.util.List; @@ -33,12 +32,12 @@ import at.gv.egovernment.moa.spss.api.common.SignerInfo; /** * Default implementation of VerifyCMSSignatureResponseElement. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class VerifyCMSSignatureResponseElementImpl - implements VerifyCMSSignatureResponseElement { + implements VerifyCMSSignatureResponseElement { /** Information about the signer certificate. */ private SignerInfo signerInfo; @@ -46,101 +45,102 @@ public class VerifyCMSSignatureResponseElementImpl private CheckResult signatureCheck; /** Information about the certificate check. */ private CheckResult certificateCheck; - + private ExtendedCertificateCheckResult extendedResult; - + private List adesResults = null; - + private String usedAlgorithm = null; - + private Boolean coversFullDocument = null; - + private int[] byteRangeOfSignature = null; - + /** * Sets a SignerInfo element according to CMS. - * + * * @param signerInfo The SignerInfo element according to CMS. */ public void setSignerInfo(SignerInfo signerInfo) { this.signerInfo = signerInfo; } + @Override public SignerInfo getSignerInfo() { return signerInfo; } /** * Sets a result of the signature verification. - * + * * @param signatureCheck The result of the signature verification. */ public void setSignatureCheck(CheckResult signatureCheck) { this.signatureCheck = signatureCheck; } + @Override public CheckResult getSignatureCheck() { return signatureCheck; } /** * Sets a result of the certificate verification. - * + * * @param certificateCheck The result of the certificate verification. */ public void setCertificateCheck(CheckResult certificateCheck) { this.certificateCheck = certificateCheck; } + @Override public CheckResult getCertificateCheck() { return certificateCheck; } public void setAdESFormResults(List adesResults) { - this.adesResults = adesResults; + this.adesResults = adesResults; } - + + @Override public List getAdESFormResults() { - return adesResults; + return adesResults; } public void setExtendedCertificateCheck(ExtendedCertificateCheckResult r) { - this.extendedResult = r; - } - - @Override - public ExtendedCertificateCheckResult getExtendedCertificateCheck() { - return extendedResult; - } - - @Override - public String getSignatureAlgorithm() { - return usedAlgorithm; - } - - public void setSignatureAlgorithm(String usedAlgorithm) { - this.usedAlgorithm = usedAlgorithm; - } - - @Override - public Boolean getCoversFullDocument() { - return coversFullDocument; - } - - public void setCoversFullDocument(Boolean coversFullDocument) { - this.coversFullDocument = coversFullDocument; - } - - @Override - public int[] getByteRangeOfSignature() { - return byteRangeOfSignature; - } - - public void setByteRangeOfSignature(int[] byteRangeOfSignature) { - this.byteRangeOfSignature = byteRangeOfSignature; - } - - - - + this.extendedResult = r; + } + + @Override + public ExtendedCertificateCheckResult getExtendedCertificateCheck() { + return extendedResult; + } + + @Override + public String getSignatureAlgorithm() { + return usedAlgorithm; + } + + public void setSignatureAlgorithm(String usedAlgorithm) { + this.usedAlgorithm = usedAlgorithm; + } + + @Override + public Boolean getCoversFullDocument() { + return coversFullDocument; + } + + public void setCoversFullDocument(Boolean coversFullDocument) { + this.coversFullDocument = coversFullDocument; + } + + @Override + public int[] getByteRangeOfSignature() { + return byteRangeOfSignature; + } + + public void setByteRangeOfSignature(int[] byteRangeOfSignature) { + this.byteRangeOfSignature = byteRangeOfSignature; + } + } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyCMSSinatureResponseImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyCMSSinatureResponseImpl.java index 44fb474..c7fd29f 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyCMSSinatureResponseImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyCMSSinatureResponseImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.util.ArrayList; @@ -32,28 +31,29 @@ import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureResponse; /** * Default implementation of VerifyCMSSignatureResponse. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class VerifyCMSSinatureResponseImpl - implements VerifyCMSSignatureResponse { + implements VerifyCMSSignatureResponse { /** The elements contained in the response. */ private List responseElements; /** * Sets the elements contained in the response. - * + * * @param responseElements The elements contained in the response. */ public void setResponseElements(List responseElements) { this.responseElements = - responseElements != null - ? Collections.unmodifiableList(new ArrayList(responseElements)) - : null; + responseElements != null + ? Collections.unmodifiableList(new ArrayList(responseElements)) + : null; } + @Override public List getResponseElements() { return responseElements; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifySignatureInfoImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifySignatureInfoImpl.java index d022ae4..f8ab10d 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifySignatureInfoImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifySignatureInfoImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.common.Content; @@ -30,7 +29,7 @@ import at.gv.egovernment.moa.spss.api.xmlverify.VerifySignatureLocation; /** * Default implementation of VerifySignatureInfo. - * + * * @author Fatemeh Philippi * @version $Id$ */ @@ -42,28 +41,29 @@ public class VerifySignatureInfoImpl implements VerifySignatureInfo { /** * Sets the location of the signature to be verified. - * - * @param verifySignatureLocation The location of the signature to be - * verified. + * + * @param verifySignatureLocation The location of the signature to be verified. */ public void setVerifySignatureLocation(VerifySignatureLocation verifySignatureLocation) { this.verifySignatureLocation = verifySignatureLocation; } + @Override public VerifySignatureLocation getVerifySignatureLocation() { return verifySignatureLocation; } /** * Sets the signature environment containing the signature to be verified. - * - * @param verifySignatureEnvironment The signature environment containing the - * signature to be verified. + * + * @param verifySignatureEnvironment The signature environment containing the + * signature to be verified. */ public void setVerifySignatureEnvironment(Content verifySignatureEnvironment) { this.verifySignatureEnvironment = verifySignatureEnvironment; } + @Override public Content getVerifySignatureEnvironment() { return verifySignatureEnvironment; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifySignatureLocationImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifySignatureLocationImpl.java index 8e183bb..7f3b381 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifySignatureLocationImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifySignatureLocationImpl.java @@ -21,19 +21,18 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.xmlverify.VerifySignatureLocation; /** * Default implementation of VerifySignatureLocation. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class VerifySignatureLocationImpl - extends ElementSelectorImpl - implements VerifySignatureLocation { + extends ElementSelectorImpl + implements VerifySignatureLocation { } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyTransformsDataImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyTransformsDataImpl.java index 25b5c39..d1eebca 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyTransformsDataImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyTransformsDataImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.util.ArrayList; @@ -32,7 +31,7 @@ import at.gv.egovernment.moa.spss.api.xmlverify.ReferenceInfo; /** * Default implementation of . - * + * * @author Fatemeh Philippi * @version $Id$ */ @@ -42,18 +41,19 @@ public class VerifyTransformsDataImpl implements ReferenceInfo { /** * Sets the information about the transformations contained in the signature. - * + * * @param verifyTransformsInfoProfiles The profiles containing transformation - * information. + * information. */ public void setVerifyTransformsInfoProfiles(List verifyTransformsInfoProfiles) { this.verifyTransformsInfoProfiles = - verifyTransformsInfoProfiles != null - ? Collections.unmodifiableList( - new ArrayList(verifyTransformsInfoProfiles)) - : null; + verifyTransformsInfoProfiles != null + ? Collections.unmodifiableList( + new ArrayList(verifyTransformsInfoProfiles)) + : null; } + @Override public List getVerifyTransformsInfoProfiles() { return verifyTransformsInfoProfiles; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyTransformsInfoProfileExplicitImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyTransformsInfoProfileExplicitImpl.java index 2ce5f39..0e1e46e 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyTransformsInfoProfileExplicitImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyTransformsInfoProfileExplicitImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.util.ArrayList; @@ -32,12 +31,12 @@ import at.gv.egovernment.moa.spss.api.xmlverify.VerifyTransformsInfoProfileExpli /** * Default implementation of VerifyTransformsInfoProfileExplicit. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class VerifyTransformsInfoProfileExplicitImpl - implements VerifyTransformsInfoProfileExplicit { + implements VerifyTransformsInfoProfileExplicit { /** The transforms contained in this profile. */ private List transforms; @@ -46,38 +45,41 @@ public class VerifyTransformsInfoProfileExplicitImpl /** * Sets the transforms contained in this profile. - * + * * @param transforms The transforms contained in this profile. */ public void setTransforms(List transforms) { this.transforms = - transforms != null - ? Collections.unmodifiableList(new ArrayList(transforms)) - : null; + transforms != null + ? Collections.unmodifiableList(new ArrayList(transforms)) + : null; } + @Override public List getTransforms() { return transforms; } /** * Sets additional information for the transforms. - * + * * @param transformParameters Additional information for the transforms. */ public void setTransformParameters(List transformParameters) { this.transformParameters = new ArrayList(transformParameters); } + @Override public List getTransformParameters() { return transformParameters; } /** * Gets the type of VerifyTransformsInfoProfile. - * + * * @return EXPLICIT_VERIFYTRANSFORMSINFOPROFILE */ + @Override public int getVerifyTransformsInfoProfileType() { return EXPLICIT_VERIFYTRANSFORMSINFOPROFILE; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyTransformsInfoProfileIDImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyTransformsInfoProfileIDImpl.java index a545535..56fc9e2 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyTransformsInfoProfileIDImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyTransformsInfoProfileIDImpl.java @@ -21,14 +21,13 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.xmlverify.VerifyTransformsInfoProfileID; /** * Default implementation of VerifyTransformsInfoProfileID. - * + * * @author Fatemeh Philippi * @version $Id$ */ @@ -39,22 +38,24 @@ public class VerifyTransformsInfoProfileIDImpl implements VerifyTransformsInfoPr /** * Sets the profile ID. - * + * * @param profileID The profile ID. */ public void setVerifyTransformsInfoProfileID(String profileID) { this.verifyTransformsInfoProfileID = profileID; } + @Override public String getVerifyTransformsInfoProfileID() { return verifyTransformsInfoProfileID; } /** * Gets the type of VerifyTransformsInfoProfile. - * + * * @return ID_VERIFYTRANSFORMSINFOPROFILE */ + @Override public int getVerifyTransformsInfoProfileType() { return ID_VERIFYTRANSFORMSINFOPROFILE; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyXMLSignatureRequestImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyXMLSignatureRequestImpl.java index 91d1917..b5094b4 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyXMLSignatureRequestImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyXMLSignatureRequestImpl.java @@ -34,118 +34,120 @@ import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureRequest; /** * Default implementation of VerifyXMLSignatureRequest. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class VerifyXMLSignatureRequestImpl implements VerifyXMLSignatureRequest { - /** Date and time for signature verification. */ - private Date dateTime; - /** The signature to be verified. */ - private VerifySignatureInfo verifySignatureInfo; - /** Supplemental information about the singature. */ - private List supplementProfiles; - /** Additional parameters for checking the signature manifest. */ - private SignatureManifestCheckParams signatureManifestCheckParams; - /** Whether to return the hash input data. */ - private boolean returnHashInputData; - private boolean extendedValidation; - /** - * The profile ID of the trust profile containing the trusted certificates. - */ - private String trustProfileId; - - /** - * Sets the date and time for signature verification. - * - * @param dateTime - * The date and time for signature verification. - */ - public void setDateTime(Date dateTime) { - this.dateTime = dateTime; - } - - public Date getDateTime() { - return dateTime; - } - - /** - * Sets the signature to be verified. - * - * @param signatureInfo - * The signature to be verified. - */ - public void setSignatureInfo(VerifySignatureInfo signatureInfo) { - this.verifySignatureInfo = signatureInfo; - } - - public VerifySignatureInfo getSignatureInfo() { - return verifySignatureInfo; - } - - /** - * Sets supplemental information about the singature. - * - * @param supplementProfiles - */ - public void setSupplementProfiles(List supplementProfiles) { - this.supplementProfiles = supplementProfiles != null - ? Collections.unmodifiableList(new ArrayList(supplementProfiles)) : null; - } - - public List getSupplementProfiles() { - return supplementProfiles; - } - - /** - * Sets supplemental information about the singature. - * - * @param params - * Supplemental information about the singature. - */ - public void setSignatureManifestCheckParams(SignatureManifestCheckParams params) { - this.signatureManifestCheckParams = params; - } - - public SignatureManifestCheckParams getSignatureManifestCheckParams() { - return signatureManifestCheckParams; - } - - /** - * Sets whether to return hash input data. - * - * @param returnSignedData - * Whether to return hash input data. - */ - public void setReturnHashInputData(boolean returnSignedData) { - this.returnHashInputData = returnSignedData; - } - - public boolean getReturnHashInputData() { - return returnHashInputData; - } - - /** - * Sets the profile ID of trusted certificates. - * - * @param trustProfileId - * The profile ID of trusted certificates. - */ - public void setTrustProfileId(String trustProfileId) { - this.trustProfileId = trustProfileId; - } - - public String getTrustProfileId() { - return trustProfileId; - } - - public synchronized void setExtendedValidation(boolean extendedValidation) { - this.extendedValidation = extendedValidation; - } - - @Override - public boolean getExtendedValidaiton() { - return extendedValidation; - } + /** Date and time for signature verification. */ + private Date dateTime; + /** The signature to be verified. */ + private VerifySignatureInfo verifySignatureInfo; + /** Supplemental information about the singature. */ + private List supplementProfiles; + /** Additional parameters for checking the signature manifest. */ + private SignatureManifestCheckParams signatureManifestCheckParams; + /** Whether to return the hash input data. */ + private boolean returnHashInputData; + private boolean extendedValidation; + /** + * The profile ID of the trust profile containing the trusted certificates. + */ + private String trustProfileId; + + /** + * Sets the date and time for signature verification. + * + * @param dateTime The date and time for signature verification. + */ + public void setDateTime(Date dateTime) { + this.dateTime = dateTime; + } + + @Override + public Date getDateTime() { + return dateTime; + } + + /** + * Sets the signature to be verified. + * + * @param signatureInfo The signature to be verified. + */ + public void setSignatureInfo(VerifySignatureInfo signatureInfo) { + this.verifySignatureInfo = signatureInfo; + } + + @Override + public VerifySignatureInfo getSignatureInfo() { + return verifySignatureInfo; + } + + /** + * Sets supplemental information about the singature. + * + * @param supplementProfiles + */ + public void setSupplementProfiles(List supplementProfiles) { + this.supplementProfiles = supplementProfiles != null + ? Collections.unmodifiableList(new ArrayList(supplementProfiles)) + : null; + } + + @Override + public List getSupplementProfiles() { + return supplementProfiles; + } + + /** + * Sets supplemental information about the singature. + * + * @param params Supplemental information about the singature. + */ + public void setSignatureManifestCheckParams(SignatureManifestCheckParams params) { + this.signatureManifestCheckParams = params; + } + + @Override + public SignatureManifestCheckParams getSignatureManifestCheckParams() { + return signatureManifestCheckParams; + } + + /** + * Sets whether to return hash input data. + * + * @param returnSignedData Whether to return hash input data. + */ + public void setReturnHashInputData(boolean returnSignedData) { + this.returnHashInputData = returnSignedData; + } + + @Override + public boolean getReturnHashInputData() { + return returnHashInputData; + } + + /** + * Sets the profile ID of trusted certificates. + * + * @param trustProfileId The profile ID of trusted certificates. + */ + public void setTrustProfileId(String trustProfileId) { + this.trustProfileId = trustProfileId; + } + + @Override + public String getTrustProfileId() { + return trustProfileId; + } + + public synchronized void setExtendedValidation(boolean extendedValidation) { + this.extendedValidation = extendedValidation; + } + + @Override + public boolean getExtendedValidaiton() { + return extendedValidation; + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyXMLSignatureResponseImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyXMLSignatureResponseImpl.java index 0047d44..85af8d4 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyXMLSignatureResponseImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/VerifyXMLSignatureResponseImpl.java @@ -39,165 +39,168 @@ import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureResponse; */ public class VerifyXMLSignatureResponseImpl implements VerifyXMLSignatureResponse { - /** Information about the signer certificate. */ - private SignerInfo signerInfo; - - private ExtendedCertificateCheckResult extendedResult; - - /** - * The hash input data objects. The list consists of - * {@link at.gv.egovernment.moa.spss.api.common.InputData}s. - */ - private List hashInputDatas = new ArrayList(); - - /** - * The reference input data objects. The list consists of - * {@link at.gv.egovernment.moa.spss.api.common.InputData}s. - */ - private List referenceInputDatas = new ArrayList(); - - /** - * The list of form validation results - */ - private List adesFormResults = new ArrayList(); - - /** Information about the signature check. */ - private ReferencesCheckResult signatureCheck; - /** Information about the signature manifest check. */ - private ReferencesCheckResult signatureManifestCheck; - /** Information about the XMLDsig manifest check. */ - private List xmlDsigManifestChecks = new ArrayList(); - /** Information about the certificate check. */ - private CheckResult certificateCheck; - - private String signatureAlgorithm = null; - - /** - * Sets information about the signer certificate. - * - * @param signerInfo - * Information about the signer certificate. - */ - public void setSignerInfo(SignerInfo signerInfo) { - this.signerInfo = signerInfo; - } - - public SignerInfo getSignerInfo() { - return signerInfo; - } - - /** - * Sets data signed by the signatory. - * - * @param hashInputDatas - * The signed datas. - */ - public void setHashInputDatas(List hashInputDatas) { - this.hashInputDatas = hashInputDatas != null ? Collections.unmodifiableList(new ArrayList(hashInputDatas)) - : null; - } - - public List getHashInputDatas() { - return hashInputDatas; - } - - /** - * Sets the source data elements. - * - * @param referenceInputDatas - * The source data elements. - */ - public void setReferenceInputDatas(List referenceInputDatas) { - this.referenceInputDatas = referenceInputDatas != null - ? Collections.unmodifiableList(new ArrayList(referenceInputDatas)) : null; - } - - public List getReferenceInputDatas() { - return referenceInputDatas; - } - - /** - * Sets the result of the signature verification. - * - * @param signatureCheck - * The result of the signature verification. - */ - public void setSignatureCheck(ReferencesCheckResult signatureCheck) { - this.signatureCheck = signatureCheck; - } - - public ReferencesCheckResult getSignatureCheck() { - return signatureCheck; - } - - /** - * Sets the result of the signature manifest verification. - * - * @param signatureManifestCheck - * The result of the signature manifest verification. - */ - public void setSignatureManifestCheck(ReferencesCheckResult signatureManifestCheck) { - this.signatureManifestCheck = signatureManifestCheck; - } - - public ReferencesCheckResult getSignatureManifestCheck() { - return signatureManifestCheck; - } - - /** - * Sets the result of the certification verification. - * - * @param certificateCheck - * The result of the certificate verification. - */ - public void setCertificateCheck(CheckResult certificateCheck) { - this.certificateCheck = certificateCheck; - } - - public CheckResult getCertificateCheck() { - return certificateCheck; - } - - /** - * Sets the XMLDSigManifestChecks. - * - * @param xmlDsigManifestChecks - * The XMLDSigManifestChecks. - */ - public void setXMLDsigManifestChecks(List xmlDsigManifestChecks) { - this.xmlDsigManifestChecks = xmlDsigManifestChecks != null - ? Collections.unmodifiableList(new ArrayList(xmlDsigManifestChecks)) : null; - } - - public List getXMLDsigManifestChecks() { - return xmlDsigManifestChecks; - } - - public void setAdESFormResults(List adesFormResults) { - this.adesFormResults = adesFormResults; - } - - @Override - public List getAdESFormResults() { - return this.adesFormResults; - } - - public void setExtendedCertificateCheck(ExtendedCertificateCheckResult r) { - this.extendedResult = r; - } - - @Override - public ExtendedCertificateCheckResult getExtendedCertificateCheck() { - return extendedResult; - } - - public String getSignatureAlgorithm() { - return signatureAlgorithm; - } - - public void setSignatureAlgorithm(String signatureAlgorithm) { - this.signatureAlgorithm = signatureAlgorithm; - } - - + /** Information about the signer certificate. */ + private SignerInfo signerInfo; + + private ExtendedCertificateCheckResult extendedResult; + + /** + * The hash input data objects. The list consists of + * {@link at.gv.egovernment.moa.spss.api.common.InputData}s. + */ + private List hashInputDatas = new ArrayList(); + + /** + * The reference input data objects. The list consists of + * {@link at.gv.egovernment.moa.spss.api.common.InputData}s. + */ + private List referenceInputDatas = new ArrayList(); + + /** + * The list of form validation results + */ + private List adesFormResults = new ArrayList(); + + /** Information about the signature check. */ + private ReferencesCheckResult signatureCheck; + /** Information about the signature manifest check. */ + private ReferencesCheckResult signatureManifestCheck; + /** Information about the XMLDsig manifest check. */ + private List xmlDsigManifestChecks = new ArrayList(); + /** Information about the certificate check. */ + private CheckResult certificateCheck; + + private String signatureAlgorithm = null; + + /** + * Sets information about the signer certificate. + * + * @param signerInfo Information about the signer certificate. + */ + public void setSignerInfo(SignerInfo signerInfo) { + this.signerInfo = signerInfo; + } + + @Override + public SignerInfo getSignerInfo() { + return signerInfo; + } + + /** + * Sets data signed by the signatory. + * + * @param hashInputDatas The signed datas. + */ + public void setHashInputDatas(List hashInputDatas) { + this.hashInputDatas = hashInputDatas != null ? Collections.unmodifiableList(new ArrayList(hashInputDatas)) + : null; + } + + @Override + public List getHashInputDatas() { + return hashInputDatas; + } + + /** + * Sets the source data elements. + * + * @param referenceInputDatas The source data elements. + */ + public void setReferenceInputDatas(List referenceInputDatas) { + this.referenceInputDatas = referenceInputDatas != null + ? Collections.unmodifiableList(new ArrayList(referenceInputDatas)) + : null; + } + + @Override + public List getReferenceInputDatas() { + return referenceInputDatas; + } + + /** + * Sets the result of the signature verification. + * + * @param signatureCheck The result of the signature verification. + */ + public void setSignatureCheck(ReferencesCheckResult signatureCheck) { + this.signatureCheck = signatureCheck; + } + + @Override + public ReferencesCheckResult getSignatureCheck() { + return signatureCheck; + } + + /** + * Sets the result of the signature manifest verification. + * + * @param signatureManifestCheck The result of the signature manifest + * verification. + */ + public void setSignatureManifestCheck(ReferencesCheckResult signatureManifestCheck) { + this.signatureManifestCheck = signatureManifestCheck; + } + + @Override + public ReferencesCheckResult getSignatureManifestCheck() { + return signatureManifestCheck; + } + + /** + * Sets the result of the certification verification. + * + * @param certificateCheck The result of the certificate verification. + */ + public void setCertificateCheck(CheckResult certificateCheck) { + this.certificateCheck = certificateCheck; + } + + @Override + public CheckResult getCertificateCheck() { + return certificateCheck; + } + + /** + * Sets the XMLDSigManifestChecks. + * + * @param xmlDsigManifestChecks The XMLDSigManifestChecks. + */ + public void setXMLDsigManifestChecks(List xmlDsigManifestChecks) { + this.xmlDsigManifestChecks = xmlDsigManifestChecks != null + ? Collections.unmodifiableList(new ArrayList(xmlDsigManifestChecks)) + : null; + } + + @Override + public List getXMLDsigManifestChecks() { + return xmlDsigManifestChecks; + } + + public void setAdESFormResults(List adesFormResults) { + this.adesFormResults = adesFormResults; + } + + @Override + public List getAdESFormResults() { + return this.adesFormResults; + } + + public void setExtendedCertificateCheck(ExtendedCertificateCheckResult r) { + this.extendedResult = r; + } + + @Override + public ExtendedCertificateCheckResult getExtendedCertificateCheck() { + return extendedResult; + } + + @Override + public String getSignatureAlgorithm() { + return signatureAlgorithm; + } + + public void setSignatureAlgorithm(String signatureAlgorithm) { + this.signatureAlgorithm = signatureAlgorithm; + } + } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/X509IssuerSerialImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/X509IssuerSerialImpl.java index aff7e10..ac2886c 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/X509IssuerSerialImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/X509IssuerSerialImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.math.BigInteger; @@ -30,7 +29,7 @@ import at.gv.egovernment.moa.spss.api.common.X509IssuerSerial; /** * Default implementation of X509IssuerSerial. - * + * * @author Fatemeh Philippi * @version $Id$ */ @@ -42,26 +41,28 @@ public class X509IssuerSerialImpl implements X509IssuerSerial { /** * Sets the issuer distinguished name. - * + * * @param x509IssuerName The issuer distinguished name. */ public void setX509IssuerName(String x509IssuerName) { this.x509IssuerName = x509IssuerName; } + @Override public String getX509IssuerName() { return x509IssuerName; } /** * Sets the certificate serial number. - * + * * @param x509SerialNumber The issuer serial number. */ public void setX509SerialNumber(BigInteger x509SerialNumber) { this.x509SerialNumber = x509SerialNumber; } + @Override public BigInteger getX509SerialNumber() { return x509SerialNumber; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/XMLDataObjectAssociationImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/XMLDataObjectAssociationImpl.java index dabf29d..7769e5a 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/XMLDataObjectAssociationImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/XMLDataObjectAssociationImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import at.gv.egovernment.moa.spss.api.common.Content; @@ -30,7 +29,7 @@ import at.gv.egovernment.moa.spss.api.common.XMLDataObjectAssociation; /** * Default implementation of XMLDataObjectAssociation. - * + * * @author Fatemeh Philippi * @version $Id$ */ @@ -43,25 +42,28 @@ public class XMLDataObjectAssociationImpl implements XMLDataObjectAssociation { /** * Sets meta information about the Content object. + * * @param metaInfo Meta information about the Content object. */ public void setMetaInfo(MetaInfo metaInfo) { this.metaInfo = metaInfo; } + @Override public MetaInfo getMetaInfo() { return metaInfo; } /** * Sets the actual data contained in this object. - * + * * @param content The actual data contained in this object. */ public void setContent(Content content) { this.content = content; } + @Override public Content getContent() { return content; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/XPathFilter2TransformImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/XPathFilter2TransformImpl.java index 175de3a..9eb4df1 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/XPathFilter2TransformImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/XPathFilter2TransformImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.util.ArrayList; @@ -31,17 +30,17 @@ import at.gv.egovernment.moa.spss.api.common.XPathFilter2Transform; /** * Default implementation of XPathFilter2Transform. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class XPathFilter2TransformImpl - extends TransformImpl - implements XPathFilter2Transform { - + extends TransformImpl + implements XPathFilter2Transform { + /** The XPath filters. */ private List filters; - + /** * Create a new XPathFilter2TransformImpl object. */ @@ -50,16 +49,16 @@ public class XPathFilter2TransformImpl } /** - * Sets the XPath filters contained in this - * XPathFilter2Transform. - * - * @param filters The XPath filters contained in this - * XPathFilter2Transform. - */ + * Sets the XPath filters contained in this XPathFilter2Transform. + * + * @param filters The XPath filters contained in this + * XPathFilter2Transform. + */ public void setFilters(List filters) { this.filters = new ArrayList(filters); } + @Override public List getFilters() { return filters; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/XPathFilterImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/XPathFilterImpl.java index 6615e9f..800270f 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/XPathFilterImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/XPathFilterImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.util.HashMap; @@ -31,7 +30,7 @@ import at.gv.egovernment.moa.spss.api.common.XPathFilter; /** * Default implementation of XPathFilter. - * + * * @author Fatemeh Philippi * @version $Id$ */ @@ -40,47 +39,51 @@ public class XPathFilterImpl implements XPathFilter { private String filterType; /** The XPath expression of the filter. */ private String xPathExpression; - /** The namespace prefix to URI mapping to while evaluating the XPath - * expression. */ + /** + * The namespace prefix to URI mapping to while evaluating the XPath expression. + */ private Map namespaceDeclarations = new HashMap(); /** * Sets the type of filter. - * + * * @param filterType The type of filter. */ public void setFilterType(String filterType) { this.filterType = filterType; } + @Override public String getFilterType() { return filterType; } /** * Sets the XPath expression of the filter. - * + * * @param xPathExpression The XPath expression of the filter. */ public void setXPathExpression(String xPathExpression) { this.xPathExpression = xPathExpression; } + @Override public String getXPathExpression() { return xPathExpression; } /** - * Sets the namespace prefix to URI mapping to while evaluating the XPath + * Sets the namespace prefix to URI mapping to while evaluating the XPath * expression. - * - * @param namespaceDeclarations The namespace prefix to URI mapping to while - * evaluating the XPath expression. + * + * @param namespaceDeclarations The namespace prefix to URI mapping to while + * evaluating the XPath expression. */ public void setNamespaceDelcarations(Map namespaceDeclarations) { this.namespaceDeclarations = namespaceDeclarations; } + @Override public Map getNamespaceDeclarations() { return namespaceDeclarations; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/XPathTransformImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/XPathTransformImpl.java index f626a95..92f7170 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/XPathTransformImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/XPathTransformImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import java.util.HashMap; @@ -31,18 +30,19 @@ import at.gv.egovernment.moa.spss.api.common.XPathTransform; /** * Default implementation of XPathTransform. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class XPathTransformImpl - extends TransformImpl - implements XPathTransform { - + extends TransformImpl + implements XPathTransform { + /** The XPath expression to evaluate. */ private String xPathExpression; - /** The namespace prefix to URI mapping to while evaluating the XPath - * expression. */ + /** + * The namespace prefix to URI mapping to while evaluating the XPath expression. + */ private Map namespaceDeclarations = new HashMap(); /** @@ -54,28 +54,30 @@ public class XPathTransformImpl /** * Sets the XPath expression to evaluate. - * + * * @param xPathExpression The XPath expression to evaluate. */ public void setXPathExpression(String xPathExpression) { this.xPathExpression = xPathExpression; } + @Override public String getXPathExpression() { return xPathExpression; } /** - * Sets the namespace prefix to URI mapping to while evaluating the XPath + * Sets the namespace prefix to URI mapping to while evaluating the XPath * expression. - * - * @param namespaceDeclarations The namespace prefix to URI mapping to while - * evaluating the XPath expression. + * + * @param namespaceDeclarations The namespace prefix to URI mapping to while + * evaluating the XPath expression. */ public void setNamespaceDelcarations(Map namespaceDeclarations) { this.namespaceDeclarations = namespaceDeclarations; } + @Override public Map getNamespaceDeclarations() { return namespaceDeclarations; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/XSLTransformImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/XSLTransformImpl.java index 3fd4cc1..5995c73 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/XSLTransformImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/impl/XSLTransformImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.impl; import org.w3c.dom.Element; @@ -30,14 +29,14 @@ import at.gv.egovernment.moa.spss.api.common.XSLTTransform; /** * Default implementation of XSLTTransform. - * + * * @author Fatemeh Philippi * @version $Id$ */ public class XSLTransformImpl extends TransformImpl implements XSLTTransform { /** The XSLT stylesheet to apply. */ private Element styleSheet; - + /** * Create a new XSLTransformImpl object. */ @@ -47,13 +46,14 @@ public class XSLTransformImpl extends TransformImpl implements XSLTTransform { /** * Sets the XSLT stylesheet to apply. - * + * * @param styleSheet The XSLT stylesheet to apply. */ public void setStylesheet(Element styleSheet) { this.styleSheet = styleSheet; } + @Override public Element getStylesheet() { return styleSheet; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/CreateCMSSignatureRequestParser.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/CreateCMSSignatureRequestParser.java index a4c4d29..579fb51 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/CreateCMSSignatureRequestParser.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/CreateCMSSignatureRequestParser.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlbind; import java.io.InputStream; @@ -49,7 +48,7 @@ import at.gv.egovernment.moaspss.util.XPathUtils; /** * A parser to parse CreateCMSSignatureRequest DOM trees into * CreateCMSSignatureRequest API objects. - * + * * @author Patrick Peck * @version $Id$ */ @@ -60,12 +59,12 @@ public class CreateCMSSignatureRequestParser { // private static final String MOA = Constants.MOA_PREFIX + ":"; private static final String KEY_IDENTIFIER_XPATH = - "/" + MOA + "CreateCMSSignatureRequest/" + MOA + "KeyIdentifier"; + "/" + MOA + "CreateCMSSignatureRequest/" + MOA + "KeyIdentifier"; private static final String SINGLE_SIGNATURE_INFO_XPATH = - "/" + MOA + "CreateCMSSignatureRequest/" + MOA + "SingleSignatureInfo"; + "/" + MOA + "CreateCMSSignatureRequest/" + MOA + "SingleSignatureInfo"; private static final String DATA_OBJECT_INFO_XPATH = MOA + "DataObjectInfo"; private static final String DATA_OBJECT_XPATH = MOA + "DataObject"; - + private static final String SL_CONFORM_ATTR_NAME = "SecurityLayerConformity"; private static final String IS_PADES_SIGNATURE_ATTR_NAME = "PAdESConformity"; @@ -74,11 +73,9 @@ public class CreateCMSSignatureRequestParser { private static final String BASE64_CONTENT_XPATH = MOA + "Base64Content"; private static final String EXCLUDEBYTERANGE_FROM_XPATH = MOA + "ExcludedByteRange/" + MOA + "From"; private static final String EXCLUDEBYTERANGE_TO_XPATH = MOA + "ExcludedByteRange/" + MOA + "To"; - - /** The factory to create API objects. */ - private SPSSFactory factory; + private final SPSSFactory factory; /** * Create a new CreateCMSSignatureRequestParser. @@ -88,44 +85,43 @@ public class CreateCMSSignatureRequestParser { } /** - * Parse a CreateCMSSignatureRequest DOM element, as defined - * by the MOA schema. - * + * Parse a CreateCMSSignatureRequest DOM element, as defined by the + * MOA schema. + * * @param requestElem The CreateCMSSignatureRequest to parse. The - * request must have been successfully parsed against the schema for this - * method to succeed. - * @return A CreateCMSSignatureRequest API object containing - * the data from the DOM element. + * request must have been successfully parsed against the + * schema for this method to succeed. + * @return A CreateCMSSignatureRequest API object containing the + * data from the DOM element. * @throws MOAApplicationException An error occurred parsing the request. */ public CreateCMSSignatureRequest parse(Element requestElem) - throws MOAApplicationException { + throws MOAApplicationException { - List singleSignatureInfos = parseSingleSignatureInfos(requestElem); - String keyIdentifier = - XPathUtils.getElementValue(requestElem, KEY_IDENTIFIER_XPATH, null); + final List singleSignatureInfos = parseSingleSignatureInfos(requestElem); + final String keyIdentifier = + XPathUtils.getElementValue(requestElem, KEY_IDENTIFIER_XPATH, null); return factory.createCreateCMSSignatureRequest( - keyIdentifier, - singleSignatureInfos); + keyIdentifier, + singleSignatureInfos); } /** - * Parse all SingleSignatureInfo elements of the + * Parse all SingleSignatureInfo elements of the * CreateCMSSignatureRequest. - * + * * @param requestElem The CreateCMSSignatureRequest to parse. - * @return A List of SingleSignatureInfo API - * objects. - * @throws MOAApplicationException An error occurred parsing on of the - * SingleSignatureInfo elements. + * @return A List of SingleSignatureInfo API objects. + * @throws MOAApplicationException An error occurred parsing on of the + * SingleSignatureInfo elements. */ private List parseSingleSignatureInfos(Element requestElem) - throws MOAApplicationException { + throws MOAApplicationException { - List singleSignatureInfos = new ArrayList(); - NodeIterator sigInfoElems = - XPathUtils.selectNodeIterator(requestElem, SINGLE_SIGNATURE_INFO_XPATH); + final List singleSignatureInfos = new ArrayList(); + final NodeIterator sigInfoElems = + XPathUtils.selectNodeIterator(requestElem, SINGLE_SIGNATURE_INFO_XPATH); Element sigInfoElem; while ((sigInfoElem = (Element) sigInfoElems.nextNode()) != null) { @@ -137,132 +133,130 @@ public class CreateCMSSignatureRequestParser { /** * Parse a SingleSignatureInfo DOM element. - * - * @param sigInfoElem The SingleSignatureInfo DOM element to - * parse. - * @return A SingleSignatureInfo API object containing the - * information of sigInfoElem. - * @throws MOAApplicationException An error occurred parsing the - * SingleSignatureInfo. + * + * @param sigInfoElem The SingleSignatureInfo DOM element to parse. + * @return A SingleSignatureInfo API object containing the + * information of sigInfoElem. + * @throws MOAApplicationException An error occurred parsing the + * SingleSignatureInfo. */ private SingleSignatureInfo parseSingleSignatureInfo(Element sigInfoElem) - throws MOAApplicationException { + throws MOAApplicationException { - DataObjectInfo dataObjectInfo = parseDataObjectInfo(sigInfoElem); + final DataObjectInfo dataObjectInfo = parseDataObjectInfo(sigInfoElem); boolean securityLayerConform; boolean isPAdESSignature = false; if (sigInfoElem.hasAttribute(SL_CONFORM_ATTR_NAME)) { securityLayerConform = - BoolUtils.valueOf(sigInfoElem.getAttribute(SL_CONFORM_ATTR_NAME)); + BoolUtils.valueOf(sigInfoElem.getAttribute(SL_CONFORM_ATTR_NAME)); } else { securityLayerConform = true; } if (sigInfoElem.hasAttribute(IS_PADES_SIGNATURE_ATTR_NAME)) { - isPAdESSignature = BoolUtils.valueOf(sigInfoElem.getAttribute(IS_PADES_SIGNATURE_ATTR_NAME)); + isPAdESSignature = BoolUtils.valueOf(sigInfoElem.getAttribute(IS_PADES_SIGNATURE_ATTR_NAME)); } - + return factory.createSingleSignatureInfoCMS( - dataObjectInfo, - securityLayerConform, - isPAdESSignature); + dataObjectInfo, + securityLayerConform, + isPAdESSignature); } /** * Parse the DataObjectInfo DOM elements contained in the given * SingleSignatureInfo DOM element. - * - * @param sigInfoElem The SingleSignatureInfo DOM element - * whose DataObjectInfos to parse. + * + * @param sigInfoElem The SingleSignatureInfo DOM element whose + * DataObjectInfos to parse. * @return A List of DataObjectInfo API objects - * containing the data from the DataObjectInfo DOM elements. + * containing the data from the DataObjectInfo DOM + * elements. * @throws MOAApplicationException An error occurred parsing one of the - * DataObjectInfos. + * DataObjectInfos. */ private DataObjectInfo parseDataObjectInfo(Element sigInfoElem) - throws MOAApplicationException { - - Element dataObjInfoElem = (Element)XPathUtils.selectSingleNode(sigInfoElem, DATA_OBJECT_INFO_XPATH); - - String structure = dataObjInfoElem.getAttribute("Structure"); - Element dataObjectElem = - (Element) XPathUtils.selectSingleNode(dataObjInfoElem, DATA_OBJECT_XPATH); - - CMSDataObject dataObject = parseDataObject(dataObjectElem); - - return factory.createDataObjectInfo( - structure, - dataObject); - - } - - + throws MOAApplicationException { + + final Element dataObjInfoElem = (Element) XPathUtils.selectSingleNode(sigInfoElem, + DATA_OBJECT_INFO_XPATH); + + final String structure = dataObjInfoElem.getAttribute("Structure"); + final Element dataObjectElem = + (Element) XPathUtils.selectSingleNode(dataObjInfoElem, DATA_OBJECT_XPATH); - + final CMSDataObject dataObject = parseDataObject(dataObjectElem); + + return factory.createDataObjectInfo( + structure, + dataObject); + + } /** - * Parse a the DataObject DOM element contained in a given + * Parse a the DataObject DOM element contained in a given * CreateCMSSignatureRequest DOM element. - * - * @param requestElem The DataObject DOM element of the VerifyCMSSignatureRequest - * to parse. - * @return The CMSDataObject API object containing the data - * from the DataObject DOM element. + * + * @param requestElem The DataObject DOM element of the + * VerifyCMSSignatureRequest to parse. + * @return The CMSDataObject API object containing the data from + * the DataObject DOM element. */ private CMSDataObject parseDataObject(Element dataObjectElem) { if (dataObjectElem != null) { - Element metaInfoElem = (Element) XPathUtils.selectSingleNode(dataObjectElem, META_INFO_XPATH); + final Element metaInfoElem = (Element) XPathUtils.selectSingleNode(dataObjectElem, META_INFO_XPATH); MetaInfo metaInfo = null; - Element contentElem = (Element) XPathUtils.selectSingleNode(dataObjectElem, CONTENT_XPATH); - CMSContent content = parseContent(contentElem); + final Element contentElem = (Element) XPathUtils.selectSingleNode(dataObjectElem, CONTENT_XPATH); + final CMSContent content = parseContent(contentElem); if (metaInfoElem != null) { metaInfo = RequestParserUtils.parseMetaInfo(metaInfoElem); } - String excludeByteRangeFromStr = XPathUtils.getElementValue(dataObjectElem, EXCLUDEBYTERANGE_FROM_XPATH, null); - String excludeByteRangeToStr = XPathUtils.getElementValue(dataObjectElem, EXCLUDEBYTERANGE_TO_XPATH, null); - + final String excludeByteRangeFromStr = XPathUtils.getElementValue(dataObjectElem, + EXCLUDEBYTERANGE_FROM_XPATH, null); + final String excludeByteRangeToStr = XPathUtils.getElementValue(dataObjectElem, + EXCLUDEBYTERANGE_TO_XPATH, null); + BigDecimal excludeByteRangeFrom = null; BigDecimal excludeByteRangeTo = null; - - if (excludeByteRangeFromStr != null) - excludeByteRangeFrom = new BigDecimal(excludeByteRangeFromStr); - if (excludeByteRangeToStr != null) - excludeByteRangeTo = new BigDecimal(excludeByteRangeToStr); - + + if (excludeByteRangeFromStr != null) { + excludeByteRangeFrom = new BigDecimal(excludeByteRangeFromStr); + } + if (excludeByteRangeToStr != null) { + excludeByteRangeTo = new BigDecimal(excludeByteRangeToStr); + } + return factory.createCMSDataObject(metaInfo, content, excludeByteRangeFrom, excludeByteRangeTo); - } - else { + } else { return null; } } - - - /** - * Parse the content contained in a CMSContentBaseType kind of - * DOM element. - * - * @param contentElem The CMSContentBaseType kind of element to - * parse. - * @return A CMSDataObject API object containing the data - * from the given DOM element. - */ - private CMSContent parseContent(Element contentElem) { - Element base64ContentElem = + /** + * Parse the content contained in a CMSContentBaseType kind of DOM + * element. + * + * @param contentElem The CMSContentBaseType kind of element to + * parse. + * @return A CMSDataObject API object containing the data from the + * given DOM element. + */ + private CMSContent parseContent(Element contentElem) { + final Element base64ContentElem = (Element) XPathUtils.selectSingleNode(contentElem, BASE64_CONTENT_XPATH); - if (base64ContentElem != null) { - String base64Str = DOMUtils.getText(base64ContentElem); - InputStream binaryContent = Base64Utils.decodeToStream(base64Str, true); - return factory.createCMSContent(binaryContent); - } else { - return factory.createCMSContent( + if (base64ContentElem != null) { + final String base64Str = DOMUtils.getText(base64ContentElem); + final InputStream binaryContent = Base64Utils.decodeToStream(base64Str, true); + return factory.createCMSContent(binaryContent); + } else { + return factory.createCMSContent( contentElem.getAttribute("Reference")); - } - } + } + } } \ No newline at end of file diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/CreateCMSSignatureResponseBuilder.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/CreateCMSSignatureResponseBuilder.java index 7ce0871..12b408b 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/CreateCMSSignatureResponseBuilder.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/CreateCMSSignatureResponseBuilder.java @@ -21,14 +21,10 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlbind; -import java.io.IOException; import java.util.Iterator; -import javax.xml.transform.TransformerException; - import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -37,76 +33,71 @@ import at.gv.egovernment.moa.spss.api.cmssign.CMSSignatureResponse; import at.gv.egovernment.moa.spss.api.cmssign.CreateCMSSignatureResponse; import at.gv.egovernment.moa.spss.api.cmssign.CreateCMSSignatureResponseElement; import at.gv.egovernment.moa.spss.api.xmlsign.ErrorResponse; -import at.gv.egovernment.moa.spss.api.xmlsign.SignatureEnvironmentResponse; import at.gv.egovernment.moaspss.util.Constants; -import at.gv.egovernment.moaspss.util.DOMUtils; /** - * Convert a CreateCMSSignatureResponse API object into its - * XML representation, according to the MOA XML schema. - * + * Convert a CreateCMSSignatureResponse API object into its XML + * representation, according to the MOA XML schema. + * * @version $Id$ */ public class CreateCMSSignatureResponseBuilder { private static final String MOA_NS_URI = Constants.MOA_NS_URI; /** The XML document containing the response element. */ - private Document responseDoc; + private final Document responseDoc; /** The response CreateCMSSignatureResponse DOM element. */ - private Element responseElem; + private final Element responseElem; /** * Create a new CreateCMSSignatureResponseBuilder: - * - * @throws MOASystemException An error occurred setting up the resulting - * XML document. + * + * @throws MOASystemException An error occurred setting up the resulting XML + * document. */ public CreateCMSSignatureResponseBuilder() throws MOASystemException { responseDoc = - ResponseBuilderUtils.createResponse("CreateCMSSignatureResponse"); + ResponseBuilderUtils.createResponse("CreateCMSSignatureResponse"); responseElem = responseDoc.getDocumentElement(); } /** - * Build a document containing a CreateCMSSignatureResponse - * DOM element being the XML representation of the given + * Build a document containing a CreateCMSSignatureResponse DOM + * element being the XML representation of the given * CreateCMSSignatureResponse API object. - * - * @param response The CreateCMSSignatureResponse to convert - * to XML. - * @return A document containing the CreateCMSSignatureResponse - * DOM element. + * + * @param response The CreateCMSSignatureResponse to convert to + * XML. + * @return A document containing the CreateCMSSignatureResponse DOM + * element. */ public Document build(CreateCMSSignatureResponse response) { Iterator iter; - - - for (iter = response.getResponseElements().iterator(); iter.hasNext();) { - - Object responseObj = iter.next(); - - if (responseObj instanceof ErrorResponse) { - ErrorResponse errorResponse = (ErrorResponse) responseObj; - addErrorResponse(errorResponse); - - } else if (responseObj instanceof CreateCMSSignatureResponseElement) { - CMSSignatureResponse cmsSignatureResponse = (CMSSignatureResponse) responseObj; - addCMSSignature(cmsSignatureResponse); - - } - + + final Object responseObj = iter.next(); + + if (responseObj instanceof ErrorResponse) { + final ErrorResponse errorResponse = (ErrorResponse) responseObj; + addErrorResponse(errorResponse); + + } else if (responseObj instanceof CreateCMSSignatureResponseElement) { + final CMSSignatureResponse cmsSignatureResponse = (CMSSignatureResponse) responseObj; + addCMSSignature(cmsSignatureResponse); + + } + // CreateCMSSignatureResponseElement responseElement = // (CreateCMSSignatureResponseElement) iter.next(); -// +// // switch (responseElement.getResponseType()) { // case CreateCMSSignatureResponseElement.CMS_SIGNATURE : -// +// // break; // // case CreateCMSSignatureResponseElement.ERROR_RESPONSE : -// +// // break; // } @@ -115,37 +106,35 @@ public class CreateCMSSignatureResponseBuilder { return responseDoc; } - - /** * Add a CMSSignature element to the response. - * + * * @param cmsSignatureResponse The content to put under the - * CMSSignature element. + * CMSSignature element. */ private void addCMSSignature(CMSSignatureResponse cmsSignatureResponse) { - String base64Value = cmsSignatureResponse.getCMSSignature(); - - Element cmsSignature = responseDoc.createElementNS(MOA_NS_URI, "CMSSignature"); - cmsSignature.setTextContent(base64Value); - - responseElem.appendChild(cmsSignature); - -} - + final String base64Value = cmsSignatureResponse.getCMSSignature(); + + final Element cmsSignature = responseDoc.createElementNS(MOA_NS_URI, "CMSSignature"); + cmsSignature.setTextContent(base64Value); + + responseElem.appendChild(cmsSignature); + + } + /** * Add a ErrorResponse element to the response. - * + * * @param errorResponse The API object containing the information to put into - * the ErrorResponse DOM element. + * the ErrorResponse DOM element. */ private void addErrorResponse(ErrorResponse errorResponse) { - Element errorElem = - responseDoc.createElementNS(MOA_NS_URI, "ErrorResponse"); - Element errorCodeElem = - responseDoc.createElementNS(MOA_NS_URI, "ErrorCode"); - Element infoElem = responseDoc.createElementNS(MOA_NS_URI, "Info"); - String errorCodeStr = Integer.toString(errorResponse.getErrorCode()); + final Element errorElem = + responseDoc.createElementNS(MOA_NS_URI, "ErrorResponse"); + final Element errorCodeElem = + responseDoc.createElementNS(MOA_NS_URI, "ErrorCode"); + final Element infoElem = responseDoc.createElementNS(MOA_NS_URI, "Info"); + final String errorCodeStr = Integer.toString(errorResponse.getErrorCode()); errorCodeElem.appendChild(responseDoc.createTextNode(errorCodeStr)); errorElem.appendChild(errorCodeElem); diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/CreateXMLSignatureRequestParser.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/CreateXMLSignatureRequestParser.java index d677f88..8898aaf 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/CreateXMLSignatureRequestParser.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/CreateXMLSignatureRequestParser.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlbind; import java.util.ArrayList; @@ -47,7 +46,7 @@ import at.gv.egovernment.moaspss.util.XPathUtils; /** * A parser to parse CreateXMLSignatureRequest DOM trees into * CreateXMLSignatureRequest API objects. - * + * * @author Patrick Peck * @version $Id$ */ @@ -58,25 +57,25 @@ public class CreateXMLSignatureRequestParser { // private static final String MOA = Constants.MOA_PREFIX + ":"; private static final String KEY_IDENTIFIER_XPATH = - "/" + MOA + "CreateXMLSignatureRequest/" + MOA + "KeyIdentifier"; + "/" + MOA + "CreateXMLSignatureRequest/" + MOA + "KeyIdentifier"; private static final String SINGLE_SIGNATURE_INFO_XPATH = - "/" + MOA + "CreateXMLSignatureRequest/" + MOA + "SingleSignatureInfo"; + "/" + MOA + "CreateXMLSignatureRequest/" + MOA + "SingleSignatureInfo"; private static final String DATA_OBJECT_INFO_XPATH = MOA + "DataObjectInfo"; private static final String DATA_OBJECT_XPATH = MOA + "DataObject"; private static final String CREATE_SIGNATURE_INFO_XPATH = - MOA + "CreateSignatureInfo"; + MOA + "CreateSignatureInfo"; private static final String CREATE_TRANSFORMS_INFO_PROFILE_XPATH = - (MOA + "CreateTransformsInfoProfile | ") - + (MOA + "CreateTransformsInfoProfileID"); + MOA + "CreateTransformsInfoProfile | " + + MOA + "CreateTransformsInfoProfileID"; private static final String CREATE_SIGNATURE_ENVIRONMENT_XPATH = - MOA + "CreateSignatureEnvironment"; + MOA + "CreateSignatureEnvironment"; private static final String CREATE_SIGNATURE_ENVIRONMENT_PROFILE_XPATH = - (MOA + "CreateSignatureEnvironmentProfile | ") - + (MOA + "CreateSignatureEnvironmentProfileID"); + MOA + "CreateSignatureEnvironmentProfile | " + + MOA + "CreateSignatureEnvironmentProfileID"; private static final String SL_CONFORM_ATTR_NAME = "SecurityLayerConformity"; - + /** The factory to create API objects. */ - private SPSSFactory factory; + private final SPSSFactory factory; /** * Create a new CreateXMLSignatureRequestParser. @@ -86,44 +85,43 @@ public class CreateXMLSignatureRequestParser { } /** - * Parse a CreateXMLSignatureRequest DOM element, as defined - * by the MOA schema. - * + * Parse a CreateXMLSignatureRequest DOM element, as defined by the + * MOA schema. + * * @param requestElem The CreateXMLSignatureRequest to parse. The - * request must have been successfully parsed against the schema for this - * method to succeed. - * @return A CreateXMLSignatureRequest API object containing - * the data from the DOM element. + * request must have been successfully parsed against the + * schema for this method to succeed. + * @return A CreateXMLSignatureRequest API object containing the + * data from the DOM element. * @throws MOAApplicationException An error occurred parsing the request. */ public CreateXMLSignatureRequest parse(Element requestElem) - throws MOAApplicationException { + throws MOAApplicationException { - List singleSignatureInfos = parseSingleSignatureInfos(requestElem); - String keyIdentifier = - XPathUtils.getElementValue(requestElem, KEY_IDENTIFIER_XPATH, null); + final List singleSignatureInfos = parseSingleSignatureInfos(requestElem); + final String keyIdentifier = + XPathUtils.getElementValue(requestElem, KEY_IDENTIFIER_XPATH, null); return factory.createCreateXMLSignatureRequest( - keyIdentifier, - singleSignatureInfos); + keyIdentifier, + singleSignatureInfos); } /** - * Parse all SingleSignatureInfo elements of the + * Parse all SingleSignatureInfo elements of the * CreateXMLSignatureRequest. - * + * * @param requestElem The CreateXMLSignatureRequest to parse. - * @return A List of SingleSignatureInfo API - * objects. - * @throws MOAApplicationException An error occurred parsing on of the - * SingleSignatureInfo elements. + * @return A List of SingleSignatureInfo API objects. + * @throws MOAApplicationException An error occurred parsing on of the + * SingleSignatureInfo elements. */ private List parseSingleSignatureInfos(Element requestElem) - throws MOAApplicationException { + throws MOAApplicationException { - List singleSignatureInfos = new ArrayList(); - NodeIterator sigInfoElems = - XPathUtils.selectNodeIterator(requestElem, SINGLE_SIGNATURE_INFO_XPATH); + final List singleSignatureInfos = new ArrayList(); + final NodeIterator sigInfoElems = + XPathUtils.selectNodeIterator(requestElem, SINGLE_SIGNATURE_INFO_XPATH); Element sigInfoElem; while ((sigInfoElem = (Element) sigInfoElems.nextNode()) != null) { @@ -135,52 +133,52 @@ public class CreateXMLSignatureRequestParser { /** * Parse a SingleSignatureInfo DOM element. - * - * @param sigInfoElem The SingleSignatureInfo DOM element to - * parse. - * @return A SingleSignatureInfo API object containing the - * information of sigInfoElem. - * @throws MOAApplicationException An error occurred parsing the - * SingleSignatureInfo. + * + * @param sigInfoElem The SingleSignatureInfo DOM element to parse. + * @return A SingleSignatureInfo API object containing the + * information of sigInfoElem. + * @throws MOAApplicationException An error occurred parsing the + * SingleSignatureInfo. */ private SingleSignatureInfo parseSingleSignatureInfo(Element sigInfoElem) - throws MOAApplicationException { + throws MOAApplicationException { - List dataObjectInfos = parseDataObjectInfos(sigInfoElem); - CreateSignatureInfo createSignatureInfo = - parseCreateSignatureInfo(sigInfoElem); + final List dataObjectInfos = parseDataObjectInfos(sigInfoElem); + final CreateSignatureInfo createSignatureInfo = + parseCreateSignatureInfo(sigInfoElem); boolean securityLayerConform; if (sigInfoElem.hasAttribute(SL_CONFORM_ATTR_NAME)) { securityLayerConform = - BoolUtils.valueOf(sigInfoElem.getAttribute(SL_CONFORM_ATTR_NAME)); + BoolUtils.valueOf(sigInfoElem.getAttribute(SL_CONFORM_ATTR_NAME)); } else { securityLayerConform = true; } return factory.createSingleSignatureInfo( - dataObjectInfos, - createSignatureInfo, - securityLayerConform); + dataObjectInfos, + createSignatureInfo, + securityLayerConform); } /** * Parse the DataObjectInfo DOM elements contained in the given * SingleSignatureInfo DOM element. - * - * @param sigInfoElem The SingleSignatureInfo DOM element - * whose DataObjectInfos to parse. + * + * @param sigInfoElem The SingleSignatureInfo DOM element whose + * DataObjectInfos to parse. * @return A List of DataObjectInfo API objects - * containing the data from the DataObjectInfo DOM elements. + * containing the data from the DataObjectInfo DOM + * elements. * @throws MOAApplicationException An error occurred parsing one of the - * DataObjectInfos. + * DataObjectInfos. */ private List parseDataObjectInfos(Element sigInfoElem) - throws MOAApplicationException { + throws MOAApplicationException { - List dataObjectInfos = new ArrayList(); - NodeIterator dataObjInfoElems = - XPathUtils.selectNodeIterator(sigInfoElem, DATA_OBJECT_INFO_XPATH); + final List dataObjectInfos = new ArrayList(); + final NodeIterator dataObjInfoElems = + XPathUtils.selectNodeIterator(sigInfoElem, DATA_OBJECT_INFO_XPATH); Element dataObjInfoElem; while ((dataObjInfoElem = (Element) dataObjInfoElems.nextNode()) != null) { @@ -191,91 +189,91 @@ public class CreateXMLSignatureRequestParser { /** * Parse a DataObjectInfo DOM element. - * - * @param dataObjInfoElem The DataObjectInfo DOM element to - * parse. - * @return A DataObjectInfo API element containing the data - * from dataObjInfoElem. + * + * @param dataObjInfoElem The DataObjectInfo DOM element to parse. + * @return A DataObjectInfo API element containing the data from + * dataObjInfoElem. * @throws MOAApplicationException An error occurred parsing the - * DataObjectInfo. + * DataObjectInfo. */ private DataObjectInfo parseDataObjectInfo(Element dataObjInfoElem) - throws MOAApplicationException { - - String structure = dataObjInfoElem.getAttribute("Structure"); - Element dataObjectElem = - (Element) XPathUtils.selectSingleNode(dataObjInfoElem, DATA_OBJECT_XPATH); - Content dataObject = RequestParserUtils.parseContent(dataObjectElem); - CreateTransformsInfoProfile createTransformsInfoProfile = - parseCreateTransformsInfoProfile(dataObjInfoElem); + throws MOAApplicationException { + + final String structure = dataObjInfoElem.getAttribute("Structure"); + final Element dataObjectElem = + (Element) XPathUtils.selectSingleNode(dataObjInfoElem, DATA_OBJECT_XPATH); + final Content dataObject = RequestParserUtils.parseContent(dataObjectElem); + final CreateTransformsInfoProfile createTransformsInfoProfile = + parseCreateTransformsInfoProfile(dataObjInfoElem); boolean childOfManifest; if (dataObjInfoElem.hasAttribute("ChildOfManifest")) { childOfManifest = - BoolUtils.valueOf(dataObjInfoElem.getAttribute("ChildOfManifest")); + BoolUtils.valueOf(dataObjInfoElem.getAttribute("ChildOfManifest")); } else { childOfManifest = false; } return factory.createDataObjectInfo( - structure, - childOfManifest, - dataObject, - createTransformsInfoProfile); + structure, + childOfManifest, + dataObject, + createTransformsInfoProfile); } /** * Parse a CreateTransformsInfoProfile DOM element. - * - * @param dataObjInfoElem The DataObjectInfo DOM element - * containing the CreateTransformsInfoProfile. + * + * @param dataObjInfoElem The DataObjectInfo DOM element containing + * the CreateTransformsInfoProfile. * @return The CreateTransformsInfoProfile API object containing - * the profile found in dataObjInfoElem. - * @throws MOAApplicationException An error occurred parsing the - * CreateTransformsInfoProfile. + * the profile found in dataObjInfoElem. + * @throws MOAApplicationException An error occurred parsing the + * CreateTransformsInfoProfile. */ private CreateTransformsInfoProfile parseCreateTransformsInfoProfile(Element dataObjInfoElem) - throws MOAApplicationException { + throws MOAApplicationException { - Element profileElem = - (Element) XPathUtils.selectSingleNode( - dataObjInfoElem, - CREATE_TRANSFORMS_INFO_PROFILE_XPATH); + final Element profileElem = + (Element) XPathUtils.selectSingleNode( + dataObjInfoElem, + CREATE_TRANSFORMS_INFO_PROFILE_XPATH); if ("CreateTransformsInfoProfile".equals(profileElem.getLocalName())) { - ProfileParser profileParser = new ProfileParser(); + final ProfileParser profileParser = new ProfileParser(); return profileParser.parseCreateTransformsInfoProfile(profileElem); } else { - String profileID = DOMUtils.getText(profileElem); + final String profileID = DOMUtils.getText(profileElem); return factory.createCreateTransformsInfoProfile(profileID); } } /** - * Parse the CreateSignatureInfo DOM element contained in - * a SingleSignatureInfo. - * + * Parse the CreateSignatureInfo DOM element contained in a + * SingleSignatureInfo. + * * @param sigInfoElem The SingleSignatureInfo DOM element - * containing the CreateSignatureInfo to be parsed. - * @return A CreateSignatureInfo API object containing the - * data from the CreateSignatureInfo DOM element, or - * null, if none was found. + * containing the CreateSignatureInfo to be + * parsed. + * @return A CreateSignatureInfo API object containing the data + * from the CreateSignatureInfo DOM element, or + * null, if none was found. */ private CreateSignatureInfo parseCreateSignatureInfo(Element sigInfoElem) { - Element createInfoElem = - (Element) XPathUtils.selectSingleNode( - sigInfoElem, - CREATE_SIGNATURE_INFO_XPATH); + final Element createInfoElem = + (Element) XPathUtils.selectSingleNode( + sigInfoElem, + CREATE_SIGNATURE_INFO_XPATH); if (createInfoElem != null) { - Element environmentElem = - (Element) XPathUtils.selectSingleNode( - createInfoElem, - CREATE_SIGNATURE_ENVIRONMENT_XPATH); - Content environment = RequestParserUtils.parseContent(environmentElem); - CreateSignatureEnvironmentProfile environmentProfile = - parseCreateSignatureEnvironmentProfile(createInfoElem); + final Element environmentElem = + (Element) XPathUtils.selectSingleNode( + createInfoElem, + CREATE_SIGNATURE_ENVIRONMENT_XPATH); + final Content environment = RequestParserUtils.parseContent(environmentElem); + final CreateSignatureEnvironmentProfile environmentProfile = + parseCreateSignatureEnvironmentProfile(createInfoElem); return factory.createCreateSignatureInfo(environment, environmentProfile); } else { @@ -284,26 +282,25 @@ public class CreateXMLSignatureRequestParser { } /** - * Parse the CreateSignatureEnvironmentProfile contained in - * the given CreateSignatureInfo DOM element. - * - * @param createInfoElem CreateSignatureInfo DOM element to - * parse. - * @return The CreateSignatureEnvironmentProfile contained - * in the given CreateSignatureInfo DOM element.. + * Parse the CreateSignatureEnvironmentProfile contained in the + * given CreateSignatureInfo DOM element. + * + * @param createInfoElem CreateSignatureInfo DOM element to parse. + * @return The CreateSignatureEnvironmentProfile contained in the + * given CreateSignatureInfo DOM element.. */ private CreateSignatureEnvironmentProfile parseCreateSignatureEnvironmentProfile(Element createInfoElem) { - Element profileElem = - (Element) XPathUtils.selectSingleNode( - createInfoElem, - CREATE_SIGNATURE_ENVIRONMENT_PROFILE_XPATH); + final Element profileElem = + (Element) XPathUtils.selectSingleNode( + createInfoElem, + CREATE_SIGNATURE_ENVIRONMENT_PROFILE_XPATH); if ("CreateSignatureEnvironmentProfile" - .equals(profileElem.getLocalName())) { - ProfileParser profileParser = new ProfileParser(); + .equals(profileElem.getLocalName())) { + final ProfileParser profileParser = new ProfileParser(); return profileParser.parseCreateSignatureEnvironmentProfile(profileElem); } else { - String profileID = DOMUtils.getText(profileElem); + final String profileID = DOMUtils.getText(profileElem); return factory.createCreateSignatureEnvironmentProfile(profileID); } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/CreateXMLSignatureResponseBuilder.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/CreateXMLSignatureResponseBuilder.java index 3c93fce..d6af889 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/CreateXMLSignatureResponseBuilder.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/CreateXMLSignatureResponseBuilder.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlbind; import java.util.Iterator; @@ -38,9 +37,9 @@ import at.gv.egovernment.moa.spss.api.xmlsign.SignatureEnvironmentResponse; import at.gv.egovernment.moaspss.util.Constants; /** - * Convert a CreateXMLSignatureResponse API object into its - * XML representation, according to the MOA XML schema. - * + * Convert a CreateXMLSignatureResponse API object into its XML + * representation, according to the MOA XML schema. + * * @author Patrick Peck * @version $Id$ */ @@ -48,48 +47,48 @@ public class CreateXMLSignatureResponseBuilder { private static final String MOA_NS_URI = Constants.MOA_NS_URI; /** The XML document containing the response element. */ - private Document responseDoc; + private final Document responseDoc; /** The response CreateXMLSignatureResponse DOM element. */ - private Element responseElem; + private final Element responseElem; /** * Create a new CreateXMLSignatureResponseBuilder: - * - * @throws MOASystemException An error occurred setting up the resulting - * XML document. + * + * @throws MOASystemException An error occurred setting up the resulting XML + * document. */ public CreateXMLSignatureResponseBuilder() throws MOASystemException { responseDoc = - ResponseBuilderUtils.createResponse("CreateXMLSignatureResponse"); + ResponseBuilderUtils.createResponse("CreateXMLSignatureResponse"); responseElem = responseDoc.getDocumentElement(); } /** - * Build a document containing a CreateXMLSignatureResponse - * DOM element being the XML representation of the given + * Build a document containing a CreateXMLSignatureResponse DOM + * element being the XML representation of the given * CreateXMLSignatureResponse API object. - * - * @param response The CreateXMLSignatureResponse to convert - * to XML. - * @return A document containing the CreateXMLSignatureResponse - * DOM element. + * + * @param response The CreateXMLSignatureResponse to convert to + * XML. + * @return A document containing the CreateXMLSignatureResponse DOM + * element. */ public Document build(CreateXMLSignatureResponse response) { Iterator iter; for (iter = response.getResponseElements().iterator(); iter.hasNext();) { - CreateXMLSignatureResponseElement responseElement = - (CreateXMLSignatureResponseElement) iter.next(); + final CreateXMLSignatureResponseElement responseElement = + (CreateXMLSignatureResponseElement) iter.next(); switch (responseElement.getResponseType()) { - case CreateXMLSignatureResponseElement.SIGNATURE_ENVIRONMENT_RESPONSE : - SignatureEnvironmentResponse envResponse = - (SignatureEnvironmentResponse) responseElement; + case CreateXMLSignatureResponseElement.SIGNATURE_ENVIRONMENT_RESPONSE: + final SignatureEnvironmentResponse envResponse = + (SignatureEnvironmentResponse) responseElement; addSignatureEnvironment(envResponse); break; - case CreateXMLSignatureResponseElement.ERROR_RESPONSE : - ErrorResponse errorResponse = (ErrorResponse) responseElement; + case CreateXMLSignatureResponseElement.ERROR_RESPONSE: + final ErrorResponse errorResponse = (ErrorResponse) responseElement; addErrorResponse(errorResponse); break; } @@ -101,35 +100,36 @@ public class CreateXMLSignatureResponseBuilder { /** * Add a SignatureEnvironment element to the response. - * + * * @param envResponse The content to put under the - * SignatureEnvironment element. This should either be a - * dsig:Signature element (in case of a detached signature) or - * the signature environment containing the signature (in case of - * an enveloping signature). + * SignatureEnvironment element. This should + * either be a dsig:Signature element (in case + * of a detached signature) or the signature environment + * containing the signature (in case of an enveloping + * signature). */ private void addSignatureEnvironment(SignatureEnvironmentResponse envResponse) { - Element content = envResponse.getSignatureEnvironment(); - Node importedSignature = responseDoc.importNode(content, true); - Element signatureEnvironment = - responseDoc.createElementNS(MOA_NS_URI, "SignatureEnvironment"); + final Element content = envResponse.getSignatureEnvironment(); + final Node importedSignature = responseDoc.importNode(content, true); + final Element signatureEnvironment = + responseDoc.createElementNS(MOA_NS_URI, "SignatureEnvironment"); signatureEnvironment.appendChild(importedSignature); responseElem.appendChild(signatureEnvironment); } /** * Add a ErrorResponse element to the response. - * + * * @param errorResponse The API object containing the information to put into - * the ErrorResponse DOM element. + * the ErrorResponse DOM element. */ private void addErrorResponse(ErrorResponse errorResponse) { - Element errorElem = - responseDoc.createElementNS(MOA_NS_URI, "ErrorResponse"); - Element errorCodeElem = - responseDoc.createElementNS(MOA_NS_URI, "ErrorCode"); - Element infoElem = responseDoc.createElementNS(MOA_NS_URI, "Info"); - String errorCodeStr = Integer.toString(errorResponse.getErrorCode()); + final Element errorElem = + responseDoc.createElementNS(MOA_NS_URI, "ErrorResponse"); + final Element errorCodeElem = + responseDoc.createElementNS(MOA_NS_URI, "ErrorCode"); + final Element infoElem = responseDoc.createElementNS(MOA_NS_URI, "Info"); + final String errorCodeStr = Integer.toString(errorResponse.getErrorCode()); errorCodeElem.appendChild(responseDoc.createTextNode(errorCodeStr)); errorElem.appendChild(errorCodeElem); diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/ProfileParser.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/ProfileParser.java index 6b34922..b8cb361 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/ProfileParser.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/ProfileParser.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlbind; import java.io.IOException; @@ -52,85 +51,86 @@ import at.gv.egovernment.moaspss.util.XPathUtils; /** * Parse the various profile elements contained in the MOA web service requests * and given as separate files in the MOA configuration. - * + * * The profiles parsed must be schema valid according to the MOA XML schema. - * + * * @author Patrick Peck * @version $Id$ */ public class ProfileParser { - + // // XPath expressions to select parts of the profiles // private static final String MOA = Constants.MOA_PREFIX + ":"; private static final String DSIG = Constants.DSIG_PREFIX + ":"; private static final String CREATE_TRANSFORMS_XPATH = - MOA + "CreateTransformsInfo/" + DSIG + "Transforms"; + MOA + "CreateTransformsInfo/" + DSIG + "Transforms"; private static final String FINAL_DATA_META_INFO_XPATH = - MOA + "CreateTransformsInfo/" + MOA + "FinalDataMetaInfo"; + MOA + "CreateTransformsInfo/" + MOA + "FinalDataMetaInfo"; private static final String CREATE_SIGNATURE_LOCATION_XPATH = - MOA + "CreateSignatureLocation"; + MOA + "CreateSignatureLocation"; private static final String SUPPLEMENT_XPATH = MOA + "Supplement"; private static final String VERIFY_TRANSFORMS_XPATH = DSIG + "Transforms"; private static final String TRANSFORM_PARAMETER_XPATH = - MOA + "TransformParameter"; + MOA + "TransformParameter"; private static final String TRANSFORM_PARAMETER_CONTENT_XPATH = - MOA + "Base64Content | " + MOA + "Hash"; + MOA + "Base64Content | " + MOA + "Hash"; private static final String DIGEST_METHOD_XPATH = DSIG + "DigestMethod"; private static final String DIGEST_VALUE_XPATH = DSIG + "DigestValue"; /** The factory used to create API objects. */ - private SPSSFactory factory = SPSSFactory.getInstance(); + private final SPSSFactory factory = SPSSFactory.getInstance(); /** * Parse a CreateTransformsInfoProfile DOM element. - * - * @param profileElem The CreateTransformsInfoProfile element - * to parse. + * + * @param profileElem The CreateTransformsInfoProfile element to + * parse. * @return The CreateTransformsInfoProfile API object containing - * the data from the profileElem. - * @throws MOAApplicationException An error occurred parsing the DOM element. + * the data from the profileElem. + * @throws MOAApplicationException An error occurred parsing the DOM element. */ public CreateTransformsInfoProfile parseCreateTransformsInfoProfile(Element profileElem) - throws MOAApplicationException { - CreateTransformsInfo createTransformsInfo = - parseCreateTransformsInfo(profileElem); - List supplements = parseSupplements(profileElem); + throws MOAApplicationException { + final CreateTransformsInfo createTransformsInfo = + parseCreateTransformsInfo(profileElem); + final List supplements = parseSupplements(profileElem); return factory.createCreateTransformsInfoProfile( - createTransformsInfo, - supplements); + createTransformsInfo, + supplements); } /** - * Parse the CreateTransformsInfo DOM element contained in a + * Parse the CreateTransformsInfo DOM element contained in a * CreateTransformsInfoProfile. - * - * @param profileElem The CreateTransformsInfoProfile DOM - * element containing the CreateTransformsInfo. - * @return The CreateTransformsInfo API object containinig the - * data from the CreateTransformsInfo DOM element. + * + * @param profileElem The CreateTransformsInfoProfile DOM element + * containing the CreateTransformsInfo. + * @return The CreateTransformsInfo API object containinig the data + * from the CreateTransformsInfo DOM element. * @throws MOAApplicationException An error occurred parsing the - * CreateTransformsInfo DOM element. + * CreateTransformsInfo DOM + * element. */ private CreateTransformsInfo parseCreateTransformsInfo(Element profileElem) - throws MOAApplicationException { + throws MOAApplicationException { - Element transformsElem = - (Element) XPathUtils.selectSingleNode( - profileElem, - CREATE_TRANSFORMS_XPATH); - Element metaInfoElem = - (Element) XPathUtils.selectSingleNode( - profileElem, - FINAL_DATA_META_INFO_XPATH); + final Element transformsElem = + (Element) XPathUtils.selectSingleNode( + profileElem, + CREATE_TRANSFORMS_XPATH); + final Element metaInfoElem = + (Element) XPathUtils.selectSingleNode( + profileElem, + FINAL_DATA_META_INFO_XPATH); MetaInfo finalDataMetaInfo; List transforms; - // parse the dsig:Transforms + // parse the dsig:Transforms if (transformsElem != null) { - TransformParser transformsParser = new TransformParser(); + final TransformParser transformsParser = new TransformParser(); transforms = transformsParser.parseTransforms(transformsElem); } else { transforms = null; @@ -144,65 +144,66 @@ public class ProfileParser { /** * Parse a CreateSignatureEnvironmentProfile DOM element. - * - * @param profileElem The CreateSignatureEnvironmentProfile - * DOM element to parse. + * + * @param profileElem The CreateSignatureEnvironmentProfile DOM + * element to parse. * @return The CreateSignatureEnvironmentProfile API object - * containing the data from the profileElem. + * containing the data from the profileElem. */ public CreateSignatureEnvironmentProfile parseCreateSignatureEnvironmentProfile(Element profileElem) { - CreateSignatureLocation createSignatureLocation = - parseCreateSignatureLocation(profileElem); - List supplements = parseSupplements(profileElem); + final CreateSignatureLocation createSignatureLocation = + parseCreateSignatureLocation(profileElem); + final List supplements = parseSupplements(profileElem); return factory.createCreateSignatureEnvironmentProfile( - createSignatureLocation, - supplements); + createSignatureLocation, + supplements); } /** - * Parse a CreateSignatureLocation DOM element contained in - * a CreateSignatureEnvironmentProfile. - * + * Parse a CreateSignatureLocation DOM element contained in a + * CreateSignatureEnvironmentProfile. + * * @param profileElem The CreateSignatureEnvironmentProfile DOM - * element containing the CreateSignatureLocation. - * @return The CreateSignatureLocation API object containing - * the data from the CreateSignatureLocation DOM element. + * element containing the + * CreateSignatureLocation. + * @return The CreateSignatureLocation API object containing the + * data from the CreateSignatureLocation DOM element. */ private CreateSignatureLocation parseCreateSignatureLocation(Element profileElem) { - Element locationElem = - (Element) XPathUtils.selectSingleNode( - profileElem, - CREATE_SIGNATURE_LOCATION_XPATH); - String xPathExpression = DOMUtils.getText(locationElem); - Map namespaceDeclarations = DOMUtils.getNamespaceDeclarations(locationElem); - String indexStr = locationElem.getAttribute("Index"); - int index = Integer.parseInt(indexStr); + final Element locationElem = + (Element) XPathUtils.selectSingleNode( + profileElem, + CREATE_SIGNATURE_LOCATION_XPATH); + final String xPathExpression = DOMUtils.getText(locationElem); + final Map namespaceDeclarations = DOMUtils.getNamespaceDeclarations(locationElem); + final String indexStr = locationElem.getAttribute("Index"); + final int index = Integer.parseInt(indexStr); return factory.createCreateSignatureLocation( - xPathExpression, - index, - namespaceDeclarations); + xPathExpression, + index, + namespaceDeclarations); } /** - * Parse all Supplement DOM elements contained in a given - * parent DOM element. - * + * Parse all Supplement DOM elements contained in a given parent + * DOM element. + * * @param supplementsParentElem The DOM element being the parent of the - * Supplements. - * @return A List of Supplement API objects - * containing the data from the Supplement DOM elements. + * Supplements. + * @return A List of Supplement API objects containing + * the data from the Supplement DOM elements. */ private List parseSupplements(Element supplementsParentElem) { - List supplements = new ArrayList(); - NodeIterator supplementElems = - XPathUtils.selectNodeIterator(supplementsParentElem, SUPPLEMENT_XPATH); + final List supplements = new ArrayList(); + final NodeIterator supplementElems = + XPathUtils.selectNodeIterator(supplementsParentElem, SUPPLEMENT_XPATH); Element supplementElem; while ((supplementElem = (Element) supplementElems.nextNode()) != null) { - XMLDataObjectAssociation supplement = - RequestParserUtils.parseXMLDataObjectAssociation(supplementElem); + final XMLDataObjectAssociation supplement = + RequestParserUtils.parseXMLDataObjectAssociation(supplementElem); supplements.add(supplement); } return supplements; @@ -210,44 +211,44 @@ public class ProfileParser { /** * Parse a SupplementProfile DOM element. - * + * * @param profileElem The SupplementProfile DOM element to parse. - * @return The SupplementProfile API object containing the - * data from the SupplementProfile DOM element. + * @return The SupplementProfile API object containing the data + * from the SupplementProfile DOM element. */ public SupplementProfile parseSupplementProfile(Element profileElem) { - XMLDataObjectAssociation supplementProfile = - RequestParserUtils.parseXMLDataObjectAssociation(profileElem); + final XMLDataObjectAssociation supplementProfile = + RequestParserUtils.parseXMLDataObjectAssociation(profileElem); return factory.createSupplementProfile(supplementProfile); } /** - * Parse a VerifyTransformsInfoProfile DOM element. - * - * @param profileElem The VerifyTransformsInfoProfile DOM - * element to parse. - * @return A VerifyTransformsInfoProfile API object containing - * the information from the VerifyTransformsInfoProfile DOM - * element. + * Parse a VerifyTransformsInfoProfile DOM element. + * + * @param profileElem The VerifyTransformsInfoProfile DOM element + * to parse. + * @return A VerifyTransformsInfoProfile API object containing the + * information from the VerifyTransformsInfoProfile DOM + * element. * @throws MOAApplicationException An error occurred parsing the - * VerifyTransformsInfoProfile. + * VerifyTransformsInfoProfile. */ public VerifyTransformsInfoProfile parseVerifyTransformsInfoProfile(Element profileElem) - throws MOAApplicationException { - Element transformsElem = - (Element) XPathUtils.selectSingleNode( - profileElem, - VERIFY_TRANSFORMS_XPATH); + throws MOAApplicationException { + final Element transformsElem = + (Element) XPathUtils.selectSingleNode( + profileElem, + VERIFY_TRANSFORMS_XPATH); List transforms = null; - NodeIterator paramElems = - XPathUtils.selectNodeIterator(profileElem, TRANSFORM_PARAMETER_XPATH); + final NodeIterator paramElems = + XPathUtils.selectNodeIterator(profileElem, TRANSFORM_PARAMETER_XPATH); Element paramElem; - List transformParameters = new ArrayList(); + final List transformParameters = new ArrayList(); // parse the dsig:Transforms if (transformsElem != null) { - TransformParser transformsParser = new TransformParser(); + final TransformParser transformsParser = new TransformParser(); transforms = transformsParser.parseTransforms(transformsElem); } @@ -257,51 +258,50 @@ public class ProfileParser { } return factory.createVerifyTransformsInfoProfile( - transforms, - transformParameters); + transforms, + transformParameters); } /** * Parse a TransformParameter DOM element. - * - * @param paramElem The TransformParameter DOM element to - * parse. + * + * @param paramElem The TransformParameter DOM element to parse. * @return The TransformParameter API object containing the - * information from the TransformParameter DOM element. + * information from the TransformParameter DOM element. * @throws MOAApplicationException An error occurred parsing the - * TransformParameter DOM element. + * TransformParameter DOM element. */ - private TransformParameter parseTransformParameter(Element paramElem) - throws MOAApplicationException { - String uri = paramElem.getAttribute("URI"); - Element contentElem = - (Element) XPathUtils.selectSingleNode( - paramElem, - TRANSFORM_PARAMETER_CONTENT_XPATH); + private TransformParameter parseTransformParameter(Element paramElem) + throws MOAApplicationException { + final String uri = paramElem.getAttribute("URI"); + final Element contentElem = + (Element) XPathUtils.selectSingleNode( + paramElem, + TRANSFORM_PARAMETER_CONTENT_XPATH); if (contentElem == null) { return factory.createTransformParameter(uri); } else if ("Base64Content".equals(contentElem.getLocalName())) { - String base64Str = DOMUtils.getText(contentElem); - InputStream binaryContent = Base64Utils.decodeToStream(base64Str, true); + final String base64Str = DOMUtils.getText(contentElem); + final InputStream binaryContent = Base64Utils.decodeToStream(base64Str, true); return factory.createTransformParameter(uri, binaryContent); } else { // "Hash".equals(contentElem.getLocalName()) - String digestMethodStr = - XPathUtils.getElementValue(contentElem, DIGEST_METHOD_XPATH, ""); - String digestValueStr = - XPathUtils.getElementValue(contentElem, DIGEST_VALUE_XPATH, ""); + final String digestMethodStr = + XPathUtils.getElementValue(contentElem, DIGEST_METHOD_XPATH, ""); + final String digestValueStr = + XPathUtils.getElementValue(contentElem, DIGEST_VALUE_XPATH, ""); byte[] digestValue = null; try { digestValue = Base64Utils.decode(digestValueStr, true); - } catch (IOException e) { - throw new MOAApplicationException("2270", null); + } catch (final IOException e) { + throw new MOAApplicationException("2270", null); } return factory.createTransformParameter( - uri, - digestMethodStr, - digestValue); + uri, + digestMethodStr, + digestValue); } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/RequestParserUtils.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/RequestParserUtils.java index 99a64d9..173ecbf 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/RequestParserUtils.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/RequestParserUtils.java @@ -42,165 +42,163 @@ import at.gv.egovernment.moaspss.util.XPathUtils; /** * Utility methods for parsing XML requests definied in the MOA XML schema. - * + * * @author Patrick Peck * @version $Id$ */ public class RequestParserUtils { - // - // XPath expressions for parsing parts of a request - // - private static final String MOA = Constants.MOA_PREFIX + ":"; - private static final String REFERENCE_ATTR_NAME = "Reference"; - private static final String MIME_TYPE_XPATH = MOA + "MimeType"; - private static final String DESCRIPTION_XPATH = MOA + "Description"; - private static final String TYPE_XPATH = MOA + "Type"; - private static final String XML_ASSOC_CONTENT_XPATH = MOA + "Content"; - private static final String CONTENT_XPATH = MOA + "Base64Content | " + MOA + "XMLContent |" + MOA + "LocRefContent"; - private static final String ANY_OTHER_XPATH = "*[namespace-uri() != \"" + Constants.MOA_NS_URI + "\"]"; - - /** - * Parse a XMLDataObjectAssociationType kind of DOM element. - * - * @param assocElem - * The XMLDataObjectAssociationType kind of DOM - * elmeent to parse. - * @return The XMLDataObjectAssociation API object containing - * the data from the XMLDataObjectAssociationType DOM - * element. - */ - public static XMLDataObjectAssociation parseXMLDataObjectAssociation(Element assocElem) { - SPSSFactory factory = SPSSFactory.getInstance(); - MetaInfo metaInfo = parseMetaInfo(assocElem); - Element contentElem = (Element) XPathUtils.selectSingleNode(assocElem, XML_ASSOC_CONTENT_XPATH); - Content content = parseContent(contentElem); - - return factory.createXMLDataObjectAssociation(metaInfo, content); - } - - /** - * Parse a MetaInfoType kind of DOM element. - * - * @param metaInfoElem - * The MetaInfoType kind of DOM element. - * @return The MetaInfo API object containing the data from the - * metaInfoElem. - */ - public static MetaInfo parseMetaInfo(Element metaInfoElem) { - SPSSFactory factory = SPSSFactory.getInstance(); - String mimeType = XPathUtils.getElementValue(metaInfoElem, MIME_TYPE_XPATH, null); - String description = XPathUtils.getElementValue(metaInfoElem, DESCRIPTION_XPATH, null); - NodeList anyOther = XPathUtils.selectNodeList(metaInfoElem, ANY_OTHER_XPATH); - String type = XPathUtils.getElementValue(metaInfoElem, TYPE_XPATH, null); - - return factory.createMetaInfo(mimeType, description, anyOther, type); - } - - /** - * Parse a ContentOptionalRefType or - * ContentRequiredRefType kind of DOM element. - * - * @param contentParentElem - * The DOM element being the parent of the content element. - * @return The Content API object containing the data from the - * given DOM element. - */ - public static Content parseContent(Element contentParentElem) { - SPSSFactory factory = SPSSFactory.getInstance(); - String referenceURI = contentParentElem.hasAttribute(REFERENCE_ATTR_NAME) - ? contentParentElem.getAttribute(REFERENCE_ATTR_NAME) : null; - Element contentElem = (Element) XPathUtils.selectSingleNode(contentParentElem, CONTENT_XPATH); - - if (contentElem == null) { - return factory.createContent(referenceURI); - } - - if ("Base64Content".equals(contentElem.getLocalName())) { - String base64String = DOMUtils.getText(contentElem); - return factory.createContent(Base64Utils.decodeToStream(base64String, true), referenceURI); - } else if ("LocRefContent".equals(contentElem.getLocalName())) { - String locationReferenceURI = DOMUtils.getText(contentElem); - return factory.createContent(locationReferenceURI, referenceURI); - } else { // "XMLContent".equals(contentElem.getLocalName()) - return factory.createContent(contentElem.getChildNodes(), referenceURI); - } - } - - /** - * Get the signing time from a Verfiy(CMS|XML)SignatureRequest. - * - * @param requestElem - * A Verify(CMS|XML)SignatureRequest DOM element. - * @param dateTimeXPath - * The XPath to lookup the DateTime element within - * the request. - * @return Date The date and time corresponding to the DateTime - * element in the request. If no DateTime element - * exists in the request, null is returned. - * @throws MOAApplicationException - * An error occurred during a parsing the DateTime - * element or creating the return value. - */ - public static Date parseDateTime(Element requestElem, String dateTimeXPath) throws MOAApplicationException { - - Element dateTimeElem; - String dateTimeText; - - // select the DateTime element - dateTimeElem = (Element) XPathUtils.selectSingleNode(requestElem, dateTimeXPath); - - // parse a date from the element value - if (dateTimeElem != null) { - dateTimeText = DOMUtils.getText(dateTimeElem); - try { - return DateTimeUtils.parseDateTime(dateTimeText); - } catch (ParseException e) { - throw new MOAApplicationException("1104", new Object[] { dateTimeText }); - } - } else { - return null; - } - } - - /** - * Get the signing time from a Verfiy(CMS|XML)SignatureRequest. - * - * @param requestElem - * A Verify(CMS|XML)SignatureRequest DOM element. - * @param dateTimeXPath - * The XPath to lookup the DateTime element within - * the request. - * @return Date The date and time corresponding to the DateTime - * element in the request. If no DateTime element - * exists in the request, null is returned. - * @throws MOAApplicationException - * An error occurred during a parsing the DateTime - * element or creating the return value. - */ - public static boolean parseExtendedValidation(Element requestElem, String extendedValidationXPath, - boolean defaultValue) throws MOAApplicationException { - - Element dateTimeElem; - String dateTimeText; - - // select the DateTime element - dateTimeElem = (Element) XPathUtils.selectSingleNode(requestElem, extendedValidationXPath); - - // parse a date from the element value - if (dateTimeElem != null) { - dateTimeText = DOMUtils.getText(dateTimeElem); - String xsdBoolean = dateTimeText.trim(); - if ("".equals(xsdBoolean)) - return defaultValue; - if("true".equalsIgnoreCase(xsdBoolean) || - "1".equalsIgnoreCase(xsdBoolean)) { - return true; - } else { - return false; - } - } else { - return defaultValue; - } - } + // + // XPath expressions for parsing parts of a request + // + private static final String MOA = Constants.MOA_PREFIX + ":"; + private static final String REFERENCE_ATTR_NAME = "Reference"; + private static final String MIME_TYPE_XPATH = MOA + "MimeType"; + private static final String DESCRIPTION_XPATH = MOA + "Description"; + private static final String TYPE_XPATH = MOA + "Type"; + private static final String XML_ASSOC_CONTENT_XPATH = MOA + "Content"; + private static final String CONTENT_XPATH = MOA + "Base64Content | " + MOA + "XMLContent |" + MOA + + "LocRefContent"; + private static final String ANY_OTHER_XPATH = "*[namespace-uri() != \"" + Constants.MOA_NS_URI + "\"]"; + + /** + * Parse a XMLDataObjectAssociationType kind of DOM element. + * + * @param assocElem The XMLDataObjectAssociationType kind of DOM + * elmeent to parse. + * @return The XMLDataObjectAssociation API object containing the + * data from the XMLDataObjectAssociationType DOM element. + */ + public static XMLDataObjectAssociation parseXMLDataObjectAssociation(Element assocElem) { + final SPSSFactory factory = SPSSFactory.getInstance(); + final MetaInfo metaInfo = parseMetaInfo(assocElem); + final Element contentElem = (Element) XPathUtils.selectSingleNode(assocElem, XML_ASSOC_CONTENT_XPATH); + final Content content = parseContent(contentElem); + + return factory.createXMLDataObjectAssociation(metaInfo, content); + } + + /** + * Parse a MetaInfoType kind of DOM element. + * + * @param metaInfoElem The MetaInfoType kind of DOM element. + * @return The MetaInfo API object containing the data from the + * metaInfoElem. + */ + public static MetaInfo parseMetaInfo(Element metaInfoElem) { + final SPSSFactory factory = SPSSFactory.getInstance(); + final String mimeType = XPathUtils.getElementValue(metaInfoElem, MIME_TYPE_XPATH, null); + final String description = XPathUtils.getElementValue(metaInfoElem, DESCRIPTION_XPATH, null); + final NodeList anyOther = XPathUtils.selectNodeList(metaInfoElem, ANY_OTHER_XPATH); + final String type = XPathUtils.getElementValue(metaInfoElem, TYPE_XPATH, null); + + return factory.createMetaInfo(mimeType, description, anyOther, type); + } + + /** + * Parse a ContentOptionalRefType or + * ContentRequiredRefType kind of DOM element. + * + * @param contentParentElem The DOM element being the parent of the content + * element. + * @return The Content API object containing the data from the + * given DOM element. + */ + public static Content parseContent(Element contentParentElem) { + final SPSSFactory factory = SPSSFactory.getInstance(); + final String referenceURI = contentParentElem.hasAttribute(REFERENCE_ATTR_NAME) + ? contentParentElem.getAttribute(REFERENCE_ATTR_NAME) + : null; + final Element contentElem = (Element) XPathUtils.selectSingleNode(contentParentElem, CONTENT_XPATH); + + if (contentElem == null) { + return factory.createContent(referenceURI); + } + + if ("Base64Content".equals(contentElem.getLocalName())) { + final String base64String = DOMUtils.getText(contentElem); + return factory.createContent(Base64Utils.decodeToStream(base64String, true), referenceURI); + } else if ("LocRefContent".equals(contentElem.getLocalName())) { + final String locationReferenceURI = DOMUtils.getText(contentElem); + return factory.createContent(locationReferenceURI, referenceURI); + } else { // "XMLContent".equals(contentElem.getLocalName()) + return factory.createContent(contentElem.getChildNodes(), referenceURI); + } + } + + /** + * Get the signing time from a Verfiy(CMS|XML)SignatureRequest. + * + * @param requestElem A Verify(CMS|XML)SignatureRequest DOM + * element. + * @param dateTimeXPath The XPath to lookup the DateTime element + * within the request. + * @return Date The date and time corresponding to the DateTime + * element in the request. If no DateTime element exists in + * the request, null is returned. + * @throws MOAApplicationException An error occurred during a parsing the + * DateTime element or creating the + * return value. + */ + public static Date parseDateTime(Element requestElem, String dateTimeXPath) throws MOAApplicationException { + + Element dateTimeElem; + String dateTimeText; + + // select the DateTime element + dateTimeElem = (Element) XPathUtils.selectSingleNode(requestElem, dateTimeXPath); + + // parse a date from the element value + if (dateTimeElem != null) { + dateTimeText = DOMUtils.getText(dateTimeElem); + try { + return DateTimeUtils.parseDateTime(dateTimeText); + } catch (final ParseException e) { + throw new MOAApplicationException("1104", new Object[] { dateTimeText }); + } + } else { + return null; + } + } + + /** + * Get the signing time from a Verfiy(CMS|XML)SignatureRequest. + * + * @param requestElem A Verify(CMS|XML)SignatureRequest DOM + * element. + * @param dateTimeXPath The XPath to lookup the DateTime element + * within the request. + * @return Date The date and time corresponding to the DateTime + * element in the request. If no DateTime element exists in + * the request, null is returned. + * @throws MOAApplicationException An error occurred during a parsing the + * DateTime element or creating the + * return value. + */ + public static boolean parseExtendedValidation(Element requestElem, String extendedValidationXPath, + boolean defaultValue) throws MOAApplicationException { + + Element dateTimeElem; + String dateTimeText; + + // select the DateTime element + dateTimeElem = (Element) XPathUtils.selectSingleNode(requestElem, extendedValidationXPath); + + // parse a date from the element value + if (dateTimeElem != null) { + dateTimeText = DOMUtils.getText(dateTimeElem); + final String xsdBoolean = dateTimeText.trim(); + if ("".equals(xsdBoolean)) { + return defaultValue; + } + if ("true".equalsIgnoreCase(xsdBoolean) || + "1".equalsIgnoreCase(xsdBoolean)) { + return true; + } else { + return false; + } + } else { + return defaultValue; + } + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/ResponseBuilderUtils.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/ResponseBuilderUtils.java index a7113fd..dff1fcc 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/ResponseBuilderUtils.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/ResponseBuilderUtils.java @@ -21,16 +21,14 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlbind; import java.io.IOException; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; -import java.text.SimpleDateFormat; +import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; -import java.util.Calendar; import java.util.TimeZone; import javax.xml.bind.DatatypeConverter; @@ -44,8 +42,6 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; -import iaik.utils.RFC2253NameParser; -import iaik.utils.RFC2253NameParserException; import at.gv.egovernment.moa.spss.MOAApplicationException; import at.gv.egovernment.moa.spss.MOASystemException; import at.gv.egovernment.moa.spss.api.common.ExtendedCertificateCheckResult; @@ -53,10 +49,12 @@ import at.gv.egovernment.moa.spss.api.common.TslInfos; import at.gv.egovernment.moaspss.util.Base64Utils; import at.gv.egovernment.moaspss.util.Constants; import at.gv.egovernment.moaspss.util.MiscUtil; +import iaik.utils.RFC2253NameParser; +import iaik.utils.RFC2253NameParserException; /** * Utility methods used by the verious ResponseBuilder classes. - * + * * @author Patrick Peck * @version $Id$ */ @@ -71,35 +69,35 @@ public class ResponseBuilderUtils { /** * Add an DOM element with a specific name as child to a root element - * + * * @param elementName Name of the DOM element - * @param response Full document with namespace information + * @param response Full document with namespace information * @param rootElement Root element * @return new child DOM element */ public static Element addChildElement(String elementName, Document response, - Element rootElement) { - Element childElement = response.createElementNS(MOA_NS_URI, elementName); - rootElement.appendChild(childElement); - return childElement; - + Element rootElement) { + final Element childElement = response.createElementNS(MOA_NS_URI, elementName); + rootElement.appendChild(childElement); + return childElement; + } - + /** * Create a response element with all the namespaces set. - * + * * @param responseName The name of the response root element. * @return A DOM document containing the response root element and predefined - * MOA, DSIG and XML namespace declarations. + * MOA, DSIG and XML namespace declarations. * @throws MOASystemException An error building the response document. */ public static Document createResponse(String responseName) - throws MOASystemException { + throws MOASystemException { try { - DocumentBuilder docBuilder = - DocumentBuilderFactory.newInstance().newDocumentBuilder(); - DOMImplementation impl = docBuilder.getDOMImplementation(); + final DocumentBuilder docBuilder = + DocumentBuilderFactory.newInstance().newDocumentBuilder(); + final DOMImplementation impl = docBuilder.getDOMImplementation(); Document response; Element root; String attrValue; @@ -113,159 +111,170 @@ public class ResponseBuilderUtils { root.setAttributeNS(XMLNS_NS_URI, attrValue, DSIG_NS_URI); return response; - } catch (ParserConfigurationException e) { + } catch (final ParserConfigurationException e) { throw new MOASystemException("2200", null, e); } } /** * Add a SignerInfo element to the response. - * - * @param response The response document, in order to create new elements in - * it. - * @param root The root element into which the SignerInfo element - * will be inserted. - * @param cert The signer certificate to add. - * @param isQualified Indicates, whether cert is a qualified - * certificate. - * @param isPublicAuthority Indicates, whether cert is - * certificate owned by a public authority. + * + * @param response The response document, in order to create new + * elements in it. + * @param root The root element into which the + * SignerInfo element will be inserted. + * @param cert The signer certificate to add. + * @param isQualified Indicates, whether cert is a qualified + * certificate. + * @param isPublicAuthority Indicates, whether cert is certificate + * owned by a public authority. * @param publicAuthorityID Information about the public authority owning - * cert. Must not be null, if - * isPublicAuthority ! = null. + * cert. Must not be null, if + * isPublicAuthority ! = null. * @throws MOAApplicationException An error occurred reading data from the - * certificate. + * certificate. */ public static void addSignerInfo( - Document response, - Element root, - X509Certificate cert, - boolean isQualified, - String qcSource, - boolean isPublicAuthority, - String publicAuthorityID, - boolean isSSCD, - String sscdSource, - String issuerCountryCode, - TslInfos tslInfos) - throws MOAApplicationException { - - Element signerInfoElem = response.createElementNS(MOA_NS_URI, "SignerInfo"); - Element x509DataElem = - response.createElementNS(DSIG_NS_URI, DSIG + "X509Data"); - Element x509IssuerSerialElem = - response.createElementNS(DSIG_NS_URI, DSIG + "X509IssuerSerial"); - Element x509IssuerElem = - response.createElementNS(DSIG_NS_URI, DSIG + "X509IssuerName"); - String issuer = cert.getIssuerDN().getName(); - Element x509SerialNumberElem = - response.createElementNS(DSIG_NS_URI, DSIG + "X509SerialNumber"); - String serialNumber = cert.getSerialNumber().toString(); - Element x509SubjectNameElem = - response.createElementNS(DSIG_NS_URI, DSIG + "X509SubjectName"); - Element x509CertificateElem = - response.createElementNS(DSIG_NS_URI, DSIG + "X509Certificate"); - Element qualifiedCertificateElem = - isQualified - ? response.createElementNS(MOA_NS_URI, "QualifiedCertificate") - : null; - Element sscdElem = - isSSCD - ? response.createElementNS(MOA_NS_URI, "SecureSignatureCreationDevice") - : null; + Document response, + Element root, + X509Certificate cert, + boolean isQualified, + String qcSource, + boolean isPublicAuthority, + String publicAuthorityID, + boolean isSSCD, + String sscdSource, + String issuerCountryCode, + TslInfos tslInfos) + throws MOAApplicationException { + + final Element signerInfoElem = response.createElementNS(MOA_NS_URI, "SignerInfo"); + final Element x509DataElem = + response.createElementNS(DSIG_NS_URI, DSIG + "X509Data"); + final Element x509IssuerSerialElem = + response.createElementNS(DSIG_NS_URI, DSIG + "X509IssuerSerial"); + final Element x509IssuerElem = + response.createElementNS(DSIG_NS_URI, DSIG + "X509IssuerName"); + final String issuer = cert.getIssuerDN().getName(); + final Element x509SerialNumberElem = + response.createElementNS(DSIG_NS_URI, DSIG + "X509SerialNumber"); + final String serialNumber = cert.getSerialNumber().toString(); + final Element x509SubjectNameElem = + response.createElementNS(DSIG_NS_URI, DSIG + "X509SubjectName"); + final Element x509CertificateElem = + response.createElementNS(DSIG_NS_URI, DSIG + "X509Certificate"); + final Element qualifiedCertificateElem = + isQualified + ? response.createElementNS(MOA_NS_URI, "QualifiedCertificate") + : null; + final Element sscdElem = + isSSCD + ? response.createElementNS(MOA_NS_URI, "SecureSignatureCreationDevice") + : null; Element issuerCountryCodeElem = null; if (issuerCountryCode != null) { - issuerCountryCodeElem = response.createElementNS(MOA_NS_URI, "IssuerCountryCode"); - issuerCountryCodeElem.setTextContent(issuerCountryCode); + issuerCountryCodeElem = response.createElementNS(MOA_NS_URI, "IssuerCountryCode"); + issuerCountryCodeElem.setTextContent(issuerCountryCode); } - - //add TSL infos + + // add TSL infos Element tslInfoElement = null; if (tslInfos != null) { - tslInfoElement = response.createElementNS(MOA_NS_URI, "TSLInformation"); - - //append TSL issuer country-code - if (MiscUtil.isNotEmpty(tslInfos.getTslIssuerCountry())); { - Element tslIssuerCountryCodeElem = response.createElementNS(MOA_NS_URI, "TSLIssuerCountryCode"); - tslIssuerCountryCodeElem.setTextContent(tslInfos.getTslIssuerCountry()); - tslInfoElement.appendChild(tslIssuerCountryCodeElem); - - } - - //append Service-Type Status - if (MiscUtil.isNotEmpty(tslInfos.getServiceTypeStatus())); { - Element tslServiceInfo = response.createElementNS(MOA_NS_URI, "ServiceTypeStatus"); - tslServiceInfo.setTextContent(tslInfos.getServiceTypeStatus()); - tslInfoElement.appendChild(tslServiceInfo); - - } - - //append Service-Type Identifier - if (MiscUtil.isNotEmpty(tslInfos.getServiceTypeIdentifier())); { - Element tslServiceInfo = response.createElementNS(MOA_NS_URI, "ServiceTypeIdentifier"); - tslServiceInfo.setTextContent(tslInfos.getServiceTypeIdentifier()); - tslInfoElement.appendChild(tslServiceInfo); - - } - - //append qualifiers - if (tslInfos.getQualifiers() != null && tslInfos.getQualifiers().size() > 0) { - Element tslQualifiers = response.createElementNS(MOA_NS_URI, "Qualifiers"); - - for (String el : tslInfos.getQualifiers()) { - Element tslQualifier = response.createElementNS(MOA_NS_URI, "Qualifier"); - tslQualifier.setTextContent(el); - tslQualifiers.appendChild(tslQualifier); - - } - - tslInfoElement.appendChild(tslQualifiers); - - } - - //append additional service information - if (tslInfos.getAdditionalServiceInformation() != null - && tslInfos.getAdditionalServiceInformation().size() > 0) { - Element tslAdditionalServiceInformations = response.createElementNS(MOA_NS_URI, "AdditionalServiceInformations"); - - for (String el : tslInfos.getAdditionalServiceInformation()) { - Element tslAdditionalServiceInformation = response.createElementNS(MOA_NS_URI, "AdditionalServiceInformation"); - tslAdditionalServiceInformation.setTextContent(el); - tslAdditionalServiceInformations.appendChild(tslAdditionalServiceInformation); - - } - tslInfoElement.appendChild(tslAdditionalServiceInformations); - - } + tslInfoElement = response.createElementNS(MOA_NS_URI, "TSLInformation"); + + // append TSL issuer country-code + if (MiscUtil.isNotEmpty(tslInfos.getTslIssuerCountry())) { + ; + } + { + final Element tslIssuerCountryCodeElem = response.createElementNS(MOA_NS_URI, "TSLIssuerCountryCode"); + tslIssuerCountryCodeElem.setTextContent(tslInfos.getTslIssuerCountry()); + tslInfoElement.appendChild(tslIssuerCountryCodeElem); + + } + + // append Service-Type Status + if (MiscUtil.isNotEmpty(tslInfos.getServiceTypeStatus())) { + ; + } + { + final Element tslServiceInfo = response.createElementNS(MOA_NS_URI, "ServiceTypeStatus"); + tslServiceInfo.setTextContent(tslInfos.getServiceTypeStatus()); + tslInfoElement.appendChild(tslServiceInfo); + + } + + // append Service-Type Identifier + if (MiscUtil.isNotEmpty(tslInfos.getServiceTypeIdentifier())) { + ; + } + { + final Element tslServiceInfo = response.createElementNS(MOA_NS_URI, "ServiceTypeIdentifier"); + tslServiceInfo.setTextContent(tslInfos.getServiceTypeIdentifier()); + tslInfoElement.appendChild(tslServiceInfo); + + } + + // append qualifiers + if (tslInfos.getQualifiers() != null && tslInfos.getQualifiers().size() > 0) { + final Element tslQualifiers = response.createElementNS(MOA_NS_URI, "Qualifiers"); + + for (final String el : tslInfos.getQualifiers()) { + final Element tslQualifier = response.createElementNS(MOA_NS_URI, "Qualifier"); + tslQualifier.setTextContent(el); + tslQualifiers.appendChild(tslQualifier); + + } + + tslInfoElement.appendChild(tslQualifiers); + + } + + // append additional service information + if (tslInfos.getAdditionalServiceInformation() != null + && tslInfos.getAdditionalServiceInformation().size() > 0) { + final Element tslAdditionalServiceInformations = response.createElementNS(MOA_NS_URI, + "AdditionalServiceInformations"); + + for (final String el : tslInfos.getAdditionalServiceInformation()) { + final Element tslAdditionalServiceInformation = response.createElementNS(MOA_NS_URI, + "AdditionalServiceInformation"); + tslAdditionalServiceInformation.setTextContent(el); + tslAdditionalServiceInformations.appendChild(tslAdditionalServiceInformation); + + } + tslInfoElement.appendChild(tslAdditionalServiceInformations); + + } } - - Element publicAuthorityElem = - isPublicAuthority - ? response.createElementNS(MOA_NS_URI, "PublicAuthority") - : null; - Element codeElem = - publicAuthorityID != null - ? response.createElementNS(MOA_NS_URI, "Code") - : null; + + final Element publicAuthorityElem = + isPublicAuthority + ? response.createElementNS(MOA_NS_URI, "PublicAuthority") + : null; + final Element codeElem = + publicAuthorityID != null + ? response.createElementNS(MOA_NS_URI, "Code") + : null; // fill in text x509IssuerElem.appendChild(response.createTextNode(issuer)); x509SerialNumberElem.appendChild(response.createTextNode(serialNumber)); try { - RFC2253NameParser parser = - new RFC2253NameParser(cert.getSubjectDN().getName()); - String subjectRfc2253 = parser.parse().getRFC2253String(); + final RFC2253NameParser parser = + new RFC2253NameParser(cert.getSubjectDN().getName()); + final String subjectRfc2253 = parser.parse().getRFC2253String(); x509SubjectNameElem.appendChild(response.createTextNode(subjectRfc2253)); - } catch (RFC2253NameParserException e) { + } catch (final RFC2253NameParserException e) { x509SubjectNameElem.appendChild( - response.createTextNode(cert.getSubjectDN().getName())); + response.createTextNode(cert.getSubjectDN().getName())); } try { x509CertificateElem.appendChild( - response.createTextNode(Base64Utils.encode(cert.getEncoded()))); - } catch (CertificateEncodingException e) { + response.createTextNode(Base64Utils.encode(cert.getEncoded()))); + } catch (final CertificateEncodingException e) { throw new MOAApplicationException("2245", null, e); - } catch (IOException e) { + } catch (final IOException e) { throw new MOAApplicationException("2245", null, e); } @@ -276,10 +285,11 @@ public class ResponseBuilderUtils { x509DataElem.appendChild(x509IssuerSerialElem); x509DataElem.appendChild(x509CertificateElem); if (isQualified) { - if (qcSource.compareToIgnoreCase("TSL") == 0) - qualifiedCertificateElem.setAttributeNS(MOA_NS_URI, "Source", qcSource); - - x509DataElem.appendChild(qualifiedCertificateElem); + if (qcSource.compareToIgnoreCase("TSL") == 0) { + qualifiedCertificateElem.setAttributeNS(MOA_NS_URI, "Source", qcSource); + } + + x509DataElem.appendChild(qualifiedCertificateElem); } if (isPublicAuthority) { x509DataElem.appendChild(publicAuthorityElem); @@ -289,16 +299,18 @@ public class ResponseBuilderUtils { } } if (isSSCD) { - sscdElem.setAttributeNS(MOA_NS_URI, "Source", sscdSource); - x509DataElem.appendChild(sscdElem); - } - if (issuerCountryCodeElem != null) - x509DataElem.appendChild(issuerCountryCodeElem); - - //add TSL infos to X509Date if TSL infos exists - if (tslInfoElement != null) - x509DataElem.appendChild(tslInfoElement); - + sscdElem.setAttributeNS(MOA_NS_URI, "Source", sscdSource); + x509DataElem.appendChild(sscdElem); + } + if (issuerCountryCodeElem != null) { + x509DataElem.appendChild(issuerCountryCodeElem); + } + + // add TSL infos to X509Date if TSL infos exists + if (tslInfoElement != null) { + x509DataElem.appendChild(tslInfoElement); + } + signerInfoElem.appendChild(x509DataElem); root.appendChild(signerInfoElem); } @@ -306,24 +318,24 @@ public class ResponseBuilderUtils { /** * Add an element containing Code and Info * subelements. - * - * @param response The response document, in order to create new elements in - * it. - * @param root The root element into which to insert the newly created - * element. + * + * @param response The response document, in order to create new elements in + * it. + * @param root The root element into which to insert the newly created + * element. * @param elementName The name of the newly created element. - * @param code The content of the Code subelement. - * @param info The content of the Info subelement. + * @param code The content of the Code subelement. + * @param info The content of the Info subelement. */ public static void addCodeInfoElement( - Document response, - Element root, - String elementName, - int code, - NodeList info) { - - Element codeInfoElem = response.createElementNS(MOA_NS_URI, elementName); - Element codeElem = response.createElementNS(MOA_NS_URI, "Code"); + Document response, + Element root, + String elementName, + int code, + NodeList info) { + + final Element codeInfoElem = response.createElementNS(MOA_NS_URI, elementName); + final Element codeElem = response.createElementNS(MOA_NS_URI, "Code"); Element infoElem; int i; @@ -339,34 +351,34 @@ public class ResponseBuilderUtils { } root.appendChild(codeInfoElem); } - + /** * Add an element containing Code and Info * subelements. - * - * @param response The response document, in order to create new elements in - * it. - * @param root The root element into which to insert the newly created - * element. + * + * @param response The response document, in order to create new elements in + * it. + * @param root The root element into which to insert the newly created + * element. * @param elementName The name of the newly created element. - * @param code The content of the Code subelement. - * @param info The content of the Info subelement. + * @param code The content of the Code subelement. + * @param info The content of the Info subelement. */ public static void addCodeInfoElement( - Document response, - Element root, - String elementName, - int code, - String info) { - - Element codeInfoElem = response.createElementNS(MOA_NS_URI, elementName); - Element codeElem = response.createElementNS(MOA_NS_URI, "Code"); + Document response, + Element root, + String elementName, + int code, + String info) { + + final Element codeInfoElem = response.createElementNS(MOA_NS_URI, elementName); + final Element codeElem = response.createElementNS(MOA_NS_URI, "Code"); Element infoElem; - int i; + final int i; codeElem.appendChild(response.createTextNode(Integer.toString(code))); codeInfoElem.appendChild(codeElem); - + if (info != null) { infoElem = response.createElementNS(MOA_NS_URI, "Info"); infoElem.appendChild(response.createTextNode(info)); @@ -376,137 +388,138 @@ public class ResponseBuilderUtils { } public static void addSigningTime(Document response, - Element root, - Date signingTime) { - if(signingTime != null) { - Element extElem = response.createElementNS(MOA_NS_URI, "SigningTime"); - TimeZone tz = TimeZone.getTimeZone("UTC"); - Calendar calendar = new GregorianCalendar(); + Element root, + Date signingTime) { + if (signingTime != null) { + final Element extElem = response.createElementNS(MOA_NS_URI, "SigningTime"); + final TimeZone tz = TimeZone.getTimeZone("UTC"); + final Calendar calendar = new GregorianCalendar(); calendar.setTimeZone(tz); calendar.setTime(signingTime); - String date = DatatypeConverter.printDateTime(calendar); + final String date = DatatypeConverter.printDateTime(calendar); extElem.appendChild(response.createTextNode(date)); root.appendChild(extElem); } } public static void addSignatureAlgorithm(Document response, - Element root, - String algorithm) { - if(algorithm != null) { - Element extElem = response.createElementNS(MOA_NS_URI, "SignatureAlgorithm"); - extElem.appendChild(response.createTextNode(algorithm)); - root.appendChild(extElem); - } + Element root, + String algorithm) { + if (algorithm != null) { + final Element extElem = response.createElementNS(MOA_NS_URI, "SignatureAlgorithm"); + extElem.appendChild(response.createTextNode(algorithm)); + root.appendChild(extElem); + } } - + public static void addSignatureCoversFullPDF(Document response, - Element root, - Boolean coversFull) { - if( coversFull != null) { - Element extElem = response.createElementNS(MOA_NS_URI, "SignatureCoversFullPDF"); - extElem.appendChild(response.createTextNode(String.valueOf(coversFull))); - root.appendChild(extElem); - } + Element root, + Boolean coversFull) { + if (coversFull != null) { + final Element extElem = response.createElementNS(MOA_NS_URI, "SignatureCoversFullPDF"); + extElem.appendChild(response.createTextNode(String.valueOf(coversFull))); + root.appendChild(extElem); + } } - + public static void addSignatureByteRange(Document response, - Element root, - int[] byteRange) { - if(byteRange != null) { - String byteRangeTextual = StringUtils.EMPTY; - for (int el : byteRange) - byteRangeTextual += "," + String.valueOf(el); - - Element extElem = response.createElementNS(MOA_NS_URI, "SignatureByteRange"); - extElem.appendChild(response.createTextNode(byteRangeTextual.substring(1))); - root.appendChild(extElem); - } + Element root, + int[] byteRange) { + if (byteRange != null) { + String byteRangeTextual = StringUtils.EMPTY; + for (final int el : byteRange) { + byteRangeTextual += "," + String.valueOf(el); + } + + final Element extElem = response.createElementNS(MOA_NS_URI, "SignatureByteRange"); + extElem.appendChild(response.createTextNode(byteRangeTextual.substring(1))); + root.appendChild(extElem); + } } - + public static Element createAndAddChildElement(Document response, Element root, String name) { - Element element = response.createElementNS(MOA_NS_URI, name); - root.appendChild(element); - return element; - + final Element element = response.createElementNS(MOA_NS_URI, name); + root.appendChild(element); + return element; + } - + public static void addHashAlgorithm(Document response, - Element root, - String algorithm) { - if(algorithm != null) { - Element extElem = response.createElementNS(MOA_NS_URI, "HashAlgorithm"); - extElem.appendChild(response.createTextNode(algorithm)); - root.appendChild(extElem); - } -} - + Element root, + String algorithm) { + if (algorithm != null) { + final Element extElem = response.createElementNS(MOA_NS_URI, "HashAlgorithm"); + extElem.appendChild(response.createTextNode(algorithm)); + root.appendChild(extElem); + } + } + public static void addExtendendResult(Document response, - Element root, - ExtendedCertificateCheckResult result) { - Element extElem = response.createElementNS(MOA_NS_URI, "ExtendedCertificateCheck"); - - Element extMajorElem = response.createElementNS(MOA_NS_URI, "Major"); - - Element codeMajorCodeElem = response.createElementNS(MOA_NS_URI, "Code"); - Element codeMajorNameElem = response.createElementNS(MOA_NS_URI, "Name"); - codeMajorCodeElem.appendChild(response.createTextNode(Integer.toString( - result.getMajorCode()))); - codeMajorNameElem.appendChild(response.createTextNode(result.getMajorInfo())); - - extMajorElem.appendChild(codeMajorCodeElem); - extMajorElem.appendChild(codeMajorNameElem); - - extElem.appendChild(extMajorElem); - - if(result.getMinorCode() >= 0) { - Element extMinorElem = response.createElementNS(MOA_NS_URI, "Minor"); - Element codeMinorCodeElem = response.createElementNS(MOA_NS_URI, "Code"); - Element codeMinorNameElem = response.createElementNS(MOA_NS_URI, "Name"); - codeMinorCodeElem.appendChild(response.createTextNode(Integer.toString( - result.getMinorCode()))); - codeMinorNameElem.appendChild(response.createTextNode(result.getMinorInfo())); - - extMinorElem.appendChild(codeMinorCodeElem); - extMinorElem.appendChild(codeMinorNameElem); - - extElem.appendChild(extMinorElem); - } - - root.appendChild(extElem); + Element root, + ExtendedCertificateCheckResult result) { + final Element extElem = response.createElementNS(MOA_NS_URI, "ExtendedCertificateCheck"); + + final Element extMajorElem = response.createElementNS(MOA_NS_URI, "Major"); + + final Element codeMajorCodeElem = response.createElementNS(MOA_NS_URI, "Code"); + final Element codeMajorNameElem = response.createElementNS(MOA_NS_URI, "Name"); + codeMajorCodeElem.appendChild(response.createTextNode(Integer.toString( + result.getMajorCode()))); + codeMajorNameElem.appendChild(response.createTextNode(result.getMajorInfo())); + + extMajorElem.appendChild(codeMajorCodeElem); + extMajorElem.appendChild(codeMajorNameElem); + + extElem.appendChild(extMajorElem); + + if (result.getMinorCode() >= 0) { + final Element extMinorElem = response.createElementNS(MOA_NS_URI, "Minor"); + final Element codeMinorCodeElem = response.createElementNS(MOA_NS_URI, "Code"); + final Element codeMinorNameElem = response.createElementNS(MOA_NS_URI, "Name"); + codeMinorCodeElem.appendChild(response.createTextNode(Integer.toString( + result.getMinorCode()))); + codeMinorNameElem.appendChild(response.createTextNode(result.getMinorInfo())); + + extMinorElem.appendChild(codeMinorCodeElem); + extMinorElem.appendChild(codeMinorNameElem); + + extElem.appendChild(extMinorElem); + } + + root.appendChild(extElem); } - + /** * Add an element containing Code and Info * subelements. - * - * @param response The response document, in order to create new elements in - * it. - * @param root The root element into which to insert the newly created - * element. + * + * @param response The response document, in order to create new elements in + * it. + * @param root The root element into which to insert the newly created + * element. * @param elementName The name of the newly created element. - * @param code The content of the Code subelement. - * @param info The content of the Info subelement. + * @param code The content of the Code subelement. + * @param info The content of the Info subelement. */ public static void addFormCheckElement( - Document response, - Element root, - String elementName, - int code, - String name) { - - Element codeInfoElem = response.createElementNS(MOA_NS_URI, elementName); - Element codeElem = response.createElementNS(MOA_NS_URI, "Code"); + Document response, + Element root, + String elementName, + int code, + String name) { + + final Element codeInfoElem = response.createElementNS(MOA_NS_URI, elementName); + final Element codeElem = response.createElementNS(MOA_NS_URI, "Code"); Element infoElem; - + codeElem.appendChild(response.createTextNode(Integer.toString(code))); codeInfoElem.appendChild(codeElem); - + infoElem = response.createElementNS(MOA_NS_URI, "Name"); infoElem.appendChild(response.createTextNode(name)); codeInfoElem.appendChild(infoElem); - + root.appendChild(codeInfoElem); } - + } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/TransformParser.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/TransformParser.java index 6dc4803..7a246d6 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/TransformParser.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/TransformParser.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlbind; import java.util.ArrayList; @@ -48,9 +47,9 @@ import at.gv.egovernment.moaspss.util.DOMUtils; import at.gv.egovernment.moaspss.util.XPathUtils; /** - * A parser to parse XMLDsig Transform DOM elements into their - * MOA SPSS API representation. - * + * A parser to parse XMLDsig Transform DOM elements into their MOA + * SPSS API representation. + * * @author Patrick Peck * @version $Id$ */ @@ -60,39 +59,38 @@ public class TransformParser { // private static final String DSIG = Constants.DSIG_PREFIX + ":"; private static final String DSIG_FILTER2 = - Constants.DSIG_FILTER2_PREFIX + ":"; + Constants.DSIG_FILTER2_PREFIX + ":"; private static final String XSLT = Constants.XSLT_PREFIX + ":"; private static final String EC = Constants.DSIG_EC_PREFIX + ":"; private static final String TRANSFORM_XPATH = DSIG + "Transform"; private static final String XPATH_XPATH = DSIG + "XPath"; private static final String XSLT_ELEMENT_XPATH = XSLT + "stylesheet"; private static final String XPATH2_XPATH = - (DSIG_FILTER2 + "XPath[@Filter=\"intersect\"] | ") - + (DSIG_FILTER2 + "XPath[@Filter=\"subtract\"] | ") - + (DSIG_FILTER2 + "XPath[@Filter=\"union\"]"); + DSIG_FILTER2 + "XPath[@Filter=\"intersect\"] | " + + DSIG_FILTER2 + "XPath[@Filter=\"subtract\"] | " + + DSIG_FILTER2 + "XPath[@Filter=\"union\"]"; private static final String INCLUSIVE_NAMESPACES_XPATH = - EC + "InclusiveNamespaces"; + EC + "InclusiveNamespaces"; /** * The SPSSFactory to use for creating new API objects. */ - private SPSSFactory factory = SPSSFactory.getInstance(); + private final SPSSFactory factory = SPSSFactory.getInstance(); /** * Parse an XMLDsig Transforms DOM element. - * + * * @param transformsElem The Transforms DOM element to parse. - * @return A List of Transform API objects - * containing the data from the individual Transform DOM - * elements. - * @throws MOAApplicationException An error occurred parsing the - * Transforms DOM element. + * @return A List of Transform API objects containing + * the data from the individual Transform DOM elements. + * @throws MOAApplicationException An error occurred parsing the + * Transforms DOM element. */ public List parseTransforms(Element transformsElem) - throws MOAApplicationException { - List transforms = new ArrayList(); - NodeIterator transformElems = - XPathUtils.selectNodeIterator(transformsElem, TRANSFORM_XPATH); + throws MOAApplicationException { + final List transforms = new ArrayList(); + final NodeIterator transformElems = + XPathUtils.selectNodeIterator(transformsElem, TRANSFORM_XPATH); Element transformElem; Transform transform; @@ -106,34 +104,31 @@ public class TransformParser { /** * Parse an XMLDsig Transform DOM element. - * + * * @param transformElem Transform DOM element to parse. - * @return The Transform API object containing the data - * from the Transform DOM element. - * @throws MOAApplicationException An error occurred parsing the - * Transform DOM element. + * @return The Transform API object containing the data from the + * Transform DOM element. + * @throws MOAApplicationException An error occurred parsing the + * Transform DOM element. */ public Transform parseTransform(Element transformElem) - throws MOAApplicationException { + throws MOAApplicationException { - String algorithmUri = transformElem.getAttribute("Algorithm"); + final String algorithmUri = transformElem.getAttribute("Algorithm"); if (CanonicalizationTransform.CANONICAL_XML.equals(algorithmUri) - || CanonicalizationTransform.CANONICAL_XML_WITH_COMMENTS.equals( - algorithmUri)) { + || CanonicalizationTransform.CANONICAL_XML_WITH_COMMENTS.equals( + algorithmUri)) { return factory.createCanonicalizationTransform(algorithmUri); - } else if ( - ExclusiveCanonicalizationTransform.EXCLUSIVE_CANONICAL_XML.equals( + } else if (ExclusiveCanonicalizationTransform.EXCLUSIVE_CANONICAL_XML.equals( algorithmUri) - || ExclusiveCanonicalizationTransform - .EXCLUSIVE_CANONICAL_XML_WITH_COMMENTS - .equals( - algorithmUri)) { + || ExclusiveCanonicalizationTransform.EXCLUSIVE_CANONICAL_XML_WITH_COMMENTS + .equals( + algorithmUri)) { return parseExclusiveC14nTransform(algorithmUri, transformElem); } else if (Base64Transform.BASE64_DECODING.equals(algorithmUri)) { return factory.createBase64Transform(); - } else if ( - EnvelopedSignatureTransform.ENVELOPED_SIGNATURE.equals(algorithmUri)) { + } else if (EnvelopedSignatureTransform.ENVELOPED_SIGNATURE.equals(algorithmUri)) { return factory.createEnvelopedSignatureTransform(); } else if (XPathTransform.XPATH.equals(algorithmUri)) { return parseXPathTransform(transformElem); @@ -148,49 +143,47 @@ public class TransformParser { /** * Parse an exclusive canonicalization type of transform. - * - * @param algorithmUri The algorithm URI of the canonicalization algorithm. + * + * @param algorithmUri The algorithm URI of the canonicalization algorithm. * @param transformElem The Transform DOM element to parse. * @return An ExclusiveCanonicalizationTransform API object - * containing the data from the transformElem. + * containing the data from the transformElem. */ private Transform parseExclusiveC14nTransform( - String algorithmUri, - Element transformElem) - { + String algorithmUri, + Element transformElem) { - Element inclusiveNamespacesElem = - (Element) XPathUtils.selectSingleNode( - transformElem, - INCLUSIVE_NAMESPACES_XPATH); + final Element inclusiveNamespacesElem = + (Element) XPathUtils.selectSingleNode( + transformElem, + INCLUSIVE_NAMESPACES_XPATH); - List inclusiveNamespaces = new ArrayList(); - if (inclusiveNamespacesElem != null) - { - StringTokenizer tokenizer = new StringTokenizer(inclusiveNamespacesElem.getAttribute("PrefixList")); - while (tokenizer.hasMoreTokens()) - { + final List inclusiveNamespaces = new ArrayList(); + if (inclusiveNamespacesElem != null) { + final StringTokenizer tokenizer = new StringTokenizer(inclusiveNamespacesElem.getAttribute( + "PrefixList")); + while (tokenizer.hasMoreTokens()) { inclusiveNamespaces.add(tokenizer.nextToken()); } } return factory.createExclusiveCanonicalizationTransform( - algorithmUri, - inclusiveNamespaces); + algorithmUri, + inclusiveNamespaces); } /** * Parse an XPath type of Transform. - * + * * @param transformElem The Transform DOM element to parse. * @return The Transform API object representation of the - * Transform DOM element. - * @throws MOAApplicationException An error occurred parsing the - * Transform DOM element. + * Transform DOM element. + * @throws MOAApplicationException An error occurred parsing the + * Transform DOM element. */ private Transform parseXPathTransform(Element transformElem) - throws MOAApplicationException { - Element xPathElem = - (Element) XPathUtils.selectSingleNode(transformElem, XPATH_XPATH); + throws MOAApplicationException { + final Element xPathElem = + (Element) XPathUtils.selectSingleNode(transformElem, XPATH_XPATH); Map nsDecls; if (xPathElem == null) { @@ -205,22 +198,22 @@ public class TransformParser { /** * Parse an XPathFilter2 type of Transform. - * + * * @param transformElem The Transform DOM element to parse. * @return The Transform API object representation of the - * Transform DOM element. - * @throws MOAApplicationException An error occurred parsing the - * Transform DOM element. + * Transform DOM element. + * @throws MOAApplicationException An error occurred parsing the + * Transform DOM element. */ private Transform parseXPathFilter2Transform(Element transformElem) - throws MOAApplicationException { - List filters = new ArrayList(); - NodeIterator iter = - XPathUtils.selectNodeIterator(transformElem, XPATH2_XPATH); + throws MOAApplicationException { + final List filters = new ArrayList(); + final NodeIterator iter = + XPathUtils.selectNodeIterator(transformElem, XPATH2_XPATH); Element filterElem; while ((filterElem = (Element) iter.nextNode()) != null) { - String filterAttr = filterElem.getAttribute("Filter"); + final String filterAttr = filterElem.getAttribute("Filter"); String filterType; String expression; Map nsDecls; @@ -247,17 +240,17 @@ public class TransformParser { /** * Parse an XSLT type of Transform. - * + * * @param transformElem The Transform DOM element to parse. * @return The Transform API object representation of the - * Transform DOM element. - * @throws MOAApplicationException An error occurred parsing the - * Transform DOM element. + * Transform DOM element. + * @throws MOAApplicationException An error occurred parsing the + * Transform DOM element. */ private Transform parseXSLTTransform(Element transformElem) - throws MOAApplicationException { - Element xsltElem = - (Element) XPathUtils.selectSingleNode(transformElem, XSLT_ELEMENT_XPATH); + throws MOAApplicationException { + final Element xsltElem = + (Element) XPathUtils.selectSingleNode(transformElem, XSLT_ELEMENT_XPATH); if (xsltElem == null) { throw new MOAApplicationException("2215", null); diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/VerifyCMSSignatureRequestParser.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/VerifyCMSSignatureRequestParser.java index cb07b34..bcab978 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/VerifyCMSSignatureRequestParser.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/VerifyCMSSignatureRequestParser.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlbind; import java.io.InputStream; @@ -39,7 +38,6 @@ import at.gv.egovernment.moa.spss.api.cmsverify.CMSContent; import at.gv.egovernment.moa.spss.api.cmsverify.CMSDataObject; import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureRequest; import at.gv.egovernment.moa.spss.api.common.MetaInfo; -import at.gv.egovernment.moaspss.logging.Logger; import at.gv.egovernment.moaspss.util.Base64Utils; import at.gv.egovernment.moaspss.util.CollectionUtils; import at.gv.egovernment.moaspss.util.Constants; @@ -49,7 +47,7 @@ import at.gv.egovernment.moaspss.util.XPathUtils; /** * A parser to parse VerifyCMSSignatureRequest DOM trees into * VerifyCMSSignatureRequest API objects. - * + * * @author Patrick Peck * @version $Id$ */ @@ -63,7 +61,7 @@ public class VerifyCMSSignatureRequestParser { private static final String EXTENDED_VALIDATION_XPATH = MOA + "ExtendedValidation"; private static final String CMS_SIGNATURE_XPATH = MOA + "CMSSignature"; private static final String PDF_SIGNATURE_XPATH = MOA + "PDFSignature"; - + private static final String TRUST_PROFILE_ID_XPATH = MOA + "TrustProfileID"; private static final String DATA_OBJECT_XPATH = MOA + "DataObject"; private static final String META_INFO_XPATH = MOA + "MetaInfo"; @@ -72,110 +70,109 @@ public class VerifyCMSSignatureRequestParser { private static final String EXCLUDEBYTERANGE_FROM_XPATH = MOA + "ExcludedByteRange/" + MOA + "From"; private static final String EXCLUDEBYTERANGE_TO_XPATH = MOA + "ExcludedByteRange/" + MOA + "To"; - /** The SPSSFactory for creating new API objects. */ - private SPSSFactory factory = SPSSFactory.getInstance(); + private final SPSSFactory factory = SPSSFactory.getInstance(); /** - * Parse a VerifyCMSSignatureRequest DOM element, as defined - * by the MOA schema. - * + * Parse a VerifyCMSSignatureRequest DOM element, as defined by the + * MOA schema. + * * @param requestElem The VerifyCMSSignatureRequest to parse. The - * request must have been successfully parsed against the schema for this - * method to succeed. - * @return A VerifyCMSSignatureRequest API objects containing - * the data from the DOM element. + * request must have been successfully parsed against the + * schema for this method to succeed. + * @return A VerifyCMSSignatureRequest API objects containing the + * data from the DOM element. * @throws MOAApplicationException An error occurred parsing the request. */ public VerifyCMSSignatureRequest parsePDF(Element requestElem) - throws MOAApplicationException { - - int[] signatories = parseSignatories(requestElem); - Date dateTime = - RequestParserUtils.parseDateTime(requestElem, DATE_TIME_XPATH); - boolean extendedValidation = - RequestParserUtils.parseExtendedValidation(requestElem, EXTENDED_VALIDATION_XPATH, false); - - String cmsSignatureStr = - XPathUtils.getElementValue(requestElem, PDF_SIGNATURE_XPATH, ""); - CMSDataObject dataObject = parseDataObject(requestElem); - String trustProfileID = - XPathUtils.getElementValue(requestElem, TRUST_PROFILE_ID_XPATH, null); - //Logger.info("CMSSignature: " + cmsSignatureStr); - InputStream cmsSignature = - Base64Utils.decodeToStream(cmsSignatureStr, true); + throws MOAApplicationException { + + final int[] signatories = parseSignatories(requestElem); + final Date dateTime = + RequestParserUtils.parseDateTime(requestElem, DATE_TIME_XPATH); + final boolean extendedValidation = + RequestParserUtils.parseExtendedValidation(requestElem, EXTENDED_VALIDATION_XPATH, false); + + final String cmsSignatureStr = + XPathUtils.getElementValue(requestElem, PDF_SIGNATURE_XPATH, ""); + final CMSDataObject dataObject = parseDataObject(requestElem); + final String trustProfileID = + XPathUtils.getElementValue(requestElem, TRUST_PROFILE_ID_XPATH, null); + // Logger.info("CMSSignature: " + cmsSignatureStr); + final InputStream cmsSignature = + Base64Utils.decodeToStream(cmsSignatureStr, true); return factory.createVerifyCMSSignatureRequest( - signatories, - dateTime, - cmsSignature, - dataObject, - trustProfileID, - true, - extendedValidation); + signatories, + dateTime, + cmsSignature, + dataObject, + trustProfileID, + true, + extendedValidation); } - + /** - * Parse a VerifyCMSSignatureRequest DOM element, as defined - * by the MOA schema. - * + * Parse a VerifyCMSSignatureRequest DOM element, as defined by the + * MOA schema. + * * @param requestElem The VerifyCMSSignatureRequest to parse. The - * request must have been successfully parsed against the schema for this - * method to succeed. - * @return A VerifyCMSSignatureRequest API objects containing - * the data from the DOM element. + * request must have been successfully parsed against the + * schema for this method to succeed. + * @return A VerifyCMSSignatureRequest API objects containing the + * data from the DOM element. * @throws MOAApplicationException An error occurred parsing the request. */ public VerifyCMSSignatureRequest parse(Element requestElem) - throws MOAApplicationException { - - int[] signatories = parseSignatories(requestElem); - Date dateTime = - RequestParserUtils.parseDateTime(requestElem, DATE_TIME_XPATH); - boolean extendedValidation = - RequestParserUtils.parseExtendedValidation(requestElem, EXTENDED_VALIDATION_XPATH, false); - - String cmsSignatureStr = - XPathUtils.getElementValue(requestElem, CMS_SIGNATURE_XPATH, ""); - CMSDataObject dataObject = parseDataObject(requestElem); - String trustProfileID = - XPathUtils.getElementValue(requestElem, TRUST_PROFILE_ID_XPATH, null); - InputStream cmsSignature = - Base64Utils.decodeToStream(cmsSignatureStr, true); + throws MOAApplicationException { + + final int[] signatories = parseSignatories(requestElem); + final Date dateTime = + RequestParserUtils.parseDateTime(requestElem, DATE_TIME_XPATH); + final boolean extendedValidation = + RequestParserUtils.parseExtendedValidation(requestElem, EXTENDED_VALIDATION_XPATH, false); + + final String cmsSignatureStr = + XPathUtils.getElementValue(requestElem, CMS_SIGNATURE_XPATH, ""); + final CMSDataObject dataObject = parseDataObject(requestElem); + final String trustProfileID = + XPathUtils.getElementValue(requestElem, TRUST_PROFILE_ID_XPATH, null); + final InputStream cmsSignature = + Base64Utils.decodeToStream(cmsSignatureStr, true); return factory.createVerifyCMSSignatureRequest( - signatories, - dateTime, - cmsSignature, - dataObject, - trustProfileID, - false, - extendedValidation); + signatories, + dateTime, + cmsSignature, + dataObject, + trustProfileID, + false, + extendedValidation); } /** - * Parse the Signatories attribute contained in the + * Parse the Signatories attribute contained in the * VerifyCMSSignatureRequest DOM element. - * + * * @param requestElem The VerifyCMSSignatureRequest DOM element. - * @return The signatories contained in the given - * VerifyCMSSignatureRequest DOM element. + * @return The signatories contained in the given + * VerifyCMSSignatureRequest DOM element. */ private int[] parseSignatories(Element requestElem) { - String signatoriesStr = requestElem.getAttribute("Signatories"); + final String signatoriesStr = requestElem.getAttribute("Signatories"); if ("all".equals(signatoriesStr)) { return VerifyCMSSignatureRequest.ALL_SIGNATORIES; } else { - StringTokenizer tokenizer = new StringTokenizer(signatoriesStr); - List signatoriesList = new ArrayList(); + final StringTokenizer tokenizer = new StringTokenizer(signatoriesStr); + final List signatoriesList = new ArrayList(); int[] signatories; // put the signatories into a List while (tokenizer.hasMoreTokens()) { try { signatoriesList.add(new Integer(tokenizer.nextToken())); - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { // this cannot occur if the request has been validated } } @@ -188,44 +185,47 @@ public class VerifyCMSSignatureRequestParser { } /** - * Parse a the DataObject DOM element contained in a given + * Parse a the DataObject DOM element contained in a given * VerifyCMSSignatureRequest DOM element. - * - * @param requestElem The VerifyCMSSignatureRequest DOM element - * to parse. - * @return The CMSDataObject API object containing the data - * from the DataObject DOM element. + * + * @param requestElem The VerifyCMSSignatureRequest DOM element to + * parse. + * @return The CMSDataObject API object containing the data from + * the DataObject DOM element. */ private CMSDataObject parseDataObject(Element requestElem) { - Element dataObjectElem = - (Element) XPathUtils.selectSingleNode(requestElem, DATA_OBJECT_XPATH); + final Element dataObjectElem = + (Element) XPathUtils.selectSingleNode(requestElem, DATA_OBJECT_XPATH); if (dataObjectElem != null) { - Element metaInfoElem = - (Element) XPathUtils.selectSingleNode(dataObjectElem, META_INFO_XPATH); + final Element metaInfoElem = + (Element) XPathUtils.selectSingleNode(dataObjectElem, META_INFO_XPATH); MetaInfo metaInfo = null; - Element contentElem = - (Element) XPathUtils.selectSingleNode(dataObjectElem, CONTENT_XPATH); - CMSContent content = parseContent(contentElem); + final Element contentElem = + (Element) XPathUtils.selectSingleNode(dataObjectElem, CONTENT_XPATH); + final CMSContent content = parseContent(contentElem); if (metaInfoElem != null) { metaInfo = RequestParserUtils.parseMetaInfo(metaInfoElem); } - String excludeByteRangeFromStr = XPathUtils.getElementValue(dataObjectElem, EXCLUDEBYTERANGE_FROM_XPATH, null); - String excludeByteRangeToStr = XPathUtils.getElementValue(dataObjectElem, EXCLUDEBYTERANGE_TO_XPATH, null); - + final String excludeByteRangeFromStr = XPathUtils.getElementValue(dataObjectElem, + EXCLUDEBYTERANGE_FROM_XPATH, null); + final String excludeByteRangeToStr = XPathUtils.getElementValue(dataObjectElem, + EXCLUDEBYTERANGE_TO_XPATH, null); + BigDecimal excludeByteRangeFrom = null; BigDecimal excludeByteRangeTo = null; - - if (excludeByteRangeFromStr != null) - excludeByteRangeFrom = new BigDecimal(excludeByteRangeFromStr); - if (excludeByteRangeToStr != null) - excludeByteRangeTo = new BigDecimal(excludeByteRangeToStr); + + if (excludeByteRangeFromStr != null) { + excludeByteRangeFrom = new BigDecimal(excludeByteRangeFromStr); + } + if (excludeByteRangeToStr != null) { + excludeByteRangeTo = new BigDecimal(excludeByteRangeToStr); + } return factory.createCMSDataObject(metaInfo, content, excludeByteRangeFrom, excludeByteRangeTo); - - + } else { return null; } @@ -233,25 +233,25 @@ public class VerifyCMSSignatureRequestParser { } /** - * Parse the content contained in a CMSContentBaseType kind of - * DOM element. - * + * Parse the content contained in a CMSContentBaseType kind of DOM + * element. + * * @param contentElem The CMSContentBaseType kind of element to - * parse. - * @return A CMSDataObject API object containing the data - * from the given DOM element. + * parse. + * @return A CMSDataObject API object containing the data from the + * given DOM element. */ private CMSContent parseContent(Element contentElem) { - Element base64ContentElem = - (Element) XPathUtils.selectSingleNode(contentElem, BASE64_CONTENT_XPATH); + final Element base64ContentElem = + (Element) XPathUtils.selectSingleNode(contentElem, BASE64_CONTENT_XPATH); if (base64ContentElem != null) { - String base64Str = DOMUtils.getText(base64ContentElem); - InputStream binaryContent = Base64Utils.decodeToStream(base64Str, true); + final String base64Str = DOMUtils.getText(base64ContentElem); + final InputStream binaryContent = Base64Utils.decodeToStream(base64Str, true); return factory.createCMSContent(binaryContent); } else { return factory.createCMSContent( - contentElem.getAttribute("Reference")); + contentElem.getAttribute("Reference")); } } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/VerifyCMSSignatureResponseBuilder.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/VerifyCMSSignatureResponseBuilder.java index de39948..265d0f3 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/VerifyCMSSignatureResponseBuilder.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/VerifyCMSSignatureResponseBuilder.java @@ -21,13 +21,10 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlbind; import java.util.Iterator; -import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureResponse; -import at.gv.egovernment.moaspss.util.Constants; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -38,137 +35,138 @@ import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureResponseElemen import at.gv.egovernment.moa.spss.api.common.CheckResult; import at.gv.egovernment.moa.spss.api.common.SignerInfo; import at.gv.egovernment.moa.spss.api.xmlverify.AdESFormResults; +import at.gv.egovernment.moaspss.util.Constants; /** - * Convert a VerifyCMSSignatureResponse API object into its - * XML representation, according to the MOA XML schema. - * + * Convert a VerifyCMSSignatureResponse API object into its XML + * representation, according to the MOA XML schema. + * * @author Patrick Peck * @version $Id$ */ public class VerifyCMSSignatureResponseBuilder { /** The XML document containing the response element. */ - private Document responseDoc; + private final Document responseDoc; /** The response VerifyCMSSignatureResponse DOM element. */ - private Element responseElem; + private final Element responseElem; private boolean includeSigningTime = false; /** * Create a new VerifyCMSSignatureResponseBuilder: - * - * @throws MOASystemException An error occurred setting up the resulting - * XML document. + * + * @throws MOASystemException An error occurred setting up the resulting XML + * document. */ public VerifyCMSSignatureResponseBuilder() throws MOASystemException { responseDoc = - ResponseBuilderUtils.createResponse("VerifyCMSSignatureResponse"); + ResponseBuilderUtils.createResponse("VerifyCMSSignatureResponse"); responseElem = responseDoc.getDocumentElement(); } - public VerifyCMSSignatureResponseBuilder(Document responseDoc, String name, boolean includeSigningTime) throws MOASystemException { - this.responseDoc = responseDoc; - responseElem = responseDoc.createElementNS(Constants.MOA_NS_URI, name); - this.includeSigningTime = includeSigningTime; - } + public VerifyCMSSignatureResponseBuilder(Document responseDoc, String name, boolean includeSigningTime) + throws MOASystemException { + this.responseDoc = responseDoc; + responseElem = responseDoc.createElementNS(Constants.MOA_NS_URI, name); + this.includeSigningTime = includeSigningTime; + } + + public Element buildElement(VerifyCMSSignatureResponse response) throws MOAApplicationException { + this.build(response); + return responseElem; + } - public Element buildElement(VerifyCMSSignatureResponse response) throws MOAApplicationException { - this.build(response); - return responseElem; - } - /** - * Build a document containing a VerifyCMSSignatureResponse - * DOM element being the XML representation of the given + * Build a document containing a VerifyCMSSignatureResponse DOM + * element being the XML representation of the given * VerifyCMSSignatureResponse API object. - * - * @param response The VerifyCMSSignatureResponse to convert - * to XML. - * @return A document containing the VerifyCMSSignatureResponse - * DOM element. + * + * @param response The VerifyCMSSignatureResponse to convert to + * XML. + * @return A document containing the VerifyCMSSignatureResponse DOM + * element. * @throws MOAApplicationException An error occurred building the response. */ public Document build(VerifyCMSSignatureResponse response) - throws MOAApplicationException { + throws MOAApplicationException { Iterator iter; for (iter = response.getResponseElements().iterator(); iter.hasNext();) { - VerifyCMSSignatureResponseElement responseElement = - (VerifyCMSSignatureResponseElement) iter.next(); + final VerifyCMSSignatureResponseElement responseElement = + (VerifyCMSSignatureResponseElement) iter.next(); addResponseElement(responseElement); } - + return responseDoc; } /** * Add an element to the response. - * + * * @param responseElement The element to add to the response. * @throws MOAApplicationException An error occurred adding the element. */ private void addResponseElement(VerifyCMSSignatureResponseElement responseElement) - throws MOAApplicationException { + throws MOAApplicationException { + + final SignerInfo signerInfo = responseElement.getSignerInfo(); + final CheckResult signatureCheck = responseElement.getSignatureCheck(); + final CheckResult certCheck = responseElement.getCertificateCheck(); - SignerInfo signerInfo = responseElement.getSignerInfo(); - CheckResult signatureCheck = responseElement.getSignatureCheck(); - CheckResult certCheck = responseElement.getCertificateCheck(); - ResponseBuilderUtils.addSignerInfo( - responseDoc, - responseElem, - signerInfo.getSignerCertificate(), - signerInfo.isQualifiedCertificate(), - signerInfo.getQCSource(), - signerInfo.isPublicAuthority(), - signerInfo.getPublicAuhtorityID(), - signerInfo.isSSCD(), - signerInfo.getSSCDSource(), - signerInfo.getIssuerCountryCode(), - signerInfo.getTslInfos()); - - if(this.includeSigningTime) { + responseDoc, + responseElem, + signerInfo.getSignerCertificate(), + signerInfo.isQualifiedCertificate(), + signerInfo.getQCSource(), + signerInfo.isPublicAuthority(), + signerInfo.getPublicAuhtorityID(), + signerInfo.isSSCD(), + signerInfo.getSSCDSource(), + signerInfo.getIssuerCountryCode(), + signerInfo.getTslInfos()); + + if (this.includeSigningTime) { ResponseBuilderUtils.addSigningTime(responseDoc, - responseElem, signerInfo.getSigningTime()); + responseElem, signerInfo.getSigningTime()); } ResponseBuilderUtils.addSignatureAlgorithm(responseDoc, - responseElem, - responseElement.getSignatureAlgorithm()); - - + responseElem, + responseElement.getSignatureAlgorithm()); + ResponseBuilderUtils.addCodeInfoElement( - responseDoc, - responseElem, - "SignatureCheck", - signatureCheck.getCode(), - signatureCheck.getInfo()); + responseDoc, + responseElem, + "SignatureCheck", + signatureCheck.getCode(), + signatureCheck.getInfo()); ResponseBuilderUtils.addCodeInfoElement( - responseDoc, - responseElem, - "CertificateCheck", - certCheck.getCode(), - certCheck.getInfo()); - + responseDoc, + responseElem, + "CertificateCheck", + certCheck.getCode(), + certCheck.getInfo()); if (responseElement.getAdESFormResults() != null) { - Iterator formIterator = responseElement.getAdESFormResults().iterator(); - - while (formIterator.hasNext()) { - AdESFormResults adESFormResult = (AdESFormResults) formIterator.next(); - // add the CertificateCheck - ResponseBuilderUtils.addFormCheckElement(responseDoc, responseElem, "FormCheckResult", - adESFormResult.getCode().intValue(), adESFormResult.getName()); - - } - } - - if(responseElement.getExtendedCertificateCheck() != null) { - ResponseBuilderUtils.addExtendendResult(responseDoc, responseElem, responseElement.getExtendedCertificateCheck()); - } - + final Iterator formIterator = responseElement.getAdESFormResults().iterator(); + + while (formIterator.hasNext()) { + final AdESFormResults adESFormResult = (AdESFormResults) formIterator.next(); + // add the CertificateCheck + ResponseBuilderUtils.addFormCheckElement(responseDoc, responseElem, "FormCheckResult", + adESFormResult.getCode().intValue(), adESFormResult.getName()); + + } + } + + if (responseElement.getExtendedCertificateCheck() != null) { + ResponseBuilderUtils.addExtendendResult(responseDoc, responseElem, responseElement + .getExtendedCertificateCheck()); + } + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/VerifyPDFSignatureResponseBuilder.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/VerifyPDFSignatureResponseBuilder.java index 499f514..b9b7d26 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/VerifyPDFSignatureResponseBuilder.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/VerifyPDFSignatureResponseBuilder.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlbind; import java.util.Iterator; @@ -39,145 +38,144 @@ import at.gv.egovernment.moa.spss.api.xmlverify.AdESFormResults; import at.gv.egovernment.moaspss.logging.Logger; /** - * Convert a VerifyCMSSignatureResponse API object into its - * XML representation, according to the MOA XML schema. - * + * Convert a VerifyCMSSignatureResponse API object into its XML + * representation, according to the MOA XML schema. + * * @author Patrick Peck * @version $Id$ */ public class VerifyPDFSignatureResponseBuilder { /** The XML document containing the response element. */ - private Document responseDoc; + private final Document responseDoc; /** The response VerifyCMSSignatureResponse DOM element. */ - private Element responseRootElem; + private final Element responseRootElem; /** * Create a new VerifyCMSSignatureResponseBuilder: - * - * @throws MOASystemException An error occurred setting up the resulting - * XML document. + * + * @throws MOASystemException An error occurred setting up the resulting XML + * document. */ public VerifyPDFSignatureResponseBuilder() throws MOASystemException { responseDoc = - ResponseBuilderUtils.createResponse("VerifyPDFSignatureResponse"); + ResponseBuilderUtils.createResponse("VerifyPDFSignatureResponse"); responseRootElem = responseDoc.getDocumentElement(); } - + /** - * Build a document containing a VerifyCMSSignatureResponse - * DOM element being the XML representation of the given + * Build a document containing a VerifyCMSSignatureResponse DOM + * element being the XML representation of the given * VerifyCMSSignatureResponse API object. - * - * @param response The VerifyCMSSignatureResponse to convert - * to XML. - * @return A document containing the VerifyCMSSignatureResponse - * DOM element. + * + * @param response The VerifyCMSSignatureResponse to convert to + * XML. + * @return A document containing the VerifyCMSSignatureResponse DOM + * element. * @throws MOAApplicationException An error occurred building the response. */ public Document build(VerifyCMSSignatureResponse response) - throws MOAApplicationException { + throws MOAApplicationException { Iterator iter; - for (iter = response.getResponseElements().iterator(); iter.hasNext();) { - VerifyCMSSignatureResponseElement responseElement = - (VerifyCMSSignatureResponseElement) iter.next(); - Element signatureResult = ResponseBuilderUtils.addChildElement("SignatureResult", responseDoc, responseRootElem); + final VerifyCMSSignatureResponseElement responseElement = + (VerifyCMSSignatureResponseElement) iter.next(); + final Element signatureResult = ResponseBuilderUtils.addChildElement("SignatureResult", responseDoc, + responseRootElem); addResponseElement(responseElement, signatureResult); - + } - + return responseDoc; } /** * Add an element to the response. - * + * * @param responseElement The element to add to the response. - * @param signatureResult + * @param signatureResult * @throws MOAApplicationException An error occurred adding the element. */ private void addResponseElement(VerifyCMSSignatureResponseElement responseElement, Element responseElem) - throws MOAApplicationException { + throws MOAApplicationException { + + final SignerInfo signerInfo = responseElement.getSignerInfo(); + final CheckResult signatureCheck = responseElement.getSignatureCheck(); + final CheckResult certCheck = responseElement.getCertificateCheck(); - SignerInfo signerInfo = responseElement.getSignerInfo(); - CheckResult signatureCheck = responseElement.getSignatureCheck(); - CheckResult certCheck = responseElement.getCertificateCheck(); - if (signerInfo != null) { - ResponseBuilderUtils.addSignerInfo( - responseDoc, - responseElem, - signerInfo.getSignerCertificate(), - signerInfo.isQualifiedCertificate(), - signerInfo.getQCSource(), - signerInfo.isPublicAuthority(), - signerInfo.getPublicAuhtorityID(), - signerInfo.isSSCD(), - signerInfo.getSSCDSource(), - signerInfo.getIssuerCountryCode(), - signerInfo.getTslInfos()); - - ResponseBuilderUtils.addSigningTime(responseDoc, - responseElem, - signerInfo.getSigningTime()); - - + ResponseBuilderUtils.addSignerInfo( + responseDoc, + responseElem, + signerInfo.getSignerCertificate(), + signerInfo.isQualifiedCertificate(), + signerInfo.getQCSource(), + signerInfo.isPublicAuthority(), + signerInfo.getPublicAuhtorityID(), + signerInfo.isSSCD(), + signerInfo.getSSCDSource(), + signerInfo.getIssuerCountryCode(), + signerInfo.getTslInfos()); + + ResponseBuilderUtils.addSigningTime(responseDoc, + responseElem, + signerInfo.getSigningTime()); + } else { - Logger.info("Find signature result with no 'SignerInfo'. Maybe a signature verification Failed"); - + Logger.info("Find signature result with no 'SignerInfo'. Maybe a signature verification Failed"); + } ResponseBuilderUtils.addSignatureAlgorithm(responseDoc, - responseElem, - responseElement.getSignatureAlgorithm()); - + responseElem, + responseElement.getSignatureAlgorithm()); + ResponseBuilderUtils.addCodeInfoElement( - responseDoc, - responseElem, - "SignatureCheck", - signatureCheck.getCode(), - signatureCheck.getInfo()); + responseDoc, + responseElem, + "SignatureCheck", + signatureCheck.getCode(), + signatureCheck.getInfo()); ResponseBuilderUtils.addCodeInfoElement( - responseDoc, - responseElem, - "CertificateCheck", - certCheck.getCode(), - certCheck.getInfo()); - + responseDoc, + responseElem, + "CertificateCheck", + certCheck.getCode(), + certCheck.getInfo()); if (responseElement.getAdESFormResults() != null) { - Iterator formIterator = responseElement.getAdESFormResults().iterator(); - - while (formIterator.hasNext()) { - AdESFormResults adESFormResult = (AdESFormResults) formIterator.next(); - // add the CertificateCheck - ResponseBuilderUtils.addFormCheckElement(responseDoc, responseElem, "FormCheckResult", - adESFormResult.getCode().intValue(), adESFormResult.getName()); - - } - } - - if(responseElement.getExtendedCertificateCheck() != null) { - ResponseBuilderUtils.addExtendendResult(responseDoc, responseElem, responseElement.getExtendedCertificateCheck()); - } - - - //add additional PDF signature properteis - if (responseElement.getCoversFullDocument() != null || - responseElement.getByteRangeOfSignature() != null) { - Element pdfSigProps = ResponseBuilderUtils.createAndAddChildElement(responseDoc, responseElem, "SignatureProperties"); - ResponseBuilderUtils.addSignatureCoversFullPDF(responseDoc, - pdfSigProps, - responseElement.getCoversFullDocument()); - ResponseBuilderUtils.addSignatureByteRange(responseDoc, - pdfSigProps, - responseElement.getByteRangeOfSignature()); + final Iterator formIterator = responseElement.getAdESFormResults().iterator(); + + while (formIterator.hasNext()) { + final AdESFormResults adESFormResult = (AdESFormResults) formIterator.next(); + // add the CertificateCheck + ResponseBuilderUtils.addFormCheckElement(responseDoc, responseElem, "FormCheckResult", + adESFormResult.getCode().intValue(), adESFormResult.getName()); + + } + } + + if (responseElement.getExtendedCertificateCheck() != null) { + ResponseBuilderUtils.addExtendendResult(responseDoc, responseElem, responseElement + .getExtendedCertificateCheck()); + } + + // add additional PDF signature properteis + if (responseElement.getCoversFullDocument() != null || + responseElement.getByteRangeOfSignature() != null) { + final Element pdfSigProps = ResponseBuilderUtils.createAndAddChildElement(responseDoc, responseElem, + "SignatureProperties"); + ResponseBuilderUtils.addSignatureCoversFullPDF(responseDoc, + pdfSigProps, + responseElement.getCoversFullDocument()); + ResponseBuilderUtils.addSignatureByteRange(responseDoc, + pdfSigProps, + responseElement.getByteRangeOfSignature()); } - + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/VerifyXMLSignatureRequestParser.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/VerifyXMLSignatureRequestParser.java index f1bb1d7..1360c5f 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/VerifyXMLSignatureRequestParser.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/VerifyXMLSignatureRequestParser.java @@ -51,236 +51,230 @@ import at.gv.egovernment.moaspss.util.XPathUtils; */ public class VerifyXMLSignatureRequestParser { - // - // XPath expressions for parsing parts of the request - // - private static final String MOA = Constants.MOA_PREFIX + ":"; - private static final String DATE_TIME_XPATH = MOA + "DateTime"; - private static final String EXTENDED_VALIDATION_XPATH = MOA + "ExtendedValidation"; - private static final String RETURN_HASH_INPUT_DATA_XPATH = MOA + "ReturnHashInputData"; - private static final String TRUST_PROFILE_ID_XPATH = MOA + "TrustProfileID"; - private static final String VERIFY_SIGNATURE_ENVIRONMENT_XPATH = MOA + "VerifySignatureInfo/" + MOA - + "VerifySignatureEnvironment"; - private static final String VERIFY_SIGNATURE_LOCATION_XPATH = MOA + "VerifySignatureInfo/" + MOA - + "VerifySignatureLocation"; - private static final String SUPPLEMENT_PROFILE_XPATH = MOA + "SupplementProfile | " + MOA + "SupplementProfileID"; - private static final String SIGNATURE_MANIFEST_CHECK_PARAMS_XPATH = MOA + "SignatureManifestCheckParams"; - private static final String VERIFY_TRANSFORMS_INFO_PROFILE_XPATH = (MOA + "VerifyTransformsInfoProfile | ") - + (MOA + "VerifyTransformsInfoProfileID"); - private static final String REFERENCE_INFO_XPATH = MOA + "ReferenceInfo"; - - /** The SPSSFactory for creating new API objects. */ - private SPSSFactory factory = SPSSFactory.getInstance(); - - /** - * Parse a VerifyXMLSignatureRequest DOM element, as defined - * by the MOA schema. - * + // + // XPath expressions for parsing parts of the request + // + private static final String MOA = Constants.MOA_PREFIX + ":"; + private static final String DATE_TIME_XPATH = MOA + "DateTime"; + private static final String EXTENDED_VALIDATION_XPATH = MOA + "ExtendedValidation"; + private static final String RETURN_HASH_INPUT_DATA_XPATH = MOA + "ReturnHashInputData"; + private static final String TRUST_PROFILE_ID_XPATH = MOA + "TrustProfileID"; + private static final String VERIFY_SIGNATURE_ENVIRONMENT_XPATH = MOA + "VerifySignatureInfo/" + MOA + + "VerifySignatureEnvironment"; + private static final String VERIFY_SIGNATURE_LOCATION_XPATH = MOA + "VerifySignatureInfo/" + MOA + + "VerifySignatureLocation"; + private static final String SUPPLEMENT_PROFILE_XPATH = MOA + "SupplementProfile | " + MOA + + "SupplementProfileID"; + private static final String SIGNATURE_MANIFEST_CHECK_PARAMS_XPATH = MOA + "SignatureManifestCheckParams"; + private static final String VERIFY_TRANSFORMS_INFO_PROFILE_XPATH = MOA + "VerifyTransformsInfoProfile | " + + MOA + "VerifyTransformsInfoProfileID"; + private static final String REFERENCE_INFO_XPATH = MOA + "ReferenceInfo"; + + /** The SPSSFactory for creating new API objects. */ + private final SPSSFactory factory = SPSSFactory.getInstance(); + + /** + * Parse a VerifyXMLSignatureRequest DOM element, as defined by the + * MOA schema. + * * @param requestElem The VerifyXMLSignatureRequest to parse. The - * request must have been successfully parsed against the schema for this - * method to succeed. - * @return A VerifyXMLSignatureRequest API object containing - * the data from the DOM element. + * request must have been successfully parsed against the + * schema for this method to succeed. + * @return A VerifyXMLSignatureRequest API object containing the + * data from the DOM element. * @throws MOAApplicationException An error occurred parsing the request. */ public VerifyXMLSignatureRequest parse(Element requestElem) - throws MOAApplicationException { - - Date dateTime = - RequestParserUtils.parseDateTime(requestElem, DATE_TIME_XPATH); - - boolean extendedValidation = - RequestParserUtils.parseExtendedValidation(requestElem, EXTENDED_VALIDATION_XPATH, false); - - VerifySignatureInfo verifySignatureInfo = - parseVerifySignatureInfo(requestElem); - List supplementProfiles = parseSupplementProfiles(requestElem); - SignatureManifestCheckParams signatureManifestCheckParams = - parseSignatureManifestCheckParams(requestElem); - boolean returnHashInputData = - XPathUtils.selectSingleNode(requestElem, RETURN_HASH_INPUT_DATA_XPATH) - != null; - String trustProfileID = - XPathUtils.getElementValue(requestElem, TRUST_PROFILE_ID_XPATH, null); + throws MOAApplicationException { + + final Date dateTime = + RequestParserUtils.parseDateTime(requestElem, DATE_TIME_XPATH); + + final boolean extendedValidation = + RequestParserUtils.parseExtendedValidation(requestElem, EXTENDED_VALIDATION_XPATH, false); + + final VerifySignatureInfo verifySignatureInfo = + parseVerifySignatureInfo(requestElem); + final List supplementProfiles = parseSupplementProfiles(requestElem); + final SignatureManifestCheckParams signatureManifestCheckParams = + parseSignatureManifestCheckParams(requestElem); + final boolean returnHashInputData = + XPathUtils.selectSingleNode(requestElem, RETURN_HASH_INPUT_DATA_XPATH) != null; + final String trustProfileID = + XPathUtils.getElementValue(requestElem, TRUST_PROFILE_ID_XPATH, null); return factory.createVerifyXMLSignatureRequest( - dateTime, - verifySignatureInfo, - supplementProfiles, - signatureManifestCheckParams, - returnHashInputData, - trustProfileID, - extendedValidation); + dateTime, + verifySignatureInfo, + supplementProfiles, + signatureManifestCheckParams, + returnHashInputData, + trustProfileID, + extendedValidation); } - /** - * Parse the VerifySignatureInfo DOM element contained in the - * VerifyXMLSignatureRequest DOM element. - * - * @param requestElem - * The VerifyXMLSignatureRequest DOM element - * containing the VerifySignatureInfo DOM element. - * @return The VerifySignatureInfo API object containing the - * data from the DOM element. - */ - private VerifySignatureInfo parseVerifySignatureInfo(Element requestElem) { - Element verifySignatureEnvironmentElem = (Element) XPathUtils.selectSingleNode(requestElem, - VERIFY_SIGNATURE_ENVIRONMENT_XPATH); - Content verifySignatureEnvironment = RequestParserUtils.parseContent(verifySignatureEnvironmentElem); - VerifySignatureLocation verifySignatureLocation = parseVerifySignatureLocation(requestElem); - - return factory.createVerifySignatureInfo(verifySignatureEnvironment, verifySignatureLocation); - } - - /** - * Parse the VerifySignatureLocation DOM element contained in - * the given VerifyXMLSignatureRequest DOM element. - * - * @param requestElem - * The VerifyXMLSignatureRequst DOM element. - * @return The VerifySignatureLocation API object containing - * the data from the DOM element. - */ - private VerifySignatureLocation parseVerifySignatureLocation(Element requestElem) { - Element locationElem = (Element) XPathUtils.selectSingleNode(requestElem, VERIFY_SIGNATURE_LOCATION_XPATH); - String xPathExpression = DOMUtils.getText(locationElem); - Map namespaceDeclarations = DOMUtils.getNamespaceDeclarations(locationElem); - - return factory.createVerifySignatureLocation(xPathExpression, namespaceDeclarations); - } - - /** - * Parse the supplement profiles contained in the given - * VerifyXMLSignatureRequest DOM element. - * - * @param requestElem - * The VerifyXMLSignatureRequest DOM element. - * @return A List of SupplementProfile API objects - * containing the data from the SupplementProfile DOM - * elements. - */ - private List parseSupplementProfiles(Element requestElem) { - List supplementProfiles = new ArrayList(); - NodeIterator profileElems = XPathUtils.selectNodeIterator(requestElem, SUPPLEMENT_PROFILE_XPATH); - Element profileElem; - - while ((profileElem = (Element) profileElems.nextNode()) != null) { - SupplementProfile profile; - - if ("SupplementProfile".equals(profileElem.getLocalName())) { - ProfileParser profileParser = new ProfileParser(); - profile = profileParser.parseSupplementProfile(profileElem); - } else { - String profileID = DOMUtils.getText(profileElem); - profile = factory.createSupplementProfile(profileID); - } - supplementProfiles.add(profile); - } - return supplementProfiles; - } - - /** - * Parse the SignatureManifestCheckParams DOM element contained - * in the given VerifyXMLSignatureRequest DOM element. - * - * @param requestElem - * The VerifyXMLSignatureRequest DOM element. - * @return The SignatureManifestCheckParams API object - * containing the data from the - * SignatureManifestCheckParams DOM element. - * @throws MOAApplicationException - * An error occurred parsing the - * SignatureManifestCheckParams DOM element. - */ - private SignatureManifestCheckParams parseSignatureManifestCheckParams(Element requestElem) - throws MOAApplicationException { - Element paramsElem = (Element) XPathUtils.selectSingleNode(requestElem, SIGNATURE_MANIFEST_CHECK_PARAMS_XPATH); - - if (paramsElem != null) { - String returnReferenceInputDataStr = paramsElem.getAttribute("ReturnReferenceInputData"); - boolean returnReferencInputData = BoolUtils.valueOf(returnReferenceInputDataStr); - List referenceInfos = parseReferenceInfos(paramsElem); - - return factory.createSignatureManifestCheckParams(referenceInfos, returnReferencInputData); - } else { - return null; - } - } - - /** - * Parse the ReferenceInfo DOM elements contained in a - * SignatureManifestCheckParams DOM element. - * - * @param paramsElem - * The SignatureManifestCheckParams DOM element - * containing the ReferenceInfo DOM elements. - * @return A List of RefernceInfo API objects - * containing the data from the ReferenceInfo DOM - * elements. - * @throws MOAApplicationException - * An error occurred parsing the ReferenceInfo DOM - * elements. - */ - private List parseReferenceInfos(Element paramsElem) throws MOAApplicationException { - - List referenceInfos = new ArrayList(); - NodeIterator refInfoElems = XPathUtils.selectNodeIterator(paramsElem, REFERENCE_INFO_XPATH); - Element refInfoElem; - - while ((refInfoElem = (Element) refInfoElems.nextNode()) != null) { - ReferenceInfo referenceInfo = parseReferenceInfo(refInfoElem); - - referenceInfos.add(referenceInfo); - } - - return referenceInfos; - } - - /** - * Parse a ReferenceInfo DOM element. - * - * @param refInfoElem - * The ReferenceInfo DOM element to parse. - * @return The ReferenceInfo API object containing the data - * from the given ReferenceInfo DOM element. - * @throws MOAApplicationException - * An error occurred parsing the ReferenceInfo DOM - * element. - */ - private ReferenceInfo parseReferenceInfo(Element refInfoElem) throws MOAApplicationException { - List profiles = parseVerifyTransformsInfoProfiles(refInfoElem); - return factory.createReferenceInfo(profiles); - } - - /** - * Parse the VerifyTransformsInfoProfile DOM elements contained - * in a ReferenceInfo DOM element. - * - * @param refInfoElem - * ReferenceInfo DOM element containing the - * VerifyTransformsInfoProfile DOM elements. - * @return A List of VerifyTransformsInfoProfile - * API objects containing the profile data. - * @throws MOAApplicationException - * An error occurred building the - * VerifyTransformsInfoProfiles. - */ - private List parseVerifyTransformsInfoProfiles(Element refInfoElem) throws MOAApplicationException { - - List profiles = new ArrayList(); - NodeIterator profileElems = XPathUtils.selectNodeIterator(refInfoElem, VERIFY_TRANSFORMS_INFO_PROFILE_XPATH); - Element profileElem; - - while ((profileElem = (Element) profileElems.nextNode()) != null) { - if ("VerifyTransformsInfoProfile".equals(profileElem.getLocalName())) { - ProfileParser profileParser = new ProfileParser(); - profiles.add(profileParser.parseVerifyTransformsInfoProfile(profileElem)); - } else { - String profileID = DOMUtils.getText(profileElem); - profiles.add(factory.createVerifyTransformsInfoProfile(profileID)); - } - } - return profiles; - } + /** + * Parse the VerifySignatureInfo DOM element contained in the + * VerifyXMLSignatureRequest DOM element. + * + * @param requestElem The VerifyXMLSignatureRequest DOM element + * containing the VerifySignatureInfo DOM + * element. + * @return The VerifySignatureInfo API object containing the data + * from the DOM element. + */ + private VerifySignatureInfo parseVerifySignatureInfo(Element requestElem) { + final Element verifySignatureEnvironmentElem = (Element) XPathUtils.selectSingleNode(requestElem, + VERIFY_SIGNATURE_ENVIRONMENT_XPATH); + final Content verifySignatureEnvironment = RequestParserUtils.parseContent( + verifySignatureEnvironmentElem); + final VerifySignatureLocation verifySignatureLocation = parseVerifySignatureLocation(requestElem); + + return factory.createVerifySignatureInfo(verifySignatureEnvironment, verifySignatureLocation); + } + + /** + * Parse the VerifySignatureLocation DOM element contained in the + * given VerifyXMLSignatureRequest DOM element. + * + * @param requestElem The VerifyXMLSignatureRequst DOM element. + * @return The VerifySignatureLocation API object containing the + * data from the DOM element. + */ + private VerifySignatureLocation parseVerifySignatureLocation(Element requestElem) { + final Element locationElem = (Element) XPathUtils.selectSingleNode(requestElem, + VERIFY_SIGNATURE_LOCATION_XPATH); + final String xPathExpression = DOMUtils.getText(locationElem); + final Map namespaceDeclarations = DOMUtils.getNamespaceDeclarations(locationElem); + + return factory.createVerifySignatureLocation(xPathExpression, namespaceDeclarations); + } + + /** + * Parse the supplement profiles contained in the given + * VerifyXMLSignatureRequest DOM element. + * + * @param requestElem The VerifyXMLSignatureRequest DOM element. + * @return A List of SupplementProfile API objects + * containing the data from the SupplementProfile DOM + * elements. + */ + private List parseSupplementProfiles(Element requestElem) { + final List supplementProfiles = new ArrayList(); + final NodeIterator profileElems = XPathUtils.selectNodeIterator(requestElem, SUPPLEMENT_PROFILE_XPATH); + Element profileElem; + + while ((profileElem = (Element) profileElems.nextNode()) != null) { + SupplementProfile profile; + + if ("SupplementProfile".equals(profileElem.getLocalName())) { + final ProfileParser profileParser = new ProfileParser(); + profile = profileParser.parseSupplementProfile(profileElem); + } else { + final String profileID = DOMUtils.getText(profileElem); + profile = factory.createSupplementProfile(profileID); + } + supplementProfiles.add(profile); + } + return supplementProfiles; + } + + /** + * Parse the SignatureManifestCheckParams DOM element contained in + * the given VerifyXMLSignatureRequest DOM element. + * + * @param requestElem The VerifyXMLSignatureRequest DOM element. + * @return The SignatureManifestCheckParams API object containing + * the data from the SignatureManifestCheckParams DOM + * element. + * @throws MOAApplicationException An error occurred parsing the + * SignatureManifestCheckParams DOM + * element. + */ + private SignatureManifestCheckParams parseSignatureManifestCheckParams(Element requestElem) + throws MOAApplicationException { + final Element paramsElem = (Element) XPathUtils.selectSingleNode(requestElem, + SIGNATURE_MANIFEST_CHECK_PARAMS_XPATH); + + if (paramsElem != null) { + final String returnReferenceInputDataStr = paramsElem.getAttribute("ReturnReferenceInputData"); + final boolean returnReferencInputData = BoolUtils.valueOf(returnReferenceInputDataStr); + final List referenceInfos = parseReferenceInfos(paramsElem); + + return factory.createSignatureManifestCheckParams(referenceInfos, returnReferencInputData); + } else { + return null; + } + } + + /** + * Parse the ReferenceInfo DOM elements contained in a + * SignatureManifestCheckParams DOM element. + * + * @param paramsElem The SignatureManifestCheckParams DOM element + * containing the ReferenceInfo DOM elements. + * @return A List of RefernceInfo API objects + * containing the data from the ReferenceInfo DOM elements. + * @throws MOAApplicationException An error occurred parsing the + * ReferenceInfo DOM elements. + */ + private List parseReferenceInfos(Element paramsElem) throws MOAApplicationException { + + final List referenceInfos = new ArrayList(); + final NodeIterator refInfoElems = XPathUtils.selectNodeIterator(paramsElem, REFERENCE_INFO_XPATH); + Element refInfoElem; + + while ((refInfoElem = (Element) refInfoElems.nextNode()) != null) { + final ReferenceInfo referenceInfo = parseReferenceInfo(refInfoElem); + + referenceInfos.add(referenceInfo); + } + + return referenceInfos; + } + + /** + * Parse a ReferenceInfo DOM element. + * + * @param refInfoElem The ReferenceInfo DOM element to parse. + * @return The ReferenceInfo API object containing the data from + * the given ReferenceInfo DOM element. + * @throws MOAApplicationException An error occurred parsing the + * ReferenceInfo DOM element. + */ + private ReferenceInfo parseReferenceInfo(Element refInfoElem) throws MOAApplicationException { + final List profiles = parseVerifyTransformsInfoProfiles(refInfoElem); + return factory.createReferenceInfo(profiles); + } + + /** + * Parse the VerifyTransformsInfoProfile DOM elements contained in + * a ReferenceInfo DOM element. + * + * @param refInfoElem ReferenceInfo DOM element containing the + * VerifyTransformsInfoProfile DOM elements. + * @return A List of VerifyTransformsInfoProfile API + * objects containing the profile data. + * @throws MOAApplicationException An error occurred building the + * VerifyTransformsInfoProfiles. + */ + private List parseVerifyTransformsInfoProfiles(Element refInfoElem) throws MOAApplicationException { + + final List profiles = new ArrayList(); + final NodeIterator profileElems = XPathUtils.selectNodeIterator(refInfoElem, + VERIFY_TRANSFORMS_INFO_PROFILE_XPATH); + Element profileElem; + + while ((profileElem = (Element) profileElems.nextNode()) != null) { + if ("VerifyTransformsInfoProfile".equals(profileElem.getLocalName())) { + final ProfileParser profileParser = new ProfileParser(); + profiles.add(profileParser.parseVerifyTransformsInfoProfile(profileElem)); + } else { + final String profileID = DOMUtils.getText(profileElem); + profiles.add(factory.createVerifyTransformsInfoProfile(profileID)); + } + } + return profiles; + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/VerifyXMLSignatureResponseBuilder.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/VerifyXMLSignatureResponseBuilder.java index 0b73442..48206c9 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/VerifyXMLSignatureResponseBuilder.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlbind/VerifyXMLSignatureResponseBuilder.java @@ -32,10 +32,6 @@ import org.w3c.dom.DocumentFragment; import org.w3c.dom.Element; import org.w3c.dom.NodeList; -import at.gv.egovernment.moaspss.logging.Logger; -import at.gv.egovernment.moaspss.util.Base64Utils; -import at.gv.egovernment.moaspss.util.Constants; -import at.gv.egovernment.moaspss.util.MiscUtil; import at.gv.egovernment.moa.spss.MOAApplicationException; import at.gv.egovernment.moa.spss.MOASystemException; import at.gv.egovernment.moa.spss.api.common.Content; @@ -46,319 +42,315 @@ import at.gv.egovernment.moa.spss.api.xmlverify.AdESFormResults; import at.gv.egovernment.moa.spss.api.xmlverify.ManifestRefsCheckResult; import at.gv.egovernment.moa.spss.api.xmlverify.ReferencesCheckResult; import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureResponse; -import at.gv.egovernment.moa.spss.server.config.ConfigurationException; -import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; +import at.gv.egovernment.moaspss.util.Base64Utils; +import at.gv.egovernment.moaspss.util.Constants; +import at.gv.egovernment.moaspss.util.MiscUtil; /** * Convert a VerifyXMLSignatureResponse API object into its XML * representation, according to the MOA XML schema. - * + * * @author Patrick Peck * @version $Id$ */ public class VerifyXMLSignatureResponseBuilder { - private static final String MOA_NS_URI = Constants.MOA_NS_URI; - - /** The XML document containing the response element. */ - private Document responseDoc; - /** The response VerifyXMLSignatureResponse DOM element. */ - private Element responseElem; - - private boolean includeSigningTime = false; - /** - * Create a new VerifyXMLSignatureResponseBuilder: - * - * @throws MOASystemException - * An error occurred setting up the resulting XML document. - */ - public VerifyXMLSignatureResponseBuilder() throws MOASystemException { - responseDoc = ResponseBuilderUtils.createResponse("VerifyXMLSignatureResponse"); - responseElem = responseDoc.getDocumentElement(); - } - - public VerifyXMLSignatureResponseBuilder(boolean includeSigningTime) throws MOASystemException { - responseDoc = ResponseBuilderUtils.createResponse("VerifyXMLSignatureResponse"); - responseElem = responseDoc.getDocumentElement(); - this.includeSigningTime = includeSigningTime; - } - - public VerifyXMLSignatureResponseBuilder(Document responseDoc, String name, boolean includeSigningTime) throws MOASystemException { - this.responseDoc = responseDoc; - responseElem = responseDoc.createElementNS(MOA_NS_URI, name); - this.includeSigningTime = includeSigningTime; - } - - public Element buildElement(VerifyXMLSignatureResponse response) throws MOAApplicationException { - this.build(response); - return responseElem; - } - - /** - * Build a document containing a VerifyXMLSignatureResponse DOM - * element being the XML representation of the given - * VerifyXMLSignatureResponse API object. - * - * @param response - * The VerifyXMLSignatureResponse to convert to XML. - * @return A document containing the VerifyXMLSignatureResponse - * DOM element. - * @throws MOAApplicationException - * An error occurred building the response. - */ - public Document build(VerifyXMLSignatureResponse response) throws MOAApplicationException { - - Iterator iter; - List responseData; - - // add the SignerInfo - ResponseBuilderUtils.addSignerInfo(responseDoc, responseElem, response.getSignerInfo().getSignerCertificate(), - response.getSignerInfo().isQualifiedCertificate(), response.getSignerInfo().getQCSource(), - response.getSignerInfo().isPublicAuthority(), response.getSignerInfo().getPublicAuhtorityID(), - response.getSignerInfo().isSSCD(), response.getSignerInfo().getSSCDSource(), - response.getSignerInfo().getIssuerCountryCode(), - response.getSignerInfo().getTslInfos()); - - if(this.includeSigningTime) { - ResponseBuilderUtils.addSigningTime(responseDoc, - responseElem, response.getSignerInfo().getSigningTime()); - } - - // add HashInputData elements - responseData = response.getHashInputDatas(); - if (responseData != null && !responseData.isEmpty()) { - for (iter = responseData.iterator(); iter.hasNext();) { - InputData inputData = (InputData) iter.next(); - addContent("HashInputData", inputData); - } - } - - // add ReferenceInputData elements - responseData = response.getReferenceInputDatas(); - if (responseData != null && !responseData.isEmpty()) { - for (iter = responseData.iterator(); iter.hasNext();) { - InputData inputData = (InputData) iter.next(); - addContent("ReferenceInputData", inputData); - } - } - - //add hash algorithm - ResponseBuilderUtils.addSignatureAlgorithm(responseDoc, responseElem, response.getSignatureAlgorithm()); - - // add the SignatureCheck - addReferencesCheckResult("SignatureCheck", response.getSignatureCheck()); - - // add the SignatureManifestCheck - if (response.getSignatureManifestCheck() != null) { - addReferencesCheckResult("SignatureManifestCheck", response.getSignatureManifestCheck()); - } - - // add the XMLDsigManifestChecks - responseData = response.getXMLDsigManifestChecks(); - if (responseData != null && !responseData.isEmpty()) { - for (iter = responseData.iterator(); iter.hasNext();) { - ManifestRefsCheckResult checkResult = (ManifestRefsCheckResult) iter.next(); - addManifestRefsCheckResult("XMLDSIGManifestCheck", checkResult); - } - } - - // add the CertificateCheck - ResponseBuilderUtils.addCodeInfoElement(responseDoc, responseElem, "CertificateCheck", - response.getCertificateCheck().getCode(), response.getCertificateCheck().getInfo()); - - if (response.getAdESFormResults() != null) { - - Iterator formIterator = response.getAdESFormResults().iterator(); - - while (formIterator.hasNext()) { - AdESFormResults adESFormResult = (AdESFormResults) formIterator.next(); - // add the CertificateCheck - ResponseBuilderUtils.addFormCheckElement(responseDoc, responseElem, "FormCheckResult", - adESFormResult.getCode().intValue(), adESFormResult.getName()); - - } - } - - if(response.getExtendedCertificateCheck() != null) { - ResponseBuilderUtils.addExtendendResult(responseDoc, responseElem, response.getExtendedCertificateCheck()); - } - - return responseDoc; - } - - /** - * Add an element of type ContentBaseType to the response. - * - * @param elementName - * The name of the element. - * - * @param inputData - * The InputData to add. Based on the type of - * - * the InputData, either a - * Base64Content element or a - * XMLContent subelement will be added. An - * InputDataBinaryImpl will be added as a Base64Content - * child element. AnInputDataXMLImpl will be added - * as - * XMLContent child element. - * - * @throws MOAApplicationException - * An error occurred adding the content. - */ - private void addContent(String elementName, InputData inputData) throws MOAApplicationException { - - Element contentElem = responseDoc.createElementNS(MOA_NS_URI, elementName); - - contentElem.setAttributeNS(null, "PartOf", inputData.getPartOf()); - if (inputData.getReferringReferenceNumber() != InputData.REFERER_NONE_) - contentElem.setAttributeNS(null, "ReferringSigReference", - Integer.toString(inputData.getReferringReferenceNumber())); - - if (MiscUtil.isNotEmpty(inputData.getHashAlgorithm())) { - contentElem.setAttribute("HashAlgorithm", inputData.getHashAlgorithm()); - - } - - switch (inputData.getContentType()) { - case Content.XML_CONTENT: - ContentXML contentXml = (ContentXML) inputData; - NodeList nodes = contentXml.getXMLContent(); - Element xmlElem; - int i; - - xmlElem = responseDoc.createElementNS(MOA_NS_URI, "XMLContent"); - // xmlElem.setAttributeNS(XML_NS_URI, "xml:space", "preserve"); - xmlElem.setAttribute("xml:space", "preserve"); - - for (i = 0; i < nodes.getLength(); i++) { - xmlElem.appendChild(responseDoc.importNode(nodes.item(i), true)); - } - contentElem.appendChild(xmlElem); - responseElem.appendChild(contentElem); - break; - case Content.BINARY_CONTENT: - Element binaryElem = responseDoc.createElementNS(MOA_NS_URI, "Base64Content"); - ContentBinary contentBinary = (ContentBinary) inputData; - String base64Str; - - try { - base64Str = Base64Utils.encode(contentBinary.getBinaryContent()); - } catch (IOException e) { - throw new MOAApplicationException("2200", null, e); - } - binaryElem.appendChild(responseDoc.createTextNode(base64Str)); - contentElem.appendChild(binaryElem); - responseElem.appendChild(contentElem); - break; - } - - } - - /** - * Add a ReferencesCheckResult to the response. - * - * @param elementName - * The DOM element name to use. - * @param checkResult - * The ReferencesCheckResult to add. - */ - private void addReferencesCheckResult(String elementName, ReferencesCheckResult checkResult) { - - NodeList info = null; - - if (checkResult.getInfo() != null) { - DocumentFragment fragment = responseDoc.createDocumentFragment(); - NodeList anyOtherInfo = checkResult.getInfo().getAnyOtherInfo(); - int[] failedReferences = checkResult.getInfo().getFailedReferences(); - - if (anyOtherInfo != null) { - addAnyOtherInfo(fragment, checkResult.getInfo().getAnyOtherInfo()); - } - - if (failedReferences != null) { - addFailedReferences(fragment, failedReferences); - } - - info = fragment.getChildNodes(); - } - - ResponseBuilderUtils.addCodeInfoElement(responseDoc, responseElem, elementName, checkResult.getCode(), info); - - } - - /** - * Add a ManifestRefsCheckResult to the response. - * - * @param elementName - * The DOM element name to use. - * @param checkResult - * The ManifestRefsCheckResult to add. - */ - private void addManifestRefsCheckResult(String elementName, ManifestRefsCheckResult checkResult) { - - DocumentFragment fragment = responseDoc.createDocumentFragment(); - NodeList anyOtherInfo = checkResult.getInfo().getAnyOtherInfo(); - int[] failedReferences = checkResult.getInfo().getFailedReferences(); - Element referringSigRefElem; - String referringSigRefStr; - - // add any other elements - if (anyOtherInfo != null) { - addAnyOtherInfo(fragment, checkResult.getInfo().getAnyOtherInfo()); - } - - // add the failed references - if (failedReferences != null) { - addFailedReferences(fragment, failedReferences); - } - - // add the ReferringSigReference - referringSigRefElem = responseDoc.createElementNS(MOA_NS_URI, "ReferringSigReference"); - referringSigRefStr = Integer.toString(checkResult.getInfo().getReferringSignatureReference()); - referringSigRefElem.appendChild(responseDoc.createTextNode(referringSigRefStr)); - fragment.appendChild(referringSigRefElem); - - // add XMLDSIGManifestCheckResult to the response - ResponseBuilderUtils.addCodeInfoElement(responseDoc, responseElem, elementName, checkResult.getCode(), - fragment.getChildNodes()); - } - - /** - * Add arbitrary XML content to a DOM DocumentFragment. - * - * @param fragment - * The fragment to add the XML content to. - * @param anyOtherInfo - * The XML content to add. - */ - private void addAnyOtherInfo(DocumentFragment fragment, NodeList anyOtherInfo) { - - int i; - - for (i = 0; i < anyOtherInfo.getLength(); i++) { - fragment.appendChild(responseDoc.importNode(anyOtherInfo.item(i), true)); - } - } - - /** - * Add the failed references as FailedReference DOM elements to - * the fragment. - * - * @param fragment - * The DOM document fragment to add the - * FailedReference elements to. - * @param failedReferences - * The indexes of the failed references. - */ - private void addFailedReferences(DocumentFragment fragment, int[] failedReferences) { - Element failedReferenceElem; - int i; - - for (i = 0; i < failedReferences.length; i++) { - failedReferenceElem = responseDoc.createElementNS(MOA_NS_URI, "FailedReference"); - failedReferenceElem.appendChild(responseDoc.createTextNode(Integer.toString(failedReferences[i]))); - fragment.appendChild(failedReferenceElem); - } - } + private static final String MOA_NS_URI = Constants.MOA_NS_URI; + + /** The XML document containing the response element. */ + private final Document responseDoc; + /** The response VerifyXMLSignatureResponse DOM element. */ + private final Element responseElem; + + private boolean includeSigningTime = false; + + /** + * Create a new VerifyXMLSignatureResponseBuilder: + * + * @throws MOASystemException An error occurred setting up the resulting XML + * document. + */ + public VerifyXMLSignatureResponseBuilder() throws MOASystemException { + responseDoc = ResponseBuilderUtils.createResponse("VerifyXMLSignatureResponse"); + responseElem = responseDoc.getDocumentElement(); + } + + public VerifyXMLSignatureResponseBuilder(boolean includeSigningTime) throws MOASystemException { + responseDoc = ResponseBuilderUtils.createResponse("VerifyXMLSignatureResponse"); + responseElem = responseDoc.getDocumentElement(); + this.includeSigningTime = includeSigningTime; + } + + public VerifyXMLSignatureResponseBuilder(Document responseDoc, String name, boolean includeSigningTime) + throws MOASystemException { + this.responseDoc = responseDoc; + responseElem = responseDoc.createElementNS(MOA_NS_URI, name); + this.includeSigningTime = includeSigningTime; + } + + public Element buildElement(VerifyXMLSignatureResponse response) throws MOAApplicationException { + this.build(response); + return responseElem; + } + + /** + * Build a document containing a VerifyXMLSignatureResponse DOM + * element being the XML representation of the given + * VerifyXMLSignatureResponse API object. + * + * @param response The VerifyXMLSignatureResponse to convert to + * XML. + * @return A document containing the VerifyXMLSignatureResponse DOM + * element. + * @throws MOAApplicationException An error occurred building the response. + */ + public Document build(VerifyXMLSignatureResponse response) throws MOAApplicationException { + + Iterator iter; + List responseData; + + // add the SignerInfo + ResponseBuilderUtils.addSignerInfo(responseDoc, responseElem, response.getSignerInfo() + .getSignerCertificate(), + response.getSignerInfo().isQualifiedCertificate(), response.getSignerInfo().getQCSource(), + response.getSignerInfo().isPublicAuthority(), response.getSignerInfo().getPublicAuhtorityID(), + response.getSignerInfo().isSSCD(), response.getSignerInfo().getSSCDSource(), + response.getSignerInfo().getIssuerCountryCode(), + response.getSignerInfo().getTslInfos()); + + if (this.includeSigningTime) { + ResponseBuilderUtils.addSigningTime(responseDoc, + responseElem, response.getSignerInfo().getSigningTime()); + } + + // add HashInputData elements + responseData = response.getHashInputDatas(); + if (responseData != null && !responseData.isEmpty()) { + for (iter = responseData.iterator(); iter.hasNext();) { + final InputData inputData = (InputData) iter.next(); + addContent("HashInputData", inputData); + } + } + + // add ReferenceInputData elements + responseData = response.getReferenceInputDatas(); + if (responseData != null && !responseData.isEmpty()) { + for (iter = responseData.iterator(); iter.hasNext();) { + final InputData inputData = (InputData) iter.next(); + addContent("ReferenceInputData", inputData); + } + } + + // add hash algorithm + ResponseBuilderUtils.addSignatureAlgorithm(responseDoc, responseElem, response.getSignatureAlgorithm()); + + // add the SignatureCheck + addReferencesCheckResult("SignatureCheck", response.getSignatureCheck()); + + // add the SignatureManifestCheck + if (response.getSignatureManifestCheck() != null) { + addReferencesCheckResult("SignatureManifestCheck", response.getSignatureManifestCheck()); + } + + // add the XMLDsigManifestChecks + responseData = response.getXMLDsigManifestChecks(); + if (responseData != null && !responseData.isEmpty()) { + for (iter = responseData.iterator(); iter.hasNext();) { + final ManifestRefsCheckResult checkResult = (ManifestRefsCheckResult) iter.next(); + addManifestRefsCheckResult("XMLDSIGManifestCheck", checkResult); + } + } + + // add the CertificateCheck + ResponseBuilderUtils.addCodeInfoElement(responseDoc, responseElem, "CertificateCheck", + response.getCertificateCheck().getCode(), response.getCertificateCheck().getInfo()); + + if (response.getAdESFormResults() != null) { + + final Iterator formIterator = response.getAdESFormResults().iterator(); + + while (formIterator.hasNext()) { + final AdESFormResults adESFormResult = (AdESFormResults) formIterator.next(); + // add the CertificateCheck + ResponseBuilderUtils.addFormCheckElement(responseDoc, responseElem, "FormCheckResult", + adESFormResult.getCode().intValue(), adESFormResult.getName()); + + } + } + + if (response.getExtendedCertificateCheck() != null) { + ResponseBuilderUtils.addExtendendResult(responseDoc, responseElem, response + .getExtendedCertificateCheck()); + } + + return responseDoc; + } + + /** + * Add an element of type ContentBaseType to the response. + * + * @param elementName The name of the element. + * + * @param inputData The InputData to add. Based on the type of + * + * the InputData, either a + * Base64Content element or a + * XMLContent subelement will be added. An + * + * InputDataBinaryImpl will be added as a Base64Content + * child element. AnInputDataXMLImpl will be + * added as + * XMLContent child element. + * + * @throws MOAApplicationException An error occurred adding the content. + */ + private void addContent(String elementName, InputData inputData) throws MOAApplicationException { + + final Element contentElem = responseDoc.createElementNS(MOA_NS_URI, elementName); + + contentElem.setAttributeNS(null, "PartOf", inputData.getPartOf()); + if (inputData.getReferringReferenceNumber() != InputData.REFERER_NONE_) { + contentElem.setAttributeNS(null, "ReferringSigReference", + Integer.toString(inputData.getReferringReferenceNumber())); + } + + if (MiscUtil.isNotEmpty(inputData.getHashAlgorithm())) { + contentElem.setAttribute("HashAlgorithm", inputData.getHashAlgorithm()); + + } + + switch (inputData.getContentType()) { + case Content.XML_CONTENT: + final ContentXML contentXml = (ContentXML) inputData; + final NodeList nodes = contentXml.getXMLContent(); + Element xmlElem; + int i; + + xmlElem = responseDoc.createElementNS(MOA_NS_URI, "XMLContent"); + // xmlElem.setAttributeNS(XML_NS_URI, "xml:space", "preserve"); + xmlElem.setAttribute("xml:space", "preserve"); + + for (i = 0; i < nodes.getLength(); i++) { + xmlElem.appendChild(responseDoc.importNode(nodes.item(i), true)); + } + contentElem.appendChild(xmlElem); + responseElem.appendChild(contentElem); + break; + case Content.BINARY_CONTENT: + final Element binaryElem = responseDoc.createElementNS(MOA_NS_URI, "Base64Content"); + final ContentBinary contentBinary = (ContentBinary) inputData; + String base64Str; + + try { + base64Str = Base64Utils.encode(contentBinary.getBinaryContent()); + } catch (final IOException e) { + throw new MOAApplicationException("2200", null, e); + } + binaryElem.appendChild(responseDoc.createTextNode(base64Str)); + contentElem.appendChild(binaryElem); + responseElem.appendChild(contentElem); + break; + } + + } + + /** + * Add a ReferencesCheckResult to the response. + * + * @param elementName The DOM element name to use. + * @param checkResult The ReferencesCheckResult to add. + */ + private void addReferencesCheckResult(String elementName, ReferencesCheckResult checkResult) { + + NodeList info = null; + + if (checkResult.getInfo() != null) { + final DocumentFragment fragment = responseDoc.createDocumentFragment(); + final NodeList anyOtherInfo = checkResult.getInfo().getAnyOtherInfo(); + final int[] failedReferences = checkResult.getInfo().getFailedReferences(); + + if (anyOtherInfo != null) { + addAnyOtherInfo(fragment, checkResult.getInfo().getAnyOtherInfo()); + } + + if (failedReferences != null) { + addFailedReferences(fragment, failedReferences); + } + + info = fragment.getChildNodes(); + } + + ResponseBuilderUtils.addCodeInfoElement(responseDoc, responseElem, elementName, checkResult.getCode(), + info); + + } + + /** + * Add a ManifestRefsCheckResult to the response. + * + * @param elementName The DOM element name to use. + * @param checkResult The ManifestRefsCheckResult to add. + */ + private void addManifestRefsCheckResult(String elementName, ManifestRefsCheckResult checkResult) { + + final DocumentFragment fragment = responseDoc.createDocumentFragment(); + final NodeList anyOtherInfo = checkResult.getInfo().getAnyOtherInfo(); + final int[] failedReferences = checkResult.getInfo().getFailedReferences(); + Element referringSigRefElem; + String referringSigRefStr; + + // add any other elements + if (anyOtherInfo != null) { + addAnyOtherInfo(fragment, checkResult.getInfo().getAnyOtherInfo()); + } + + // add the failed references + if (failedReferences != null) { + addFailedReferences(fragment, failedReferences); + } + + // add the ReferringSigReference + referringSigRefElem = responseDoc.createElementNS(MOA_NS_URI, "ReferringSigReference"); + referringSigRefStr = Integer.toString(checkResult.getInfo().getReferringSignatureReference()); + referringSigRefElem.appendChild(responseDoc.createTextNode(referringSigRefStr)); + fragment.appendChild(referringSigRefElem); + + // add XMLDSIGManifestCheckResult to the response + ResponseBuilderUtils.addCodeInfoElement(responseDoc, responseElem, elementName, checkResult.getCode(), + fragment.getChildNodes()); + } + + /** + * Add arbitrary XML content to a DOM DocumentFragment. + * + * @param fragment The fragment to add the XML content to. + * @param anyOtherInfo The XML content to add. + */ + private void addAnyOtherInfo(DocumentFragment fragment, NodeList anyOtherInfo) { + + int i; + + for (i = 0; i < anyOtherInfo.getLength(); i++) { + fragment.appendChild(responseDoc.importNode(anyOtherInfo.item(i), true)); + } + } + + /** + * Add the failed references as FailedReference DOM elements to the + * fragment. + * + * @param fragment The DOM document fragment to add the + * FailedReference elements to. + * @param failedReferences The indexes of the failed references. + */ + private void addFailedReferences(DocumentFragment fragment, int[] failedReferences) { + Element failedReferenceElem; + int i; + + for (i = 0; i < failedReferences.length; i++) { + failedReferenceElem = responseDoc.createElementNS(MOA_NS_URI, "FailedReference"); + failedReferenceElem.appendChild(responseDoc.createTextNode(Integer.toString(failedReferences[i]))); + fragment.appendChild(failedReferenceElem); + } + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateSignatureEnvironmentProfile.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateSignatureEnvironmentProfile.java index 4b40b9c..3b98dc4 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateSignatureEnvironmentProfile.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateSignatureEnvironmentProfile.java @@ -21,13 +21,12 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlsign; /** - * Base class for signature environment profile data used in XML signature + * Base class for signature environment profile data used in XML signature * creation. - * + * * @author Patrick Peck * @version $Id$ */ @@ -35,20 +34,20 @@ public interface CreateSignatureEnvironmentProfile { /** * Indicates that the profile data is given explicitly. */ - public static int EXPLICIT_CREATESIGNATUREENVIRONMENTPROFILE = 0; + int EXPLICIT_CREATESIGNATUREENVIRONMENTPROFILE = 0; /** - * Indicates that the profile data is stored in the configuration and resolved + * Indicates that the profile data is stored in the configuration and resolved * using an ID. */ - public static int ID_CREATESIGNATUREENVIRONMENTPROFILE = 1; - + int ID_CREATESIGNATUREENVIRONMENTPROFILE = 1; + /** * Gets the type of this object. - * - * @return The type of CreateSignatureEnvironmentProfile denoted - * by this object. Either - * EXPLICIT_CREATESIGNATUREENVIRONMENTPROFILE or - * ID_CREATESIGNATUREENVIRONMENTPROFILE. + * + * @return The type of CreateSignatureEnvironmentProfile denoted by + * this object. Either + * EXPLICIT_CREATESIGNATUREENVIRONMENTPROFILE or + * ID_CREATESIGNATUREENVIRONMENTPROFILE. */ - public int getCreateSignatureEnvironmentProfileType(); + int getCreateSignatureEnvironmentProfileType(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateSignatureEnvironmentProfileExplicit.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateSignatureEnvironmentProfileExplicit.java index 0bce94c..5f761f1 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateSignatureEnvironmentProfileExplicit.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateSignatureEnvironmentProfileExplicit.java @@ -21,34 +21,33 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlsign; import java.util.List; /** - * A CreateSignatureEnvironmentProfile containing the profile - * data explicitly. - * + * A CreateSignatureEnvironmentProfile containing the profile data + * explicitly. + * * @author Patrick Peck * @version $Id$ */ public interface CreateSignatureEnvironmentProfileExplicit - extends CreateSignatureEnvironmentProfile { - + extends CreateSignatureEnvironmentProfile { + /** * Gets the location and index of where to insert the signature into the * signature environment. - * - * @return The location and index of the signature in the signature - * environment. + * + * @return The location and index of the signature in the signature environment. */ - public CreateSignatureLocation getCreateSignatureLocation(); + CreateSignatureLocation getCreateSignatureLocation(); + /** * Gets the supplemental information. - * + * * @return The supplemental information. */ - public List getSupplements(); + List getSupplements(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateSignatureEnvironmentProfileID.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateSignatureEnvironmentProfileID.java index 73e4f52..8066d37 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateSignatureEnvironmentProfileID.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateSignatureEnvironmentProfileID.java @@ -21,24 +21,23 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlsign; /** * A CreateSignatureEnvironmentProfile containing a profile ID * pointing to locally stored profile data. - * + * * @author Patrick Peck * @version $Id$ */ public interface CreateSignatureEnvironmentProfileID - extends CreateSignatureEnvironmentProfile { + extends CreateSignatureEnvironmentProfile { /** * Gets the profile ID. - * + * * @return The profile ID. */ - public String getCreateSignatureEnvironmentProfileID(); - + String getCreateSignatureEnvironmentProfileID(); + } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateSignatureInfo.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateSignatureInfo.java index 9363408..e26ca1e 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateSignatureInfo.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateSignatureInfo.java @@ -21,14 +21,13 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlsign; import at.gv.egovernment.moa.spss.api.common.Content; /** * Encapsulates a signature object used during signature creation. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -39,11 +38,12 @@ public interface CreateSignatureInfo { * * @return The XML structure where the signature will be inserted. */ - public Content getCreateSignatureEnvironment(); + Content getCreateSignatureEnvironment(); + /** * Gets the supplemental data for the signature environment. * * @return The supplemental data for the signature envoronment. */ - public CreateSignatureEnvironmentProfile getCreateSignatureEnvironmentProfile(); + CreateSignatureEnvironmentProfile getCreateSignatureEnvironmentProfile(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateSignatureLocation.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateSignatureLocation.java index 9a0b798..39a85b4 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateSignatureLocation.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateSignatureLocation.java @@ -21,18 +21,17 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlsign; import at.gv.egovernment.moa.spss.api.common.ElementSelector; /** * Specifies where to insert the newly created signature. - * + * * An XPath expression is used to select the signature parent element. An - * additional index specifies the node index after which to insert the - * signature into the parent element. - * + * additional index specifies the node index after which to insert the signature + * into the parent element. + * * @author Patrick Peck * @version $Id$ */ @@ -40,8 +39,8 @@ public interface CreateSignatureLocation extends ElementSelector { /** * Gets the node index, after which the signature will be inserted into the * parent elemen. - * + * * @return The index of the node after which the signature will be inserted. */ - public int getIndex(); + int getIndex(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateTransformsInfo.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateTransformsInfo.java index fbb0000..1793365 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateTransformsInfo.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateTransformsInfo.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlsign; import java.util.List; @@ -30,7 +29,7 @@ import at.gv.egovernment.moa.spss.api.common.MetaInfo; /** * Encapsulates information used for the transformation of the data object. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -38,14 +37,15 @@ import at.gv.egovernment.moa.spss.api.common.MetaInfo; public interface CreateTransformsInfo { /** * Gets the XMLDSig transforms. - * + * * @return A List of Transform objects. */ - public List getTransforms(); + List getTransforms(); + /** * Gets meta information about the data resulting from the transformation. - * + * * @return Meta information about the resulting data. */ - public MetaInfo getFinalDataMetaInfo(); + MetaInfo getFinalDataMetaInfo(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateTransformsInfoProfile.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateTransformsInfoProfile.java index 5babdae..9832972 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateTransformsInfoProfile.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateTransformsInfoProfile.java @@ -21,12 +21,11 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlsign; /** * Base class for transformation informations used in signature creation. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -35,18 +34,18 @@ public interface CreateTransformsInfoProfile { /** * Indicates transformation information given explicitly. */ - public static final int EXPLICIT_CREATETRANSFORMSINFOPROFILE = 0; + int EXPLICIT_CREATETRANSFORMSINFOPROFILE = 0; /** * Indicates transformation information given as an ID. */ - public static final int ID_CREATETRANSFORMSINFOPROFILE = 1; - + int ID_CREATETRANSFORMSINFOPROFILE = 1; + /** * Gets the type of profile information this object contains. - * + * * @return The type of transformation information, either - * EXPLICIT_CREATETRANSFORMSINFOPROFILE or - * ID_CREATETRANSFORMSINFOPROFILE. + * EXPLICIT_CREATETRANSFORMSINFOPROFILE or + * ID_CREATETRANSFORMSINFOPROFILE. */ - public int getCreateTransformsInfoProfileType(); + int getCreateTransformsInfoProfileType(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateTransformsInfoProfileExplicit.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateTransformsInfoProfileExplicit.java index 9aae8cb..39580d6 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateTransformsInfoProfileExplicit.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateTransformsInfoProfileExplicit.java @@ -21,30 +21,30 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlsign; import java.util.List; /** * Encapsulates explicit transformation informations. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ */ public interface CreateTransformsInfoProfileExplicit - extends CreateTransformsInfoProfile { + extends CreateTransformsInfoProfile { /** * Gets the transformation information of the data object. - * + * * @return Transformation information of the data object. */ - public CreateTransformsInfo getCreateTransformsInfo(); + CreateTransformsInfo getCreateTransformsInfo(); + /** * Gets the supplemental information. - * + * * @return The supplemental information. */ - public List getSupplements(); + List getSupplements(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateTransformsInfoProfileID.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateTransformsInfoProfileID.java index 69c3629..fc9d869 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateTransformsInfoProfileID.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateTransformsInfoProfileID.java @@ -21,22 +21,21 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlsign; /** * Encapsulates transformation information given via an identifier. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ */ public interface CreateTransformsInfoProfileID - extends CreateTransformsInfoProfile { + extends CreateTransformsInfoProfile { /** * Gets the ID of the transformation. - * + * * @return The transformation profile ID. */ - public String getCreateTransformsInfoProfileID(); + String getCreateTransformsInfoProfileID(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateXMLSignatureRequest.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateXMLSignatureRequest.java index 351b16e..0f8c8a2 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateXMLSignatureRequest.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateXMLSignatureRequest.java @@ -21,15 +21,13 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlsign; import java.util.List; - /** * Object that encapsulates a request to create an XML Signature. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -37,14 +35,15 @@ import java.util.List; public interface CreateXMLSignatureRequest { /** * Gets the identifier for the keys to be used for the signature. - * + * * @return The identifier for the keys to be used. */ - public String getKeyIdentifier(); + String getKeyIdentifier(); + /** - * Gets the information of the singleSignatureInfo elements. - * + * Gets the information of the singleSignatureInfo elements. + * * @return The information of singleSignatureInfo elements. */ - public List getSingleSignatureInfos(); + List getSingleSignatureInfos(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateXMLSignatureResponse.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateXMLSignatureResponse.java index c1b1c30..1b59d7d 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateXMLSignatureResponse.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateXMLSignatureResponse.java @@ -21,15 +21,14 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlsign; import java.util.List; /** - * Object that encapsulates the response on to a + * Object that encapsulates the response on to a * CreateXMLSignatureRequest to create an XML signature. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -37,8 +36,8 @@ import java.util.List; public interface CreateXMLSignatureResponse { /** * Gets the response elements. - * + * * @return The response elements. */ - public List getResponseElements(); + List getResponseElements(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateXMLSignatureResponseElement.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateXMLSignatureResponseElement.java index b9bd334..fe6cbbb 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateXMLSignatureResponseElement.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/CreateXMLSignatureResponseElement.java @@ -21,14 +21,13 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlsign; /** - * Base class for SignatureEnvironmentResponse and - * ErrorResponse elements in a + * Base class for SignatureEnvironmentResponse and + * ErrorResponse elements in a * CreateXMLSignatureResponse. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -37,17 +36,18 @@ public interface CreateXMLSignatureResponseElement { /** * Indicates that this object contains a SignatureEnvironment. */ - public static final int SIGNATURE_ENVIRONMENT_RESPONSE = 0; + int SIGNATURE_ENVIRONMENT_RESPONSE = 0; /** * Indicates that this objet contains an ErrorResponse. */ - public static final int ERROR_RESPONSE = 1; - + int ERROR_RESPONSE = 1; + /** * Gets the type of response object. - * - * @return The type of response object, either - * SIGNATURE_ENVIRONMENT_RESPONSE or ERROR_RESPONSE. + * + * @return The type of response object, either + * SIGNATURE_ENVIRONMENT_RESPONSE or + * ERROR_RESPONSE. */ - public int getResponseType(); + int getResponseType(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/DataObjectInfo.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/DataObjectInfo.java index 620e3b3..053ff00 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/DataObjectInfo.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/DataObjectInfo.java @@ -21,14 +21,13 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlsign; import at.gv.egovernment.moa.spss.api.common.Content; /** * Encapsulates information required to create a single signature. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -37,36 +36,39 @@ public interface DataObjectInfo { /** * Indicates that a detached signature will be created. */ - public static final String STRUCTURE_DETACHED = "detached"; + String STRUCTURE_DETACHED = "detached"; /** * Indicates that an enveloping signature will be created. */ - public static final String STRUCTURE_ENVELOPING = "enveloping"; + String STRUCTURE_ENVELOPING = "enveloping"; /** * Gets the structure of the signature. - * + * * @return The structure of the signature. */ - public String getStructure(); + String getStructure(); + /** - * Checks whether a refercence will be placed in the signature itself or - * in the manifest. - * + * Checks whether a refercence will be placed in the signature itself or in the + * manifest. + * * @return true if a reference will be placed in the manifest, - * false if it will be placed in the signature. + * false if it will be placed in the signature. */ - public boolean isChildOfManifest(); + boolean isChildOfManifest(); + /** * Gets information related to a single data object. - * + * * @return Information related to a single data object. */ - public Content getDataObject(); + Content getDataObject(); + /** * Gets information for the transformation of the data object. - * + * * @return The transformation information. */ - public CreateTransformsInfoProfile getCreateTransformsInfoProfile(); + CreateTransformsInfoProfile getCreateTransformsInfoProfile(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/ErrorResponse.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/ErrorResponse.java index 6dfa843..d1b838d 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/ErrorResponse.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/ErrorResponse.java @@ -21,13 +21,11 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlsign; - /** * Object containing detailed error information. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -35,14 +33,15 @@ package at.gv.egovernment.moa.spss.api.xmlsign; public interface ErrorResponse extends CreateXMLSignatureResponseElement { /** * Gets the error code. - * + * * @return The error code. */ - public int getErrorCode(); + int getErrorCode(); + /** * Gets verbose error information. - * + * * @return Verbose error information. */ - public String getInfo(); + String getInfo(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/SignatureEnvironmentResponse.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/SignatureEnvironmentResponse.java index 47c4ce7..ecf57ce 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/SignatureEnvironmentResponse.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/SignatureEnvironmentResponse.java @@ -21,24 +21,23 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlsign; import org.w3c.dom.Element; /** * Contains the signature if the signature creation was successful. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ */ public interface SignatureEnvironmentResponse - extends CreateXMLSignatureResponseElement { - /** + extends CreateXMLSignatureResponseElement { + /** * Gets the XML structure which contains the signature. - * + * * @return A general XML structure containing the signature. */ - public Element getSignatureEnvironment(); + Element getSignatureEnvironment(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/SingleSignatureInfo.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/SingleSignatureInfo.java index 3355739..7b94bc0 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/SingleSignatureInfo.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlsign/SingleSignatureInfo.java @@ -21,14 +21,13 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlsign; import java.util.List; /** * Encapsulates data to create a single signature. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -36,21 +35,23 @@ import java.util.List; public interface SingleSignatureInfo { /** * Gets the dataObjectInfo information. - * + * * @return The dataObjectInfo information. */ - public List getDataObjectInfos(); + List getDataObjectInfos(); + /** * Gets the signature object. - * + * * @return The signature object used during signature creation. */ - public CreateSignatureInfo getCreateSignatureInfo(); + CreateSignatureInfo getCreateSignatureInfo(); + /** * Check whether a Security Layer conform signature manifest will be created. - * - * @return true, if a Security Layer conform signature manifest - * will be created, false otherwise. + * + * @return true, if a Security Layer conform signature manifest + * will be created, false otherwise. */ - public boolean isSecurityLayerConform(); + boolean isSecurityLayerConform(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/AdESFormResults.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/AdESFormResults.java index e12c39b..2730c18 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/AdESFormResults.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/AdESFormResults.java @@ -1,7 +1,9 @@ package at.gv.egovernment.moa.spss.api.xmlverify; public interface AdESFormResults { - public Integer getCode(); - public String getInfo(); - public String getName(); + Integer getCode(); + + String getInfo(); + + String getName(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/ManifestRefsCheckResult.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/ManifestRefsCheckResult.java index 8ff4617..6e5aeda 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/ManifestRefsCheckResult.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/ManifestRefsCheckResult.java @@ -21,13 +21,11 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlverify; - /** * Contains the results of manifest checks according to XMLDsig. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -35,14 +33,15 @@ package at.gv.egovernment.moa.spss.api.xmlverify; public interface ManifestRefsCheckResult { /** * Gets the check code. - * + * * @return A numerical representation of the result of the manifest check. */ - public int getCode(); + int getCode(); + /** * Gets the reference to the manifest. - * + * * @return The reference to the manifest. */ - public ManifestRefsCheckResultInfo getInfo(); + ManifestRefsCheckResultInfo getInfo(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/ManifestRefsCheckResultInfo.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/ManifestRefsCheckResultInfo.java index 4b0a4fb..f8973b2 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/ManifestRefsCheckResultInfo.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/ManifestRefsCheckResultInfo.java @@ -21,23 +21,21 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlverify; - /** * Encapsulates information referring to the manifest of the check. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ */ public interface ManifestRefsCheckResultInfo extends ReferencesCheckResultInfo { /** - * Gets the position of the signature reference containing the - * reference to the manifest being described by this object. - * + * Gets the position of the signature reference containing the reference to the + * manifest being described by this object. + * * @return The position of the signature reference. */ - public int getReferringSignatureReference(); + int getReferringSignatureReference(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/ReferenceInfo.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/ReferenceInfo.java index 95a2b92..40bfe48 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/ReferenceInfo.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/ReferenceInfo.java @@ -21,14 +21,13 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlverify; import java.util.List; /** * Contains transformation parameters which are locally available. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -36,8 +35,8 @@ import java.util.List; public interface ReferenceInfo { /** * Gets the transformation info. - * + * * @return The transformation info. */ - public List getVerifyTransformsInfoProfiles(); + List getVerifyTransformsInfoProfiles(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/ReferencesCheckResult.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/ReferencesCheckResult.java index dd1f482..bf41109 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/ReferencesCheckResult.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/ReferencesCheckResult.java @@ -21,27 +21,27 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlverify; /** - * Contains information about the verification status of references contained - * in the signature. - * + * Contains information about the verification status of references contained in + * the signature. + * * @author Patrick Peck * @version $Id$ */ public interface ReferencesCheckResult { /** * Gets the check code. - * + * * @return A numerical representation of the result of the reference check. */ - public int getCode(); + int getCode(); + /** * Gets the additional information about the result. - * + * * @return Additional information about the result. */ - public ReferencesCheckResultInfo getInfo(); + ReferencesCheckResultInfo getInfo(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/ReferencesCheckResultInfo.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/ReferencesCheckResultInfo.java index fc87c98..2a2511e 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/ReferencesCheckResultInfo.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/ReferencesCheckResultInfo.java @@ -21,29 +21,29 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlverify; import org.w3c.dom.NodeList; /** * Additional information contained in a ReferencesCheckResult. - * + * * @author Patrick Peck * @version $Id$ */ public interface ReferencesCheckResultInfo { /** * Gets the additional info of the failed dsig:reference element. - * + * * @return The info elements. */ - public NodeList getAnyOtherInfo(); + NodeList getAnyOtherInfo(); + /** * Gets the positions of the failed signature references containing the * references to the manifests being described by this object. - * - * @return The positions of the failed signature references. + * + * @return The positions of the failed signature references. */ - public int[] getFailedReferences(); + int[] getFailedReferences(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/SignatureManifestCheckParams.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/SignatureManifestCheckParams.java index 524d4b8..d1e621e 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/SignatureManifestCheckParams.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/SignatureManifestCheckParams.java @@ -21,14 +21,13 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlverify; import java.util.List; /** * Contains parameters used to check the signature manifest. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -36,15 +35,16 @@ import java.util.List; public interface SignatureManifestCheckParams { /** * Gets the referential information. - * + * * @return The referential information. */ - public List getReferenceInfos(); + List getReferenceInfos(); + /** * Gets information on whether signature source data should be returned. - * + * * @return true, if signature source data should be returned, - * otherwise false. + * otherwise false. */ - public boolean getReturnReferenceInputData(); + boolean getReturnReferenceInputData(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/SupplementProfile.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/SupplementProfile.java index 934e7c6..a906195 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/SupplementProfile.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/SupplementProfile.java @@ -21,12 +21,11 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlverify; /** * Base class for supplementary information. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -35,18 +34,19 @@ public interface SupplementProfile { /** * Indicates that this object contains explicit supplementary information. */ - public static final int EXPLICIT_SUPPLEMENTPROFILE = 0; + int EXPLICIT_SUPPLEMENTPROFILE = 0; /** * Indicates that this object contains a profile id where supplementary * information can be found. */ - public static final int ID_SUPPLEMENTPROFILE = 1; + int ID_SUPPLEMENTPROFILE = 1; /** * Gets the type of supplementary information contained in this object. - * + * * @return The type of supplementary information contained in this object, - * either EXPLICIT_SUPPLEMENT or ID_SUPPLEMENT. + * either EXPLICIT_SUPPLEMENT or + * ID_SUPPLEMENT. */ - public int getSupplementProfileType(); + int getSupplementProfileType(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/SupplementProfileExplicit.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/SupplementProfileExplicit.java index d01abec..e0da05d 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/SupplementProfileExplicit.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/SupplementProfileExplicit.java @@ -21,14 +21,13 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlverify; import at.gv.egovernment.moa.spss.api.common.XMLDataObjectAssociation; /** * Encapsulates explicit supplementary information. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -36,8 +35,8 @@ import at.gv.egovernment.moa.spss.api.common.XMLDataObjectAssociation; public interface SupplementProfileExplicit extends SupplementProfile { /** * Gets the supplemental object. - * + * * @return The supplemental object. */ - public XMLDataObjectAssociation getSupplementProfile(); + XMLDataObjectAssociation getSupplementProfile(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/SupplementProfileID.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/SupplementProfileID.java index beeb2f0..b890c3a 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/SupplementProfileID.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/SupplementProfileID.java @@ -21,22 +21,20 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlverify; /** * Encapsulates supplementary information stored in a profile. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ */ public interface SupplementProfileID extends SupplementProfile { /** - * Gets the id of the profile where the supplementary information can be - * found. - * + * Gets the id of the profile where the supplementary information can be found. + * * @return The profile id. */ - public String getSupplementProfileID(); + String getSupplementProfileID(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/TransformParameter.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/TransformParameter.java index 7ecd1b8..6eeb759 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/TransformParameter.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/TransformParameter.java @@ -21,44 +21,44 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlverify; /** - * Object encapsulating transform parameters either as a URI, binary or - * hashed. - * + * Object encapsulating transform parameters either as a URI, binary or hashed. + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ */ public interface TransformParameter { /** - * Indicates that this object contains a transform parameter given as - * a URI. + * Indicates that this object contains a transform parameter given as a URI. */ - public static final int URI_TRANSFORMPARAMETER = 0; + int URI_TRANSFORMPARAMETER = 0; /** * Indicates that this object contains binary transform parameter. */ - public static final int BINARY_TRANSFORMPARAMETER = 1; + int BINARY_TRANSFORMPARAMETER = 1; /** * Indicatest that this object contains a binary hash of the transform * parameter. */ - public static final int HASH_TRANSFORMPARAMETER = 2; - + int HASH_TRANSFORMPARAMETER = 2; + /** * Gets the type of transform parameter contained in this object. - * - * @return The type of transform parameter, being one of - * URI_TRANSFORMPARAMETER, BINARY_TRANSFORMPARAMETER - * or HASH_TRANSFORMPARAMETER. + * + * @return The type of transform parameter, being one of + * URI_TRANSFORMPARAMETER, + * BINARY_TRANSFORMPARAMETER or + * HASH_TRANSFORMPARAMETER. */ - public int getTransformParameterType(); + int getTransformParameterType(); + /** * Gets the transform parameter URI. - * + * * @return The transform parameter URI. */ - public String getURI();} + String getURI(); +} diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/TransformParameterBinary.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/TransformParameterBinary.java index 388c5d0..afd3a89 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/TransformParameterBinary.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/TransformParameterBinary.java @@ -21,14 +21,13 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlverify; import java.io.InputStream; /** * Encapsulates a binary transform parameter. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -36,10 +35,10 @@ import java.io.InputStream; public interface TransformParameterBinary extends TransformParameter { /** * Gets the binary transform parameter. - * - * @return An InputStream from which the binary content can - * be read. + * + * @return An InputStream from which the binary content can be + * read. */ - public InputStream getBinaryContent(); + InputStream getBinaryContent(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/TransformParameterHash.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/TransformParameterHash.java index 2ff6f39..11ad51e 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/TransformParameterHash.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/TransformParameterHash.java @@ -21,13 +21,11 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlverify; - /** * Contains a hash of the transform parameter. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -35,16 +33,16 @@ package at.gv.egovernment.moa.spss.api.xmlverify; public interface TransformParameterHash extends TransformParameter { /** * Gets the method used for calculating the digest value. - * + * * @return The digest method. */ - public String getDigestMethod(); + String getDigestMethod(); + /** * Gets the binary hash of the transform parameter. - * + * * @return A binary representation of the hash. */ - public byte[] getDigestValue(); - + byte[] getDigestValue(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/TransformParameterURI.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/TransformParameterURI.java index bc73e95..743ecb1 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/TransformParameterURI.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/TransformParameterURI.java @@ -21,12 +21,11 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlverify; /** * Encapsulates a transform parameter given as a URI. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifySignatureInfo.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifySignatureInfo.java index 5d6e0eb..f910747 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifySignatureInfo.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifySignatureInfo.java @@ -21,14 +21,13 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlverify; import at.gv.egovernment.moa.spss.api.common.Content; /** * Encapsulates a signature. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -36,16 +35,17 @@ import at.gv.egovernment.moa.spss.api.common.Content; public interface VerifySignatureInfo { /** * Gets the content of the VerifySignatureEnvironment element. - * - * @return A MOAElement containing the - * VerifySignatureEnvironment in a DOM-like structure. + * + * @return A MOAElement containing the + * VerifySignatureEnvironment in a DOM-like structure. */ - public Content getVerifySignatureEnvironment(); + Content getVerifySignatureEnvironment(); + /** * Gets the location of the signature. - * + * * @return The location of the signature within the signature environment. - */ - public VerifySignatureLocation getVerifySignatureLocation(); + */ + VerifySignatureLocation getVerifySignatureLocation(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifySignatureLocation.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifySignatureLocation.java index 56a2567..8cd1d4a 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifySignatureLocation.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifySignatureLocation.java @@ -21,14 +21,13 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlverify; import at.gv.egovernment.moa.spss.api.common.ElementSelector; /** * Specifies where to find the signature to be verified. - * + * * @author Patrick Peck * @version $Id$ */ diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifyTransformsInfoProfile.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifyTransformsInfoProfile.java index a55d55e..8a821d6 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifyTransformsInfoProfile.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifyTransformsInfoProfile.java @@ -21,12 +21,11 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlverify; /** * Object for explicitly specifying a transformation path. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -35,18 +34,18 @@ public interface VerifyTransformsInfoProfile { /** * Indicates that this object contains the transformation path explicitly. */ - public static final int EXPLICIT_VERIFYTRANSFORMSINFOPROFILE = 0; + int EXPLICIT_VERIFYTRANSFORMSINFOPROFILE = 0; /** * Indicatest that this object contains a transformation info id. */ - public static final int ID_VERIFYTRANSFORMSINFOPROFILE = 1; - + int ID_VERIFYTRANSFORMSINFOPROFILE = 1; + /** * Gets the type of transformation information contained in this object. - * - * @return The type of transformation information, either - * EXPLICIT_VERIFYTRANSFORMSINFOPROFILE or - * ID_VERIFYTRANSFORMSINFOPROFILE. + * + * @return The type of transformation information, either + * EXPLICIT_VERIFYTRANSFORMSINFOPROFILE or + * ID_VERIFYTRANSFORMSINFOPROFILE. */ - public int getVerifyTransformsInfoProfileType(); + int getVerifyTransformsInfoProfileType(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifyTransformsInfoProfileExplicit.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifyTransformsInfoProfileExplicit.java index cc29ace..bd91a28 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifyTransformsInfoProfileExplicit.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifyTransformsInfoProfileExplicit.java @@ -21,14 +21,13 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlverify; import java.util.List; /** * Encapsulates explicit transformation information. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -36,14 +35,15 @@ import java.util.List; public interface VerifyTransformsInfoProfileExplicit extends VerifyTransformsInfoProfile { /** * Gets the XMLDSig transforms element. - * + * * @return The List of Transforms. */ - public List getTransforms(); + List getTransforms(); + /** * Gets the transformation parameters. - * + * * @return The transformation parameters. */ - public List getTransformParameters(); + List getTransformParameters(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifyTransformsInfoProfileID.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifyTransformsInfoProfileID.java index eeb28da..ef083ba 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifyTransformsInfoProfileID.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifyTransformsInfoProfileID.java @@ -21,12 +21,11 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlverify; /** * Encapsulates transformation info id for signature verification. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -34,9 +33,9 @@ package at.gv.egovernment.moa.spss.api.xmlverify; public interface VerifyTransformsInfoProfileID extends VerifyTransformsInfoProfile { /** * Gets the identifier referencing the transformation info. - * + * * @return The identifier referencing the transformation info. */ - public String getVerifyTransformsInfoProfileID(); + String getVerifyTransformsInfoProfileID(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifyXMLSignatureRequest.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifyXMLSignatureRequest.java index c4a0fd1..666164a 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifyXMLSignatureRequest.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifyXMLSignatureRequest.java @@ -21,67 +21,70 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlverify; import java.util.Date; import java.util.List; - /** * Object that encapsulates a request to verify an XML signature. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ */ public interface VerifyXMLSignatureRequest { /** - * Gets the date and time for which the signature verification has to - * be performed. - * - * @return Date and time for which the signature verification has - * to be performed. + * Gets the date and time for which the signature verification has to be + * performed. + * + * @return Date and time for which the signature verification has to be + * performed. */ - public Date getDateTime(); + Date getDateTime(); + /** * Gets the signature to be verified. - * + * * @return The signature to be verified. */ - public VerifySignatureInfo getSignatureInfo(); + VerifySignatureInfo getSignatureInfo(); + /** * Gets the supplemental information. - * + * * @return The supplemental information. - */ - public List getSupplementProfiles(); + */ + List getSupplementProfiles(); + /** * Gets parameters for Security Layer signature verification. - * + * * @return Parameters for Security Layer signature verification. */ - public SignatureManifestCheckParams getSignatureManifestCheckParams(); + SignatureManifestCheckParams getSignatureManifestCheckParams(); + /** * Checks, whether actually signed data shall be returned. - * - * @return true, if signed data will be returned, - * otherwise false. + * + * @return true, if signed data will be returned, otherwise + * false. */ - public boolean getReturnHashInputData(); + boolean getReturnHashInputData(); + /** * Gets the profile id of the set of trusted certificates to be used for * signature verification. - * + * * @return The id of the trusted certificates. */ - public String getTrustProfileId(); - + String getTrustProfileId(); + /** * Should perform extended validation - * - * @return true, if signed data will be returned, - * otherwise false. + * + * @return true, if signed data will be returned, otherwise + * false. */ - public boolean getExtendedValidaiton(); + boolean getExtendedValidaiton(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifyXMLSignatureResponse.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifyXMLSignatureResponse.java index 0f42903..33fcf24 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifyXMLSignatureResponse.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/api/xmlverify/VerifyXMLSignatureResponse.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.api.xmlverify; import java.util.List; @@ -33,7 +32,7 @@ import at.gv.egovernment.moa.spss.api.common.SignerInfo; /** * Object that encapsulates the response on a request to verify an XML * signature. - * + * * @author Patrick Peck * @author Stephan Grill * @version $Id$ @@ -41,57 +40,63 @@ import at.gv.egovernment.moa.spss.api.common.SignerInfo; public interface VerifyXMLSignatureResponse { /** * Gets a SignerInfo element according to XMLDSig. - * + * * @return A SignerInfo element according to XMLDSig. */ - public SignerInfo getSignerInfo(); + SignerInfo getSignerInfo(); + /** * Gets datas signed by the signatory. - * + * * @return The signed datas. */ - public List getHashInputDatas(); + List getHashInputDatas(); + /** * Gets source datas elements. - * + * * @return The source datas elements. */ - public List getReferenceInputDatas(); + List getReferenceInputDatas(); + /** - * Gets the result of the signature verification. - * - * @return The result of the signature verification. - */ - public ReferencesCheckResult getSignatureCheck(); + * Gets the result of the signature verification. + * + * @return The result of the signature verification. + */ + ReferencesCheckResult getSignatureCheck(); + /** * Gets the result of the signature manifest verification. - * + * * @return The result of the signature manifest verification. */ - public ReferencesCheckResult getSignatureManifestCheck(); + ReferencesCheckResult getSignatureManifestCheck(); + /** * Gets XMLDSigManifestCheck elements. - * + * * @return The XMLDSigManifestCheck elements. */ - public List getXMLDsigManifestChecks(); + List getXMLDsigManifestChecks(); + /** * Gets the result of the certification verification. - * + * * @return The result of the certificate verification. */ - public CheckResult getCertificateCheck(); - + CheckResult getCertificateCheck(); + /** * Gets AdES Form results - * + * * This might be null! - * + * * @return The result of the AdES Form validation */ - public List getAdESFormResults(); - - public ExtendedCertificateCheckResult getExtendedCertificateCheck(); - - public String getSignatureAlgorithm(); + List getAdESFormResults(); + + ExtendedCertificateCheckResult getExtendedCertificateCheck(); + + String getSignatureAlgorithm(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/CRLDistributionPoint.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/CRLDistributionPoint.java index b2389a4..bf11240 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/CRLDistributionPoint.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/CRLDistributionPoint.java @@ -23,10 +23,6 @@ package at.gv.egovernment.moa.spss.server.config; -import iaik.asn1.structures.Name; -import iaik.pki.revocation.RevocationSourceTypes; -import iaik.utils.RFC2253NameParserException; - import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; @@ -34,144 +30,151 @@ import java.util.StringTokenizer; import at.gv.egovernment.moa.spss.util.MessageProvider; import at.gv.egovernment.moaspss.logging.LogMsg; import at.gv.egovernment.moaspss.logging.Logger; +import iaik.asn1.structures.Name; +import iaik.pki.revocation.RevocationSourceTypes; +import iaik.utils.RFC2253NameParserException; /** * A class representing a CRL distribution point. - * + * * @author Sven Aigner * @author Patrick Peck * @version $Id$ */ -public class CRLDistributionPoint extends DistributionPoint implements iaik.pki.revocation.CRLDistributionPoint { - - private static Map RC_MAPPING = new HashMap(); - - static { - - // create the mapping between reason code strings and their integer - // values - RC_MAPPING.put("unused", new Integer(iaik.asn1.structures.DistributionPoint.unused)); - RC_MAPPING.put("keyCompromise", new Integer(iaik.asn1.structures.DistributionPoint.keyCompromise)); - RC_MAPPING.put("cACompromise", new Integer(iaik.asn1.structures.DistributionPoint.cACompromise)); - RC_MAPPING.put("affiliationChanged", new Integer(iaik.asn1.structures.DistributionPoint.affiliationChanged)); - RC_MAPPING.put("superseded", new Integer(iaik.asn1.structures.DistributionPoint.superseded)); - RC_MAPPING.put("cessationOfOperation", - new Integer(iaik.asn1.structures.DistributionPoint.cessationOfOperation)); - RC_MAPPING.put("certificateHold", new Integer(iaik.asn1.structures.DistributionPoint.certificateHold)); - RC_MAPPING.put("privilegeWithdrawn", new Integer(iaik.asn1.structures.DistributionPoint.privilegeWithdrawn)); - RC_MAPPING.put("aACompromise", new Integer(iaik.asn1.structures.DistributionPoint.aACompromise)); - } - - /** - * The name of the CA issuing the CRL referred to by this DP. - */ - private String issuerName_; - - /** - * The reason codes applicable for the distribution point. - */ - private int reasonCodes; - - /** - * Create a CRLDistributionPoint. - * - * @param issuerName - * The name of the CA issuing the CRL referred to by this DP. - * - * @param uri - * The URI of the distribution point. - * - * @param reasonCodeStr - * A list of reason codes (a space-separated enumeration). - */ - public CRLDistributionPoint(String issuerName, String uri, String reasonCodeStr) { - super(uri); - issuerName_ = issuerName; - this.reasonCodes = extractReasonCodes(reasonCodeStr); - } - - /** - * @see DistributionPoint#getType() - */ - public String getType() { - return RevocationSourceTypes.CRL; - } - - /** - * Convert a list of reason codes provided as a String to a - * binary representation. - * - * @param reasonCodeStr - * A String containing a blank-separated, textual - * representation of reason codes. - * @return int A binary representation of reason codes. - * @see iaik.asn1.structures.DistributionPoint - */ - private int extractReasonCodes(String reasonCodeStr) { - int codes = 0; - StringTokenizer tokenizer = new StringTokenizer(reasonCodeStr); - String token; - Integer reasonCode; - - while (tokenizer.hasMoreTokens()) { - token = tokenizer.nextToken(); - reasonCode = (Integer) RC_MAPPING.get(token); - if (reasonCode != null) { - codes |= reasonCode.intValue(); - } else { - MessageProvider msg = MessageProvider.getInstance(); - Logger.warn(new LogMsg(msg.getMessage("config.07", new Object[] { token }))); - } - } - - // If reasonCodeStr is empty, set all possible reason codes - if (codes == 0) - codes = iaik.asn1.structures.DistributionPoint.unused | iaik.asn1.structures.DistributionPoint.keyCompromise - | iaik.asn1.structures.DistributionPoint.cACompromise - | iaik.asn1.structures.DistributionPoint.affiliationChanged - | iaik.asn1.structures.DistributionPoint.superseded - | iaik.asn1.structures.DistributionPoint.cessationOfOperation - | iaik.asn1.structures.DistributionPoint.certificateHold - | iaik.asn1.structures.DistributionPoint.privilegeWithdrawn - | iaik.asn1.structures.DistributionPoint.aACompromise; - - return codes; - } - - /** - * Return a binary representation of the reason codes of this distribution - * point. - * - * @return The binary representation of the reason codes. - */ - public int getReasonCodes() { - return reasonCodes; - } - - /** - * Return a String representation of this distribution point. - * - * @return The String representation of this distribution - * point. - * @see java.lang.Object#toString() - */ - public String toString() { - return "(DistributionPoint - " + ("URI<" + getUri()) + ("> REASONCODES<" + getReasonCodes() + ">)"); - } - - /** - * @see iaik.pki.revocation.CRLDistributionPoint#getIssuerName() - */ - public String getIssuerName() { - return issuerName_; - } - - @Override - public Name getIssuerDN() { - try { - return new Name(this.issuerName_); - } catch (RFC2253NameParserException e) { - throw new RuntimeException(e); - } - } +public class CRLDistributionPoint extends DistributionPoint implements + iaik.pki.revocation.CRLDistributionPoint { + + private static Map RC_MAPPING = new HashMap(); + + static { + + // create the mapping between reason code strings and their integer + // values + RC_MAPPING.put("unused", new Integer(iaik.asn1.structures.DistributionPoint.unused)); + RC_MAPPING.put("keyCompromise", new Integer(iaik.asn1.structures.DistributionPoint.keyCompromise)); + RC_MAPPING.put("cACompromise", new Integer(iaik.asn1.structures.DistributionPoint.cACompromise)); + RC_MAPPING.put("affiliationChanged", new Integer( + iaik.asn1.structures.DistributionPoint.affiliationChanged)); + RC_MAPPING.put("superseded", new Integer(iaik.asn1.structures.DistributionPoint.superseded)); + RC_MAPPING.put("cessationOfOperation", + new Integer(iaik.asn1.structures.DistributionPoint.cessationOfOperation)); + RC_MAPPING.put("certificateHold", new Integer(iaik.asn1.structures.DistributionPoint.certificateHold)); + RC_MAPPING.put("privilegeWithdrawn", new Integer( + iaik.asn1.structures.DistributionPoint.privilegeWithdrawn)); + RC_MAPPING.put("aACompromise", new Integer(iaik.asn1.structures.DistributionPoint.aACompromise)); + } + + /** + * The name of the CA issuing the CRL referred to by this DP. + */ + private final String issuerName_; + + /** + * The reason codes applicable for the distribution point. + */ + private final int reasonCodes; + + /** + * Create a CRLDistributionPoint. + * + * @param issuerName The name of the CA issuing the CRL referred to by this + * DP. + * + * @param uri The URI of the distribution point. + * + * @param reasonCodeStr A list of reason codes (a space-separated enumeration). + */ + public CRLDistributionPoint(String issuerName, String uri, String reasonCodeStr) { + super(uri); + issuerName_ = issuerName; + this.reasonCodes = extractReasonCodes(reasonCodeStr); + } + + /** + * @see DistributionPoint#getType() + */ + @Override + public String getType() { + return RevocationSourceTypes.CRL; + } + + /** + * Convert a list of reason codes provided as a String to a binary + * representation. + * + * @param reasonCodeStr A String containing a blank-separated, + * textual representation of reason codes. + * @return int A binary representation of reason codes. + * @see iaik.asn1.structures.DistributionPoint + */ + private int extractReasonCodes(String reasonCodeStr) { + int codes = 0; + final StringTokenizer tokenizer = new StringTokenizer(reasonCodeStr); + String token; + Integer reasonCode; + + while (tokenizer.hasMoreTokens()) { + token = tokenizer.nextToken(); + reasonCode = (Integer) RC_MAPPING.get(token); + if (reasonCode != null) { + codes |= reasonCode.intValue(); + } else { + final MessageProvider msg = MessageProvider.getInstance(); + Logger.warn(new LogMsg(msg.getMessage("config.07", new Object[] { token }))); + } + } + + // If reasonCodeStr is empty, set all possible reason codes + if (codes == 0) { + codes = iaik.asn1.structures.DistributionPoint.unused + | iaik.asn1.structures.DistributionPoint.keyCompromise + | iaik.asn1.structures.DistributionPoint.cACompromise + | iaik.asn1.structures.DistributionPoint.affiliationChanged + | iaik.asn1.structures.DistributionPoint.superseded + | iaik.asn1.structures.DistributionPoint.cessationOfOperation + | iaik.asn1.structures.DistributionPoint.certificateHold + | iaik.asn1.structures.DistributionPoint.privilegeWithdrawn + | iaik.asn1.structures.DistributionPoint.aACompromise; + } + + return codes; + } + + /** + * Return a binary representation of the reason codes of this distribution + * point. + * + * @return The binary representation of the reason codes. + */ + @Override + public int getReasonCodes() { + return reasonCodes; + } + + /** + * Return a String representation of this distribution point. + * + * @return The String representation of this distribution point. + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "(DistributionPoint - " + "URI<" + getUri() + "> REASONCODES<" + getReasonCodes() + ">)"; + } + + /** + * @see iaik.pki.revocation.CRLDistributionPoint#getIssuerName() + */ + public String getIssuerName() { + return issuerName_; + } + + @Override + public Name getIssuerDN() { + try { + return new Name(this.issuerName_); + } catch (final RFC2253NameParserException e) { + throw new RuntimeException(e); + } + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/ConfigurationException.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/ConfigurationException.java index 6546e88..13f1de9 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/ConfigurationException.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/ConfigurationException.java @@ -21,27 +21,26 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.config; import at.gv.egovernment.moa.spss.MOASystemException; /** * Exception signalling an error in the configuration. - * + * * @author Patrick Peck * @version $Id$ */ public class ConfigurationException extends MOASystemException { /** - * - */ - private static final long serialVersionUID = -1934466124930228755L; + * + */ + private static final long serialVersionUID = -1934466124930228755L; -/** + /** * Create a ConfigurationException. - * + * * @see at.gv.egovernment.moa.spss.MOAException#MOAException(String, Object[]) */ public ConfigurationException(String messageId, Object[] parameters) { @@ -50,12 +49,14 @@ public class ConfigurationException extends MOASystemException { /** * Create a ConfigurationException. - * @see at.gv.egovernment.moa.spss.MOAException#MOAException(String, Object[], Throwable) + * + * @see at.gv.egovernment.moa.spss.MOAException#MOAException(String, Object[], + * Throwable) */ public ConfigurationException( - String messageId, - Object[] parameters, - Throwable wrapped) { + String messageId, + Object[] parameters, + Throwable wrapped) { super(messageId, parameters, wrapped); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/ConfigurationPartsBuilder.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/ConfigurationPartsBuilder.java index 3c00232..41b0c29 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/ConfigurationPartsBuilder.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/ConfigurationPartsBuilder.java @@ -20,22 +20,8 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.config; -import iaik.asn1.structures.Name; -//import iaik.ixsil.exceptions.URIException; -//import iaik.ixsil.util.URI; -import iaik.pki.pathvalidation.ChainingModes; -import iaik.pki.revocation.RevocationSourceTypes; -import iaik.server.modules.xml.BlackListEntry; -import iaik.server.modules.xml.ExternalReferenceChecker; -import iaik.server.modules.xml.WhiteListEntry; -import iaik.utils.RFC2253NameParser; -import iaik.utils.RFC2253NameParserException; -import iaik.xml.crypto.utils.URI; -import iaik.xml.crypto.utils.URIException; - import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -70,14 +56,25 @@ import at.gv.egovernment.moaspss.logging.LogMsg; import at.gv.egovernment.moaspss.logging.Logger; import at.gv.egovernment.moaspss.util.Constants; import at.gv.egovernment.moaspss.util.DOMUtils; -import at.gv.egovernment.moaspss.util.FileUtils; import at.gv.egovernment.moaspss.util.MiscUtil; import at.gv.egovernment.moaspss.util.StringUtils; import at.gv.egovernment.moaspss.util.XPathUtils; +import iaik.asn1.structures.Name; +//import iaik.ixsil.exceptions.URIException; +//import iaik.ixsil.util.URI; +import iaik.pki.pathvalidation.ChainingModes; +import iaik.pki.revocation.RevocationSourceTypes; +import iaik.server.modules.xml.BlackListEntry; +import iaik.server.modules.xml.ExternalReferenceChecker; +import iaik.server.modules.xml.WhiteListEntry; +import iaik.utils.RFC2253NameParser; +import iaik.utils.RFC2253NameParserException; +import iaik.xml.crypto.utils.URI; +import iaik.xml.crypto.utils.URIException; /** * A class that builds configuration data from a DOM based representation. - * + * * @author Patrick Peck * @version $Id$ */ @@ -102,271 +99,274 @@ public class ConfigurationPartsBuilder { // private static final String ROOT = "/" + CONF + "MOAConfiguration/"; - + private static final String PDFAS_CONFIGURATION_XPATH = - ROOT + CONF + "Common/" + CONF + "PDFASConfig"; - + ROOT + CONF + "Common/" + CONF + "PDFASConfig"; + private static final String FORMRESULT_CONFIGURATION_XPATH = - ROOT + CONF + "Common/" + CONF + "AdESFormResult"; - + ROOT + CONF + "Common/" + CONF + "AdESFormResult"; + private static final String DIGEST_METHOD_XPATH = - ROOT + CONF + "SignatureCreation/" - + CONF + "XMLDSig/" - + CONF + "DigestMethodAlgorithm"; + ROOT + CONF + "SignatureCreation/" + + CONF + "XMLDSig/" + + CONF + "DigestMethodAlgorithm"; private static final String XADES_VERSION_XPATH = - ROOT + CONF + "SignatureCreation/" - + CONF + "XAdES/" - + CONF + "Version"; + ROOT + CONF + "SignatureCreation/" + + CONF + "XAdES/" + + CONF + "Version"; private static final String C14N_ALGORITHM_XPATH = - ROOT + CONF + "SignatureCreation/" - + CONF + "XMLDSig/" - + CONF + "CanonicalizationAlgorithm"; + ROOT + CONF + "SignatureCreation/" + + CONF + "XMLDSig/" + + CONF + "CanonicalizationAlgorithm"; private static final String HARDWARE_CRYPTO_MODULE_XPATH = - ROOT + CONF + "Common/" - + CONF + "HardwareCryptoModule"; + ROOT + CONF + "Common/" + + CONF + "HardwareCryptoModule"; private static final String PERMIT_EXTERNAL_URIS_XPATH = - ROOT + CONF + "Common/" - + CONF + "PermitExternalUris"; + ROOT + CONF + "Common/" + + CONF + "PermitExternalUris"; private static final String BLACK_LIST_URIS_XPATH = - ROOT + CONF + "Common/" - + CONF + "PermitExternalUris/" - + CONF + "BlackListUri"; + ROOT + CONF + "Common/" + + CONF + "PermitExternalUris/" + + CONF + "BlackListUri"; private static final String FORBID_EXTERNAL_URIS_XPATH = - ROOT + CONF + "Common/" - + CONF + "ForbidExternalUris"; + ROOT + CONF + "Common/" + + CONF + "ForbidExternalUris"; private static final String WHITE_LIST_URIS_XPATH = - ROOT + CONF + "Common/" - + CONF + "ForbidExternalUris/" - + CONF + "WhiteListUri"; - + ROOT + CONF + "Common/" + + CONF + "ForbidExternalUris/" + + CONF + "WhiteListUri"; + private static final String HARDWARE_KEY_XPATH = - ROOT + CONF + "SignatureCreation/" - + CONF + "KeyModules/" - + CONF + "HardwareKeyModule"; + ROOT + CONF + "SignatureCreation/" + + CONF + "KeyModules/" + + CONF + "HardwareKeyModule"; private static final String SOFTWARE_KEY_XPATH = - ROOT + CONF + "SignatureCreation/" - + CONF + "KeyModules/" - + CONF + "SoftwareKeyModule"; - private static final String KEYGROUP_XPATH = - ROOT + CONF + "SignatureCreation/" - + CONF + "KeyGroup"; + ROOT + CONF + "SignatureCreation/" + + CONF + "KeyModules/" + + CONF + "SoftwareKeyModule"; + private static final String KEYGROUP_XPATH = + ROOT + CONF + "SignatureCreation/" + + CONF + "KeyGroup"; private static final String KEYGROUP_MAPPING_XPATH = - ROOT + CONF + "SignatureCreation/" - + CONF + "KeyGroupMapping"; - private static final String ISSUER_XPATH = - DSIG + "X509IssuerName"; - private static final String SERIAL_XPATH = - DSIG + "X509SerialNumber"; + ROOT + CONF + "SignatureCreation/" + + CONF + "KeyGroupMapping"; + private static final String ISSUER_XPATH = + DSIG + "X509IssuerName"; + private static final String SERIAL_XPATH = + DSIG + "X509SerialNumber"; private static final String CERTSTORE_LOCATION_XPATH = - ROOT + CONF + "SignatureVerification/" - + CONF + "CertificateValidation/" - + CONF + "PathConstruction/" - + CONF + "CertificateStore/" - + CONF + "DirectoryStore/" - + CONF + "Location"; - private static final String AUTO_ADD_CERTIFICATES_XPATH_ = - ROOT + CONF + "SignatureVerification/" - + CONF + "CertificateValidation/" - + CONF + "PathConstruction/" - + CONF + "AutoAddCertificates"; - - private static final String AUTO_ADD_EE_CERTIFICATES_XPATH_ = - ROOT + CONF + "SignatureVerification/" - + CONF + "CertificateValidation/" - + CONF + "PathConstruction/" - + CONF + "AutoAddEECertificates"; - + ROOT + CONF + "SignatureVerification/" + + CONF + "CertificateValidation/" + + CONF + "PathConstruction/" + + CONF + "CertificateStore/" + + CONF + "DirectoryStore/" + + CONF + "Location"; + private static final String AUTO_ADD_CERTIFICATES_XPATH_ = + ROOT + CONF + "SignatureVerification/" + + CONF + "CertificateValidation/" + + CONF + "PathConstruction/" + + CONF + "AutoAddCertificates"; + + private static final String AUTO_ADD_EE_CERTIFICATES_XPATH_ = + ROOT + CONF + "SignatureVerification/" + + CONF + "CertificateValidation/" + + CONF + "PathConstruction/" + + CONF + "AutoAddEECertificates"; + private static final String USE_AUTHORITY_INFO_ACCESS_XPATH_ = - ROOT + CONF + "SignatureVerification/" - + CONF + "CertificateValidation/" - + CONF + "PathConstruction/" - + CONF + "UseAuthorityInformationAccess"; + ROOT + CONF + "SignatureVerification/" + + CONF + "CertificateValidation/" + + CONF + "PathConstruction/" + + CONF + "UseAuthorityInformationAccess"; private static final String CHAINING_MODES_XPATH = - ROOT + CONF + "SignatureVerification/" - + CONF + "CertificateValidation/" - + CONF + "PathValidation/" - + CONF + "ChainingMode"; + ROOT + CONF + "SignatureVerification/" + + CONF + "CertificateValidation/" + + CONF + "PathValidation/" + + CONF + "ChainingMode"; private static final String CHAINING_MODES_DEFAULT_XPATH = - CHAINING_MODES_XPATH + "/" - + CONF + "DefaultMode"; + CHAINING_MODES_XPATH + "/" + + CONF + "DefaultMode"; private static final String TRUST_ANCHOR_XPATH = - CHAINING_MODES_XPATH + "/" - + CONF + "TrustAnchor"; + CHAINING_MODES_XPATH + "/" + + CONF + "TrustAnchor"; private static final String TRUST_PROFILE_XPATH = - ROOT + CONF + "SignatureVerification/" - + CONF + "CertificateValidation/" - + CONF + "PathValidation/" - + CONF + "TrustProfile"; + ROOT + CONF + "SignatureVerification/" + + CONF + "CertificateValidation/" + + CONF + "PathValidation/" + + CONF + "TrustProfile"; private static final String DISTRIBUTION_POINTS_XPATH = - ROOT + CONF + "SignatureVerification/" - + CONF + "CertificateValidation/" - + CONF + "RevocationChecking/" - + CONF + "DistributionPoint"; + ROOT + CONF + "SignatureVerification/" + + CONF + "CertificateValidation/" + + CONF + "RevocationChecking/" + + CONF + "DistributionPoint"; private static final String CRL_RETENTION_INTERVALS_CA_XPATH = - ROOT + CONF + "SignatureVerification/" - + CONF + "CertificateValidation/" - + CONF + "RevocationChecking/" - + CONF + "CrlRetentionIntervals/" - + CONF + "CA"; - private static final String ENABLE_REVOCATION_CHECKING_XPATH_ = - ROOT + CONF + "SignatureVerification/" - + CONF + "CertificateValidation/" - + CONF + "RevocationChecking/" - + CONF + "EnableChecking"; + ROOT + CONF + "SignatureVerification/" + + CONF + "CertificateValidation/" + + CONF + "RevocationChecking/" + + CONF + "CrlRetentionIntervals/" + + CONF + "CA"; + private static final String ENABLE_REVOCATION_CHECKING_XPATH_ = + ROOT + CONF + "SignatureVerification/" + + CONF + "CertificateValidation/" + + CONF + "RevocationChecking/" + + CONF + "EnableChecking"; private static final String MAX_REVOCATION_AGE_XPATH_ = - ROOT + CONF + "SignatureVerification/" - + CONF + "CertificateValidation/" - + CONF + "RevocationChecking/" - + CONF + "MaxRevocationAge"; - private static final String REVOCATION_SERVICEORDER_XPATH_ = - ROOT + CONF + "SignatureVerification/" - + CONF + "CertificateValidation/" - + CONF + "RevocationChecking/" - + CONF + "ServiceOrder/" - + CONF + "Service"; - private static final String ENABLE_ARCHIVING_XPATH = - ROOT + CONF + "SignatureVerification/" - + CONF + "CertificateValidation/" - + CONF + "RevocationChecking/" - + CONF + "Archiving/" - + CONF + "EnableArchiving"; - private static final String CRL_ARCHIVE_DURATION_XPATH = - ROOT + CONF + "SignatureVerification/" - + CONF + "CertificateValidation/" - + CONF + "RevocationChecking/" - + CONF + "Archiving/" - + CONF + "ArchiveDuration"; - private static final String ACHIVE_JDBC_URL_ = - ROOT + CONF + "SignatureVerification/" - + CONF + "CertificateValidation/" - + CONF + "RevocationChecking/" - + CONF + "Archiving/" - + CONF + "Archive/" - + CONF + "DatabaseArchive/" - + CONF + "JDBCURL"; - private static final String ACHIVE_JDBC_DRIVER_CLASS_ = - ROOT + CONF + "SignatureVerification/" - + CONF + "CertificateValidation/" - + CONF + "RevocationChecking/" - + CONF + "Archiving/" - + CONF + "Archive/" - + CONF + "DatabaseArchive/" - + CONF + "JDBCDriverClassName"; + ROOT + CONF + "SignatureVerification/" + + CONF + "CertificateValidation/" + + CONF + "RevocationChecking/" + + CONF + "MaxRevocationAge"; + private static final String REVOCATION_SERVICEORDER_XPATH_ = + ROOT + CONF + "SignatureVerification/" + + CONF + "CertificateValidation/" + + CONF + "RevocationChecking/" + + CONF + "ServiceOrder/" + + CONF + "Service"; + private static final String ENABLE_ARCHIVING_XPATH = + ROOT + CONF + "SignatureVerification/" + + CONF + "CertificateValidation/" + + CONF + "RevocationChecking/" + + CONF + "Archiving/" + + CONF + "EnableArchiving"; + private static final String CRL_ARCHIVE_DURATION_XPATH = + ROOT + CONF + "SignatureVerification/" + + CONF + "CertificateValidation/" + + CONF + "RevocationChecking/" + + CONF + "Archiving/" + + CONF + "ArchiveDuration"; + private static final String ACHIVE_JDBC_URL_ = + ROOT + CONF + "SignatureVerification/" + + CONF + "CertificateValidation/" + + CONF + "RevocationChecking/" + + CONF + "Archiving/" + + CONF + "Archive/" + + CONF + "DatabaseArchive/" + + CONF + "JDBCURL"; + private static final String ACHIVE_JDBC_DRIVER_CLASS_ = + ROOT + CONF + "SignatureVerification/" + + CONF + "CertificateValidation/" + + CONF + "RevocationChecking/" + + CONF + "Archiving/" + + CONF + "Archive/" + + CONF + "DatabaseArchive/" + + CONF + "JDBCDriverClassName"; private static final String CREATE_TRANSFORMS_INFO_PROFILE_XPATH = - ROOT + CONF + "SignatureCreation/" - + CONF + "CreateTransformsInfoProfile"; + ROOT + CONF + "SignatureCreation/" + + CONF + "CreateTransformsInfoProfile"; private static final String CREATE_SIGNATURE_ENVIRONMENT_PROFILE_XPATH = - ROOT + CONF + "SignatureCreation/" - + CONF + "CreateSignatureEnvironmentProfile"; + ROOT + CONF + "SignatureCreation/" + + CONF + "CreateSignatureEnvironmentProfile"; private static final String VERIFY_TRANSFORMS_INFO_PROFILE_XPATH = - ROOT + CONF + "SignatureVerification/" - + CONF + "VerifyTransformsInfoProfile"; + ROOT + CONF + "SignatureVerification/" + + CONF + "VerifyTransformsInfoProfile"; private static final String SUPPLEMENT_PROFILE_XPATH = - ROOT + CONF + "SignatureVerification/" - + CONF + "SupplementProfile"; + ROOT + CONF + "SignatureVerification/" + + CONF + "SupplementProfile"; private static final String PERMIT_FILE_URIS_XPATH = - ROOT + CONF + "SignatureVerification/" - + CONF + "PermitFileURIs"; - + ROOT + CONF + "SignatureVerification/" + + CONF + "PermitFileURIs"; + private static final String CONNECTION_TIMEOUT_XPATH_ = - ROOT + CONF + "SignatureVerification/" - + CONF + "CertificateValidation/" - + CONF + "ConnectionTimeout"; - + ROOT + CONF + "SignatureVerification/" + + CONF + "CertificateValidation/" + + CONF + "ConnectionTimeout"; + private static final String READ_TIMEOUT_XPATH_ = - ROOT + CONF + "SignatureVerification/" - + CONF + "CertificateValidation/" - + CONF + "ReadTimeout"; - - private static final String TSL_CONFIGURATION_XPATH = - ROOT + CONF + "SignatureVerification/" - + CONF + "CertificateValidation/" - + CONF + "TSLConfiguration/"; + ROOT + CONF + "SignatureVerification/" + + CONF + "CertificateValidation/" + + CONF + "ReadTimeout"; + + private static final String TSL_CONFIGURATION_XPATH = + ROOT + CONF + "SignatureVerification/" + + CONF + "CertificateValidation/" + + CONF + "TSLConfiguration/"; // - // default values for configuration parameters + // default values for configuration parameters // /** The accepted canonicalization algorithm URIs, as an array */ private static final String[] ACCEPTED_C14N_ALGORITHMS_ARRAY = - { - Constants.C14N_URI, - Constants.C14N_WITH_COMMENTS_URI, - Constants.EXC_C14N_URI, - Constants.EXC_C14N_WITH_COMMENTS_URI }; + { + Constants.C14N_URI, + Constants.C14N_WITH_COMMENTS_URI, + Constants.EXC_C14N_URI, + Constants.EXC_C14N_WITH_COMMENTS_URI }; /** The accepted canonicalization algorithm URIs, as a Set */ private static final Set ACCEPTED_C14N_ALGORITHMS = - new HashSet(Arrays.asList(ACCEPTED_C14N_ALGORITHMS_ARRAY)); + new HashSet(Arrays.asList(ACCEPTED_C14N_ALGORITHMS_ARRAY)); /** Default canonicalization algorithm, if none/illegal has been configured */ private static final String C14N_ALGORITHM_DEFAULT = Constants.C14N_URI; /** The accepted digest method algorithm URIs, as an array */ private static final String[] ACCEPTED_DIGEST_ALGORITHMS_ARRAY = - { Constants.SHA1_URI, - Constants.SHA256_URI, - Constants.SHA384_URI, - Constants.SHA512_URI}; + { Constants.SHA1_URI, + Constants.SHA256_URI, + Constants.SHA384_URI, + Constants.SHA512_URI }; /** The accepted digest method algorithm URIs, as a Set */ private static final Set ACCEPTED_DIGEST_ALGORITHMS = - new HashSet(Arrays.asList(ACCEPTED_DIGEST_ALGORITHMS_ARRAY)); - - - /** Default digest algorithm URI, if none/illegal has been configured (for XAdES 1.1.1) */ + new HashSet(Arrays.asList(ACCEPTED_DIGEST_ALGORITHMS_ARRAY)); + + /** + * Default digest algorithm URI, if none/illegal has been configured (for XAdES + * 1.1.1) + */ private static final String DIGEST_ALGORITHM_DEFAULT_XADES_1_1_1 = Constants.SHA1_URI; - - /** Default digest algorithm URI, if none/illegal has been configured (for XAdES 1.4.2) */ + + /** + * Default digest algorithm URI, if none/illegal has been configured (for XAdES + * 1.4.2) + */ private static final String DIGEST_ALGORITHM_DEFAULT_XADES_1_4_2 = Constants.SHA256_URI; - + /** The root element of the MOA configuration */ - private Element configElem; - + private final Element configElem; + /** * The directory containing the underlying configuration file. */ - private File configRoot_; + private final File configRoot_; /** Whether any warnings were encountered building the configuration. */ - private List warnings = new ArrayList(); + private final List warnings = new ArrayList(); /** * Create a new ConfigurationPartsBuilder. - * + * * @param configElem The root element of the MOA configuration. - * + * * @param configRoot The directory containing the underlying configuration file. */ - public ConfigurationPartsBuilder(Element configElem, File configRoot) - { + public ConfigurationPartsBuilder(Element configElem, File configRoot) { this.configElem = configElem; configRoot_ = configRoot; } /** - * Returns the root element of the MOA configuration. - * + * Returns the root element of the MOA configuration. + * * @return The root element of the MOA configuration. */ public Element getConfigElem() { return configElem; } - - /** + + /** * Returns the directory containing the underlying configuration file. - * + * * @return the directory containing the underlying configuration file. */ - public File getConfigRoot() - { + public File getConfigRoot() { return configRoot_; } /** * Returns the warnings encountered during building the configuration. - * - * @return A List of Strings, containing the - * warning messages. + * + * @return A List of Strings, containing the warning + * messages. */ public List getWarnings() { return warnings; @@ -374,124 +374,114 @@ public class ConfigurationPartsBuilder { /** * Returns the digest method algorithm name. - * + * * @return The digest method algorithm name from the configuration. */ - public String getDigestMethodAlgorithmName() - { + public String getDigestMethodAlgorithmName() { String digestMethod = getElementValue(getConfigElem(), DIGEST_METHOD_XPATH, null); - - if (digestMethod == null || !ACCEPTED_DIGEST_ALGORITHMS.contains(digestMethod)) - { - String xadesVersion = this.getXAdESVersion(); - if (xadesVersion == null) { - info( - "config.23", - new Object[] { "DigestMethodAlgorithm", DIGEST_ALGORITHM_DEFAULT_XADES_1_1_1 }); - digestMethod = DIGEST_ALGORITHM_DEFAULT_XADES_1_1_1; - } - else { - info( - "config.23", - new Object[] { "DigestMethodAlgorithm", DIGEST_ALGORITHM_DEFAULT_XADES_1_4_2 }); - digestMethod = DIGEST_ALGORITHM_DEFAULT_XADES_1_4_2; - } - - + + if (digestMethod == null || !ACCEPTED_DIGEST_ALGORITHMS.contains(digestMethod)) { + final String xadesVersion = this.getXAdESVersion(); + if (xadesVersion == null) { + info( + "config.23", + new Object[] { "DigestMethodAlgorithm", DIGEST_ALGORITHM_DEFAULT_XADES_1_1_1 }); + digestMethod = DIGEST_ALGORITHM_DEFAULT_XADES_1_1_1; + } else { + info( + "config.23", + new Object[] { "DigestMethodAlgorithm", DIGEST_ALGORITHM_DEFAULT_XADES_1_4_2 }); + digestMethod = DIGEST_ALGORITHM_DEFAULT_XADES_1_4_2; + } + } return digestMethod; } - + /** * Returns the digest method algorithm name. - * + * * @return The digest method algorithm name from the configuration. */ - public String getXAdESVersion() - { - String xadesVersion = getElementValue(getConfigElem(), XADES_VERSION_XPATH, null); - + public String getXAdESVersion() { + final String xadesVersion = getElementValue(getConfigElem(), XADES_VERSION_XPATH, null); + return xadesVersion; } - + /** * Returns the digest method algorithm name. - * + * * @return The digest method algorithm name from the configuration. */ - public String getPDFASConfiguration() - { - String pdfasConfiguration = getElementValue(getConfigElem(), PDFAS_CONFIGURATION_XPATH, null); - + public String getPDFASConfiguration() { + final String pdfasConfiguration = getElementValue(getConfigElem(), PDFAS_CONFIGURATION_XPATH, null); + return pdfasConfiguration; } - + /** * Returns the digest method algorithm name. - * + * * @return The digest method algorithm name from the configuration. */ - public int getConnectionTimeout() - { - String connectionTimeout = getElementValue(getConfigElem(), CONNECTION_TIMEOUT_XPATH_, "30"); + public int getConnectionTimeout() { + final String connectionTimeout = getElementValue(getConfigElem(), CONNECTION_TIMEOUT_XPATH_, "30"); int defaultConnectionTimeout = 30; - - if(connectionTimeout != null) { - try { - defaultConnectionTimeout = Integer.parseInt(connectionTimeout); - } catch(NumberFormatException e) { - Logger.warn("Configuration value " + CONNECTION_TIMEOUT_XPATH_ + " should be a number defaulting to 30"); - } + + if (connectionTimeout != null) { + try { + defaultConnectionTimeout = Integer.parseInt(connectionTimeout); + } catch (final NumberFormatException e) { + Logger.warn("Configuration value " + CONNECTION_TIMEOUT_XPATH_ + + " should be a number defaulting to 30"); + } } - - if(defaultConnectionTimeout < 0) { - defaultConnectionTimeout = 30; + + if (defaultConnectionTimeout < 0) { + defaultConnectionTimeout = 30; } - + return defaultConnectionTimeout * 1000; } - - public int getReadTimeout() - { - String connectionTimeout = getElementValue(getConfigElem(), READ_TIMEOUT_XPATH_, "30"); + + public int getReadTimeout() { + final String connectionTimeout = getElementValue(getConfigElem(), READ_TIMEOUT_XPATH_, "30"); int defaultConnectionTimeout = 30; - - if(connectionTimeout != null) { - try { - defaultConnectionTimeout = Integer.parseInt(connectionTimeout); - } catch(NumberFormatException e) { - Logger.warn("Configuration value " + READ_TIMEOUT_XPATH_ + " should be a number defaulting to 30"); - } + + if (connectionTimeout != null) { + try { + defaultConnectionTimeout = Integer.parseInt(connectionTimeout); + } catch (final NumberFormatException e) { + Logger.warn("Configuration value " + READ_TIMEOUT_XPATH_ + " should be a number defaulting to 30"); + } } - - if(defaultConnectionTimeout < 0) { - defaultConnectionTimeout = 30; + + if (defaultConnectionTimeout < 0) { + defaultConnectionTimeout = 30; } - + return defaultConnectionTimeout * 1000; } - - public boolean getAdesFormResult() - { - String enableArchiving = getElementValue(getConfigElem(), FORMRESULT_CONFIGURATION_XPATH, null); - return Boolean.valueOf(enableArchiving).booleanValue(); + + public boolean getAdesFormResult() { + final String enableArchiving = getElementValue(getConfigElem(), FORMRESULT_CONFIGURATION_XPATH, null); + return Boolean.valueOf(enableArchiving).booleanValue(); } - + /** * Returns the canonicalization algorithm name. - * + * * @return The canonicalization algorithm name from the configuration. */ - public String getCanonicalizationAlgorithmName() - { + public String getCanonicalizationAlgorithmName() { String c14nAlgorithm = getElementValue(getConfigElem(), C14N_ALGORITHM_XPATH, null); - if (c14nAlgorithm == null || !ACCEPTED_C14N_ALGORITHMS.contains(c14nAlgorithm)) - { + if (c14nAlgorithm == null || !ACCEPTED_C14N_ALGORITHMS.contains(c14nAlgorithm)) { info( - "config.23", - new Object[] { "CanonicalizationAlgorithm", C14N_ALGORITHM_DEFAULT }); + "config.23", + new Object[] { "CanonicalizationAlgorithm", C14N_ALGORITHM_DEFAULT }); c14nAlgorithm = C14N_ALGORITHM_DEFAULT; } @@ -500,189 +490,172 @@ public class ConfigurationPartsBuilder { /** * Build the configured hardware crypto modules. - * + * * @return The hardware crypto modules from the configuration. */ - public List buildHardwareCryptoModules() - { - List modules = new ArrayList(); - NodeIterator modIter = XPathUtils.selectNodeIterator( - getConfigElem(), - HARDWARE_CRYPTO_MODULE_XPATH); + public List buildHardwareCryptoModules() { + final List modules = new ArrayList(); + final NodeIterator modIter = XPathUtils.selectNodeIterator( + getConfigElem(), + HARDWARE_CRYPTO_MODULE_XPATH); Element modElem; while ((modElem = (Element) modIter.nextNode()) != null) { - String name = getElementValue(modElem, CONF + "Name", null); - String slotId = getElementValue(modElem, CONF + "SlotId", null); - String userPIN = getElementValue(modElem, CONF + "UserPIN", null); - HardwareCryptoModule module = new HardwareCryptoModule(name, slotId, userPIN); + final String name = getElementValue(modElem, CONF + "Name", null); + final String slotId = getElementValue(modElem, CONF + "SlotId", null); + final String userPIN = getElementValue(modElem, CONF + "UserPIN", null); + final HardwareCryptoModule module = new HardwareCryptoModule(name, slotId, userPIN); modules.add(module); } return modules; } - + /** - * + * * @return */ public boolean allowExternalUris() { - Element permitExtUris = (Element)XPathUtils.selectSingleNode(getConfigElem(), PERMIT_EXTERNAL_URIS_XPATH); - - // if PermitExternalUris element does not exist - don't allow external uris - if (permitExtUris == null) { - // set permitExtUris for iaik-moa - ExternalReferenceChecker.setPermitExternalURLs(false); - return false; - } - else { - // set permitExtUris for iaik-moa - ExternalReferenceChecker.setPermitExternalURLs(true); - return true; - } + final Element permitExtUris = (Element) XPathUtils.selectSingleNode(getConfigElem(), + PERMIT_EXTERNAL_URIS_XPATH); + + // if PermitExternalUris element does not exist - don't allow external uris + if (permitExtUris == null) { + // set permitExtUris for iaik-moa + ExternalReferenceChecker.setPermitExternalURLs(false); + return false; + } else { + // set permitExtUris for iaik-moa + ExternalReferenceChecker.setPermitExternalURLs(true); + return true; + } } - - + /** - * + * * @return */ public List buildPermitExternalUris() { - - info("config.33", null); - - List blacklist = new ArrayList(); - List blackListIaikMoa = new ArrayList(); - - NodeIterator permitExtIter = XPathUtils.selectNodeIterator( - getConfigElem(), - BLACK_LIST_URIS_XPATH); - - Element permitExtElem = null; - while ((permitExtElem = (Element) permitExtIter.nextNode()) != null) { - String host = getElementValue(permitExtElem, CONF + "IP", null); - String port = getElementValue(permitExtElem, CONF + "Port", null); - - BlackListEntry entry =null; - if (port == null) { - entry = new BlackListEntry(host, -1); - info("config.34", new Object[]{host}); - } - else { - entry = new BlackListEntry(host, new Integer(port).intValue()); - info("config.34", new Object[]{host + ":" + port}); - } - - // add entry to iaik-moa blacklist - blackListIaikMoa.add(entry); - - - String array[] = new String[2]; - array[0] = host; - array[1] = port; - blacklist.add(array); - - } - - - // set blacklist for iaik-moa - ExternalReferenceChecker.setBlacklist(blackListIaikMoa); - - - if(blacklist.isEmpty()) // no blacklisted uris given - info("config.36", null); - - - return blacklist; + + info("config.33", null); + + final List blacklist = new ArrayList(); + final List blackListIaikMoa = new ArrayList(); + + final NodeIterator permitExtIter = XPathUtils.selectNodeIterator( + getConfigElem(), + BLACK_LIST_URIS_XPATH); + + Element permitExtElem = null; + while ((permitExtElem = (Element) permitExtIter.nextNode()) != null) { + final String host = getElementValue(permitExtElem, CONF + "IP", null); + final String port = getElementValue(permitExtElem, CONF + "Port", null); + + BlackListEntry entry = null; + if (port == null) { + entry = new BlackListEntry(host, -1); + info("config.34", new Object[] { host }); + } else { + entry = new BlackListEntry(host, new Integer(port).intValue()); + info("config.34", new Object[] { host + ":" + port }); + } + + // add entry to iaik-moa blacklist + blackListIaikMoa.add(entry); + + final String array[] = new String[2]; + array[0] = host; + array[1] = port; + blacklist.add(array); + + } + + // set blacklist for iaik-moa + ExternalReferenceChecker.setBlacklist(blackListIaikMoa); + + if (blacklist.isEmpty()) { + info("config.36", null); + } + + return blacklist; } - + /** - * + * * @return */ public List buildForbidExternalUris() { - - //info("config.47", null); - - List whitelist = new ArrayList(); - List whiteListIaikMoa = new ArrayList(); - - NodeIterator forbidExtIter = XPathUtils.selectNodeIterator( - getConfigElem(), - WHITE_LIST_URIS_XPATH); - - Element permitExtElem = null; - while ((permitExtElem = (Element) forbidExtIter.nextNode()) != null) { - String host = getElementValue(permitExtElem, CONF + "IP", null); - String port = getElementValue(permitExtElem, CONF + "Port", null); - - // WhiteListeEntry - WhiteListEntry entry =null; - if (port == null) { - entry = new WhiteListEntry(host, -1); - info("config.49", new Object[]{host}); + + // info("config.47", null); + + final List whitelist = new ArrayList(); + final List whiteListIaikMoa = new ArrayList(); + + final NodeIterator forbidExtIter = XPathUtils.selectNodeIterator( + getConfigElem(), + WHITE_LIST_URIS_XPATH); + + Element permitExtElem = null; + while ((permitExtElem = (Element) forbidExtIter.nextNode()) != null) { + final String host = getElementValue(permitExtElem, CONF + "IP", null); + final String port = getElementValue(permitExtElem, CONF + "Port", null); + + // WhiteListeEntry + WhiteListEntry entry = null; + if (port == null) { + entry = new WhiteListEntry(host, -1); + info("config.49", new Object[] { host }); + } else { + entry = new WhiteListEntry(host, new Integer(port).intValue()); + info("config.49", new Object[] { host + ":" + port }); } - else { - entry = new WhiteListEntry(host, new Integer(port).intValue()); - info("config.49", new Object[]{host + ":" + port}); - } - - // add entry to iaik-moa whitelist - whiteListIaikMoa.add(entry); - - - String array[] = new String[2]; - array[0] = host; - array[1] = port; - whitelist.add(array); - - } - - - // set whitelist for iaik-moa - ExternalReferenceChecker.setWhitelist(whiteListIaikMoa); - - - if(whitelist.isEmpty()) // no whitelisted uris given - info("config.48", null); - - - return whitelist; + + // add entry to iaik-moa whitelist + whiteListIaikMoa.add(entry); + + final String array[] = new String[2]; + array[0] = host; + array[1] = port; + whitelist.add(array); + + } + + // set whitelist for iaik-moa + ExternalReferenceChecker.setWhitelist(whiteListIaikMoa); + + if (whitelist.isEmpty()) { + info("config.48", null); + } + + return whitelist; } - - /** - * Build the configured hardware keys. - * - * @param keyModules The keyModules that the configuration already knows about. To - * prevent multiple key modules with the same ID. + * Build the configured hardware keys. + * + * @param keyModules The keyModules that the configuration already knows about. + * To prevent multiple key modules with the same ID. * @return The hardware keys contained in the configuration. */ - public List buildHardwareKeyModules(List keyModules) - { - Set existingIds = toIdSet(keyModules); - List hardwareKeys = new ArrayList(); - NodeIterator hkIter = - XPathUtils.selectNodeIterator(getConfigElem(), HARDWARE_KEY_XPATH); + public List buildHardwareKeyModules(List keyModules) { + final Set existingIds = toIdSet(keyModules); + final List hardwareKeys = new ArrayList(); + final NodeIterator hkIter = + XPathUtils.selectNodeIterator(getConfigElem(), HARDWARE_KEY_XPATH); Element keyElem; - while ((keyElem = (Element) hkIter.nextNode()) != null) - { - String id = getElementValue(keyElem, CONF + "Id", null); - String name = getElementValue(keyElem, CONF + "Name", null); - String slotId = getElementValue(keyElem, CONF + "SlotId", null); - String userPIN = getElementValue(keyElem, CONF + "UserPIN", null); + while ((keyElem = (Element) hkIter.nextNode()) != null) { + final String id = getElementValue(keyElem, CONF + "Id", null); + final String name = getElementValue(keyElem, CONF + "Name", null); + final String slotId = getElementValue(keyElem, CONF + "SlotId", null); + final String userPIN = getElementValue(keyElem, CONF + "UserPIN", null); - if (existingIds.contains(id)) - { + if (existingIds.contains(id)) { warn( - "config.04", - new Object[] { "Hardware- oder SoftwareKeyModule", id }); - } - else - { - KeyModule key = new HardwareKeyModule(id, name, slotId, userPIN); + "config.04", + new Object[] { "Hardware- oder SoftwareKeyModule", id }); + } else { + final KeyModule key = new HardwareKeyModule(id, name, slotId, userPIN); hardwareKeys.add(key); existingIds.add(id); } @@ -694,34 +667,29 @@ public class ConfigurationPartsBuilder { /** * Build the configured software keys. - * - * @param keyModules The keyModules that the configuration already knows about. To - * prevent multiple key modules with the same ID. + * + * @param keyModules The keyModules that the configuration already knows about. + * To prevent multiple key modules with the same ID. * * @return The software keys contained in the configuration. */ - public List buildSoftwareKeyModules(List keyModules) - { - Set existingIds = toIdSet(keyModules); - List softwareKeys = new ArrayList(); - NodeIterator skIter = - XPathUtils.selectNodeIterator(getConfigElem(), SOFTWARE_KEY_XPATH); + public List buildSoftwareKeyModules(List keyModules) { + final Set existingIds = toIdSet(keyModules); + final List softwareKeys = new ArrayList(); + final NodeIterator skIter = + XPathUtils.selectNodeIterator(getConfigElem(), SOFTWARE_KEY_XPATH); Element keyElem; - while ((keyElem = (Element) skIter.nextNode()) != null) - { - String id = getElementValue(keyElem, CONF + "Id", null); - String fileName = getElementValue(keyElem, CONF + "FileName", null); - String passWord = getElementValue(keyElem, CONF + "Password", null); + while ((keyElem = (Element) skIter.nextNode()) != null) { + final String id = getElementValue(keyElem, CONF + "Id", null); + final String fileName = getElementValue(keyElem, CONF + "FileName", null); + final String passWord = getElementValue(keyElem, CONF + "Password", null); - if (existingIds.contains(id)) - { + if (existingIds.contains(id)) { warn( - "config.04", - new Object[] { "Hardware- oder SoftwareKeyModule", id }); - } - else - { + "config.04", + new Object[] { "Hardware- oder SoftwareKeyModule", id }); + } else { File keyFile; KeyModule key; @@ -733,7 +701,7 @@ public class ConfigurationPartsBuilder { // check for existence if (!keyFile.exists() || keyFile.isDirectory()) { - warn("config.25", new Object[] { id, keyFile.getAbsolutePath()}); + warn("config.25", new Object[] { id, keyFile.getAbsolutePath() }); } else { // create a new key module key = new SoftwareKeyModule(id, keyFile.getAbsolutePath(), passWord); @@ -748,39 +716,36 @@ public class ConfigurationPartsBuilder { /** * Build the key group configuration. - * - * @param keyModules The KeyModules that the configuration - * knows about. Used to check for errors in the configuration. + * + * @param keyModules The KeyModules that the configuration knows + * about. Used to check for errors in the configuration. * @return The mapping between key group IDs and key groups. */ - public Map buildKeyGroups(List keyModules) - { - Set keyModuleIds = toIdSet(keyModules); - Map keyGroups = new HashMap(); + public Map buildKeyGroups(List keyModules) { + final Set keyModuleIds = toIdSet(keyModules); + final Map keyGroups = new HashMap(); NodeIterator kgIter; Element keyGroupElem; // select all KeyGroup elements and build the KeyGroup objects from them kgIter = XPathUtils.selectNodeIterator(getConfigElem(), KEYGROUP_XPATH); - while ((keyGroupElem = (Element) kgIter.nextNode()) != null) - { + while ((keyGroupElem = (Element) kgIter.nextNode()) != null) { String keyGroupId = getElementValue(keyGroupElem, CONF + "Id", null); - //switch all keyGroupIds to lower case, only - if (MiscUtil.isNotEmpty(keyGroupId)) - keyGroupId = keyGroupId.trim().toLowerCase(); - - String keyGroupDigestMethodAlgorithm = getElementValue(keyGroupElem, CONF + "DigestMethodAlgorithm", null); - Set keyGroupEntries = - buildKeyGroupEntries(keyGroupId, keyModuleIds, keyGroupElem); - KeyGroup keyGroup = new KeyGroup(keyGroupId, keyGroupEntries, keyGroupDigestMethodAlgorithm); + // switch all keyGroupIds to lower case, only + if (MiscUtil.isNotEmpty(keyGroupId)) { + keyGroupId = keyGroupId.trim().toLowerCase(); + } - if (keyGroups.containsKey(keyGroupId)) - { + final String keyGroupDigestMethodAlgorithm = getElementValue(keyGroupElem, CONF + + "DigestMethodAlgorithm", null); + final Set keyGroupEntries = + buildKeyGroupEntries(keyGroupId, keyModuleIds, keyGroupElem); + final KeyGroup keyGroup = new KeyGroup(keyGroupId, keyGroupEntries, keyGroupDigestMethodAlgorithm); + + if (keyGroups.containsKey(keyGroupId)) { warn("config.04", new Object[] { "KeyGroup", keyGroupId }); - } - else - { + } else { keyGroups.put(keyGroup.getId(), keyGroup); } } @@ -790,17 +755,16 @@ public class ConfigurationPartsBuilder { /** * Return the set of IDs contained in the given KeyModules. - * - * @param keyModules The KeyModules from which to extract the - * IDs. + * + * @param keyModules The KeyModules from which to extract the IDs. * @return The IDs from the given KeyModules. */ private Set toIdSet(List keyModules) { - Set ids = new HashSet(); + final Set ids = new HashSet(); Iterator iter; for (iter = keyModules.iterator(); iter.hasNext();) { - KeyModule keyModule = (KeyModule) iter.next(); + final KeyModule keyModule = (KeyModule) iter.next(); ids.add(keyModule.getId()); } @@ -809,35 +773,36 @@ public class ConfigurationPartsBuilder { /** * Build the key entries belonging to a key group. - * - * @param keyGroupId The ID of the key group we are building here. Passed - * for logging purposes. + * + * @param keyGroupId The ID of the key group we are building here. Passed for + * logging purposes. * @param keyModuleIds The IDs of the HardwareKeyModules and - * SoftwareKeyModules that exist in the configuration. + * SoftwareKeyModules that exist in the + * configuration. * @param keyGroupElem The KeyGroup DOM element to parse. * @return A Set of KeyGroupEntry objects. */ private Set buildKeyGroupEntries( - String keyGroupId, - Set keyModuleIds, - Element keyGroupElem) { + String keyGroupId, + Set keyModuleIds, + Element keyGroupElem) { - Set entries = new HashSet(); + final Set entries = new HashSet(); NodeIterator keyEntryIter; Element keyEntryElem; // select all Key elements and put them into the Map keyEntryIter = XPathUtils.selectNodeIterator(keyGroupElem, CONF + "Key"); - while ((keyEntryElem = (Element) keyEntryIter.nextNode()) != null) - { - String keyModuleId = getElementValue(keyEntryElem, CONF + "KeyModuleId", ""); - Element keyCertElem = (Element) XPathUtils.selectSingleNode(keyEntryElem, CONF + "KeyCertIssuerSerial"); - IssuerAndSerial issuerSerial = buildIssuerAndSerial(keyCertElem); + while ((keyEntryElem = (Element) keyEntryIter.nextNode()) != null) { + final String keyModuleId = getElementValue(keyEntryElem, CONF + "KeyModuleId", ""); + final Element keyCertElem = (Element) XPathUtils.selectSingleNode(keyEntryElem, CONF + + "KeyCertIssuerSerial"); + final IssuerAndSerial issuerSerial = buildIssuerAndSerial(keyCertElem); if (!keyModuleIds.contains(keyModuleId)) { warn("config.26", new Object[] { keyGroupId, keyModuleId }); } else if (issuerSerial != null) { - KeyGroupEntry entry = new KeyGroupEntry(keyModuleId, issuerSerial); + final KeyGroupEntry entry = new KeyGroupEntry(keyModuleId, issuerSerial); entries.add(entry); } } @@ -846,34 +811,31 @@ public class ConfigurationPartsBuilder { /** * Build the key group mapping. - * + * * @param keyGroups The available key groups. * @param anonymous The IssuerAndSerial to be used for key group - * mappings not protected by a certificate. + * mappings not protected by a certificate. * @return The key group mapping. */ public Map buildKeyGroupMappings(Map keyGroups, IssuerAndSerial anonymous) { - Map mappings = new HashMap(); + final Map mappings = new HashMap(); NodeIterator mappingIter; Element mappingElem; // select all KeyGroupMapping elements mappingIter = - XPathUtils.selectNodeIterator(getConfigElem(), KEYGROUP_MAPPING_XPATH); + XPathUtils.selectNodeIterator(getConfigElem(), KEYGROUP_MAPPING_XPATH); // build the mapping for each KeyGroupMapping element - while ((mappingElem = (Element) mappingIter.nextNode()) != null) - { - Element issuerSerialElem = (Element) XPathUtils.selectSingleNode(mappingElem, CONF + "CustomerId"); + while ((mappingElem = (Element) mappingIter.nextNode()) != null) { + final Element issuerSerialElem = (Element) XPathUtils.selectSingleNode(mappingElem, CONF + + "CustomerId"); // build the IssuerAndSerial who has access to the key groups IssuerAndSerial issuerAndSerial; - if (issuerSerialElem != null) - { + if (issuerSerialElem != null) { issuerAndSerial = buildIssuerAndSerial(issuerSerialElem); - } - else - { + } else { // IssuerSerial element: the keygroup is generally available issuerAndSerial = anonymous; } @@ -884,8 +846,7 @@ public class ConfigurationPartsBuilder { NodeIterator keyGroupIter; Element keyGroupElem; - if (groups == null) - { + if (groups == null) { // no mapping exist -> build one groups = new HashMap(); mappings.put(issuerAndSerial, groups); @@ -893,16 +854,13 @@ public class ConfigurationPartsBuilder { // select the available key groups and add them to the mapping keyGroupIter = XPathUtils.selectNodeIterator(mappingElem, CONF + "KeyGroupId"); - while ((keyGroupElem = (Element) keyGroupIter.nextNode()) != null) - { - String keyGroupId = getElementValue(keyGroupElem, ".", null); - KeyGroup keyGroup = (KeyGroup) keyGroups.get(keyGroupId.trim().toLowerCase()); - - if (keyGroup != null) - { + while ((keyGroupElem = (Element) keyGroupIter.nextNode()) != null) { + final String keyGroupId = getElementValue(keyGroupElem, ".", null); + final KeyGroup keyGroup = (KeyGroup) keyGroups.get(keyGroupId.trim().toLowerCase()); + + if (keyGroup != null) { groups.put(keyGroupId, keyGroup); - } else - { + } else { warn("config.00", new Object[] { keyGroupId }); } } @@ -914,15 +872,14 @@ public class ConfigurationPartsBuilder { /** * Returns the default chaining mode from the configuration. - * + * * @return The default chaining mode. */ - public String getDefaultChainingMode() - { - String defaultChaining = getElementValue( - getConfigElem(), - CHAINING_MODES_DEFAULT_XPATH, - CM_PKIX); + public String getDefaultChainingMode() { + final String defaultChaining = getElementValue( + getConfigElem(), + CHAINING_MODES_DEFAULT_XPATH, + CM_PKIX); return translateChainingMode(defaultChaining); @@ -930,23 +887,20 @@ public class ConfigurationPartsBuilder { /** * Build the chaining modes for all configured trust anchors. - * + * * @return The mapping from trust anchors to chaining modes. */ - public Map buildChainingModes() - { - Map chainingModes = new HashMap(); - NodeIterator trustIter = XPathUtils.selectNodeIterator(getConfigElem(), TRUST_ANCHOR_XPATH); + public Map buildChainingModes() { + final Map chainingModes = new HashMap(); + final NodeIterator trustIter = XPathUtils.selectNodeIterator(getConfigElem(), TRUST_ANCHOR_XPATH); Element trustAnchorElem; - while ((trustAnchorElem = (Element) trustIter.nextNode()) != null) - { - IssuerAndSerial issuerAndSerial = buildIssuerAndSerial( - (Element)XPathUtils.selectSingleNode(trustAnchorElem, CONF + "Identification")); - String mode = getElementValue(trustAnchorElem, CONF + "Mode", null); + while ((trustAnchorElem = (Element) trustIter.nextNode()) != null) { + final IssuerAndSerial issuerAndSerial = buildIssuerAndSerial( + (Element) XPathUtils.selectSingleNode(trustAnchorElem, CONF + "Identification")); + final String mode = getElementValue(trustAnchorElem, CONF + "Mode", null); - if (issuerAndSerial != null) - { + if (issuerAndSerial != null) { chainingModes.put(issuerAndSerial, translateChainingMode(mode)); } } @@ -956,26 +910,26 @@ public class ConfigurationPartsBuilder { /** * Build an IssuerAndSerial from the DOM representation. - * + * * @param root The root element (being of type dsig: * X509IssuerSerialType. * @return The issuer and serial number contained in the root - * element or null if could not be built for any reason. + * element or null if could not be built for any reason. */ private IssuerAndSerial buildIssuerAndSerial(Element root) { - String issuer = getElementValue(root, ISSUER_XPATH, null); - String serial = getElementValue(root, SERIAL_XPATH, null); + final String issuer = getElementValue(root, ISSUER_XPATH, null); + final String serial = getElementValue(root, SERIAL_XPATH, null); if (issuer != null && serial != null) { try { - RFC2253NameParser nameParser = new RFC2253NameParser(issuer); - Principal issuerDN = nameParser.parse(); + final RFC2253NameParser nameParser = new RFC2253NameParser(issuer); + final Principal issuerDN = nameParser.parse(); return new IssuerAndSerial(issuerDN, new BigInteger(serial)); - } catch (RFC2253NameParserException e) { + } catch (final RFC2253NameParserException e) { warn("config.16", new Object[] { issuer, serial }, e); return null; - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { warn("config.16", new Object[] { issuer, serial }, e); return null; } @@ -986,10 +940,10 @@ public class ConfigurationPartsBuilder { /** * Translate the chaining mode from the configuration file to one used in the * IAIK MOA API. - * + * * @param chainingMode The chaining mode from the configuration. * @return The chaining mode as provided by the ChainingModes - * interface. + * interface. * @see iaik.pki.pathvalidation.ChainingModes */ private String translateChainingMode(String chainingMode) { @@ -1004,55 +958,50 @@ public class ConfigurationPartsBuilder { /** * Build the distribution points mapping. - * + * * @return The mapping from certificate authorities to distribution points. */ - public Map buildDistributionPoints() - { - Map dPs = new HashMap(); + public Map buildDistributionPoints() { + final Map dPs = new HashMap(); NodeIterator dPIter; Element dPElem; - // select all DistributionPoint elements + // select all DistributionPoint elements dPIter = XPathUtils.selectNodeIterator(getConfigElem(), DISTRIBUTION_POINTS_XPATH); - // build the mapping of CA name to distribution points + // build the mapping of CA name to distribution points while ((dPElem = (Element) dPIter.nextNode()) != null) { - String caIssuerDNText = getElementValue(dPElem, CONF + "CAIssuerDN", ""); - RFC2253NameParser nameParser = new RFC2253NameParser(caIssuerDNText); - NodeIterator cRLDPIter = XPathUtils.selectNodeIterator(dPElem, CONF + "CRLDP"); - NodeIterator oCSPDPPIter = XPathUtils.selectNodeIterator(dPElem, CONF + "OCSPDP"); + final String caIssuerDNText = getElementValue(dPElem, CONF + "CAIssuerDN", ""); + final RFC2253NameParser nameParser = new RFC2253NameParser(caIssuerDNText); + final NodeIterator cRLDPIter = XPathUtils.selectNodeIterator(dPElem, CONF + "CRLDP"); + final NodeIterator oCSPDPPIter = XPathUtils.selectNodeIterator(dPElem, CONF + "OCSPDP"); - try - { - String caIssuerDN = nameParser.parse().getName(); + try { + final String caIssuerDN = nameParser.parse().getName(); - // check, if a mapping exists or make a new mapping + // check, if a mapping exists or make a new mapping Set dPsForCA = (Set) dPs.get(caIssuerDN); - if (dPsForCA == null) - { + if (dPsForCA == null) { dPsForCA = new HashSet(); dPs.put(caIssuerDN, dPsForCA); } // add the CRL distribution points of this CA to the set Element cRLDPElem; - while ((cRLDPElem = (Element) cRLDPIter.nextNode()) != null) - { - CRLDistributionPoint cRLDP = (CRLDistributionPoint) buildDistributionPoint(cRLDPElem, caIssuerDN); + while ((cRLDPElem = (Element) cRLDPIter.nextNode()) != null) { + final CRLDistributionPoint cRLDP = (CRLDistributionPoint) buildDistributionPoint(cRLDPElem, + caIssuerDN); dPsForCA.add(cRLDP); } // add the OCSP distribution points of this CA to the set Element oCSPPElem; - while ((oCSPPElem = (Element) oCSPDPPIter.nextNode()) != null) - { - OCSPDistributionPoint oCSPDP = (OCSPDistributionPoint) buildDistributionPoint(oCSPPElem, null); + while ((oCSPPElem = (Element) oCSPDPPIter.nextNode()) != null) { + final OCSPDistributionPoint oCSPDP = (OCSPDistributionPoint) buildDistributionPoint(oCSPPElem, + null); dPsForCA.add(oCSPDP); } -} - catch (RFC2253NameParserException e) - { + } catch (final RFC2253NameParserException e) { warn("config.13", new Object[] { caIssuerDNText }, e); } @@ -1063,143 +1012,126 @@ public class ConfigurationPartsBuilder { /** * Build a distribution point from the DOM representation. - * - * @param dpElem The root element of the distribution point. - * - * @param issuerName The name of the CA issuing the CRL referred to by this DP, or null - * if this DP refers to an OCSP responder. - * + * + * @param dpElem The root element of the distribution point. + * + * @param issuerName The name of the CA issuing the CRL referred to by this DP, + * or null if this DP refers to an OCSP + * responder. + * * @return The distribution point. */ - private DistributionPoint buildDistributionPoint(Element dpElem, String issuerName) - { - String uri = getElementValue(dpElem, CONF + "Location", null); - - if ("CRLDP".equals(dpElem.getLocalName())) - { - NodeIterator reasonCodesIter = XPathUtils.selectNodeIterator(dpElem, CONF + "ReasonCode"); + private DistributionPoint buildDistributionPoint(Element dpElem, String issuerName) { + final String uri = getElementValue(dpElem, CONF + "Location", null); + + if ("CRLDP".equals(dpElem.getLocalName())) { + final NodeIterator reasonCodesIter = XPathUtils.selectNodeIterator(dpElem, CONF + "ReasonCode"); Element reasonCodeElem; - StringBuffer reasonCodesSB = new StringBuffer(); - while ((reasonCodeElem = (Element)reasonCodesIter.nextNode()) != null) - { - if (reasonCodesSB.length() > 0) reasonCodesSB.append(" "); + final StringBuffer reasonCodesSB = new StringBuffer(); + while ((reasonCodeElem = (Element) reasonCodesIter.nextNode()) != null) { + if (reasonCodesSB.length() > 0) { + reasonCodesSB.append(" "); + } reasonCodesSB.append(getElementValue(reasonCodeElem, ".", "").trim()); } return new CRLDistributionPoint(issuerName, uri, reasonCodesSB.toString()); - } - else - { + } else { return new OCSPDistributionPoint(uri); } } /** * Return the CRL archive duration. - * - * @return The value of the CRL archive duration setting from the configuration, or 0 if - * no value is set in the configuration. + * + * @return The value of the CRL archive duration setting from the configuration, + * or 0 if no value is set in the configuration. */ - public int getRevocationArchiveDuration() - { - String archiveDuration = getElementValue(getConfigElem(), CRL_ARCHIVE_DURATION_XPATH, null); - try - { + public int getRevocationArchiveDuration() { + final String archiveDuration = getElementValue(getConfigElem(), CRL_ARCHIVE_DURATION_XPATH, null); + try { return Integer.parseInt(archiveDuration); - } - catch (NumberFormatException e) - { + } catch (final NumberFormatException e) { warn("config.01", null); return 365; } } /** - * Build the CreateTransformsInfoProfiles. - * + * Build the CreateTransformsInfoProfiles. + * * @return The mapping from profile ID to profile. */ - public Map buildCreateTransformsInfoProfiles() - { + public Map buildCreateTransformsInfoProfiles() { return loadProfiles(CREATE_TRANSFORMS_INFO_PROFILE_XPATH, "CreateTransformsInfoProfile"); } /** * Build the CreateSignatureEnvironmentProfiles. - * + * * @return The mapping from profile ID to profile. */ - public Map buildCreateSignatureEnvironmentProfiles() - { + public Map buildCreateSignatureEnvironmentProfiles() { return loadProfiles(CREATE_SIGNATURE_ENVIRONMENT_PROFILE_XPATH, "CreateSignatureEnvironmentProfile"); } /** * Build the VerifyTransformsInfoProfiles. - * + * * @return The mapping from profile ID to profile. */ - public Map buildVerifyTransformsInfoProfiles() - { + public Map buildVerifyTransformsInfoProfiles() { return loadProfiles(VERIFY_TRANSFORMS_INFO_PROFILE_XPATH, "VerifyTransformsInfoProfile"); } /** * Build the SupplementProfiles. - * + * * @return The mapping from profile ID to profile. */ - public Map buildSupplementProfiles() - { + public Map buildSupplementProfiles() { return loadProfiles(SUPPLEMENT_PROFILE_XPATH, "SupplementProfile"); } /** * Load a profile mapping. - * - * @param xpath The XPath to select the profiles from the configuration. - * + * + * @param xpath The XPath to select the profiles from the configuration. + * * @param profileRoot The name of the profile root element. - * + * * @return Map The profile ID to profile mapping. */ - private Map loadProfiles(String xpath, String profileRoot) - { - Map profiles = new HashMap(); - NodeIterator profileIter = XPathUtils.selectNodeIterator(getConfigElem(), xpath); + private Map loadProfiles(String xpath, String profileRoot) { + final Map profiles = new HashMap(); + final NodeIterator profileIter = XPathUtils.selectNodeIterator(getConfigElem(), xpath); Element profileElem; - while ((profileElem = (Element) profileIter.nextNode()) != null) - { - String id = getElementValue(profileElem, CONF + "Id", null); - String fileName = getElementValue(profileElem, CONF + "Location", null); + while ((profileElem = (Element) profileIter.nextNode()) != null) { + final String id = getElementValue(profileElem, CONF + "Id", null); + final String fileName = getElementValue(profileElem, CONF + "Location", null); - if (profiles.containsKey(id)) - { + if (profiles.containsKey(id)) { warn("config.04", new Object[] { profileRoot, id }); - } - else - { - try - { + } else { + try { File profileFile = new File(fileName); // make profileFile absolute - if (!profileFile.isAbsolute()) profileFile = new File(configRoot_, fileName); + if (!profileFile.isAbsolute()) { + profileFile = new File(configRoot_, fileName); + } // load the profile - info("config.22", new Object[] { profileRoot, id, profileFile.getAbsoluteFile()}); - Element profile = loadProfile(profileFile); + info("config.22", new Object[] { profileRoot, id, profileFile.getAbsoluteFile() }); + final Element profile = loadProfile(profileFile); - if (Constants.MOA_NS_URI.equals(profile.getNamespaceURI()) && - profile.getLocalName().equals(profileRoot)) - { + if (Constants.MOA_NS_URI.equals(profile.getNamespaceURI()) && + profile.getLocalName().equals(profileRoot)) { profiles.put(id, profile); - } - else - { + } else { warn("config.02", new Object[] { profileRoot, id, fileName }); } - } catch (ConfigurationException e) { + } catch (final ConfigurationException e) { warn("config.03", new Object[] { profileRoot, id }); } } @@ -1210,8 +1142,9 @@ public class ConfigurationPartsBuilder { /** * Load a profile from a file. - * - * @param root The absolute directory path of the main configuration file. + * + * @param root The absolute directory path of the main configuration + * file. * @param profileFile The file containing the profile. * @return The profile in its DOM representation. * @throws ConfigurationException An error occurred loading the profile. @@ -1222,7 +1155,7 @@ public class ConfigurationPartsBuilder { try { profile = parseXml(new FileInputStream(profileFile)); - } catch (Exception e) { + } catch (final Exception e) { throw new ConfigurationException("config.12", null, e); } @@ -1231,146 +1164,136 @@ public class ConfigurationPartsBuilder { /** * Build the trust profile mapping. - * + * * @return The profile ID to profile mapping. */ - - public Map buildTrustProfiles() - { - Map trustProfiles = new HashMap(); - NodeIterator profileIter = XPathUtils.selectNodeIterator(getConfigElem(), TRUST_PROFILE_XPATH); + + public Map buildTrustProfiles() { + final Map trustProfiles = new HashMap(); + final NodeIterator profileIter = XPathUtils.selectNodeIterator(getConfigElem(), TRUST_PROFILE_XPATH); Element profileElem; - while ((profileElem = (Element) profileIter.nextNode()) != null) { - //load basic TrustProfile information - - //check TrustProfileId - String id = getElementValue(profileElem, CONF + "Id", null); - if (MiscUtil.isEmpty(id)) { - warn("config.52", new Object[]{"Id des TrustProfiles ist leer."}); - continue; - - } - //cast profileId to lowercase (changed in 3.0.1) - id = id.trim().toLowerCase(); - if (trustProfiles.containsKey(id)) { - warn("config.04", new Object[] { "TrustProfile", id }); + while ((profileElem = (Element) profileIter.nextNode()) != null) { + // load basic TrustProfile information + + // check TrustProfileId + String id = getElementValue(profileElem, CONF + "Id", null); + if (MiscUtil.isEmpty(id)) { + warn("config.52", new Object[] { "Id des TrustProfiles ist leer." }); + continue; + + } + // cast profileId to lowercase (changed in 3.0.1) + id = id.trim().toLowerCase(); + if (trustProfiles.containsKey(id)) { + warn("config.04", new Object[] { "TrustProfile", id }); + continue; + } + + // check location of TrustAnchor directory + final String trustAnchorsLocStr = getElementValue(profileElem, CONF + "TrustAnchorsLocation", null); + URI trustAnchorsLocURI = null; + try { + trustAnchorsLocURI = new URI(trustAnchorsLocStr); + if (!trustAnchorsLocURI.isAbsolute()) { // make it absolute to the config file + trustAnchorsLocURI = new URI(configRoot_.toURL() + trustAnchorsLocStr); + } + } catch (final URIException e) { + warn("config.14", new Object[] { "uri", id, trustAnchorsLocStr }, e); + continue; + } catch (final MalformedURLException e) { + warn("config.15", new Object[] { id }, e); + continue; + } + final File profileDir = new File(trustAnchorsLocURI.getPath()); + if (!profileDir.exists() || !profileDir.isDirectory()) { + warn("config.27", new Object[] { "uri", id }); + continue; + } + + // check signerCertsLocation URL + String signerCertsLocStr = getElementValue(profileElem, CONF + "SignerCertsLocation", null); + URI signerCertsLocURI = null; + if (signerCertsLocStr != null && !"".equals(signerCertsLocStr)) { + try { + signerCertsLocURI = new URI(signerCertsLocStr); + if (!signerCertsLocURI.isAbsolute()) { + signerCertsLocURI = new URI(configRoot_.toURL() + signerCertsLocStr); + } + + final File signerCertsDir = new File(signerCertsLocURI.getPath()); + if (!signerCertsDir.exists() || !signerCertsDir.isDirectory()) { + warn("config.27", new Object[] { "signerCertsUri", id }); continue; - } - - //check location of TrustAnchor directory - String trustAnchorsLocStr = getElementValue(profileElem, CONF + "TrustAnchorsLocation", null); - URI trustAnchorsLocURI = null; - try - { - trustAnchorsLocURI = new URI(trustAnchorsLocStr); - if (!trustAnchorsLocURI.isAbsolute()) { // make it absolute to the config file - trustAnchorsLocURI = new URI(configRoot_.toURL() + trustAnchorsLocStr); } - } - catch (URIException e) { - warn("config.14", new Object[] { "uri", id, trustAnchorsLocStr }, e); - continue; - } - catch (MalformedURLException e) - { - warn("config.15", new Object[] {id}, e); + } catch (final URIException e) { + warn("config.14", new Object[] { "signerCertsUri", id, trustAnchorsLocStr }, e); continue; - } - File profileDir = new File(trustAnchorsLocURI.getPath()); - if (!profileDir.exists() || !profileDir.isDirectory()) { - warn("config.27", new Object[] { "uri", id }); + } catch (final MalformedURLException e) { + warn("config.15", new Object[] { id }, e); continue; } + } + signerCertsLocStr = signerCertsLocURI != null ? signerCertsLocURI.toString() : null; + + // check if TSL support is enabled + final Element eutslElem = (Element) XPathUtils.selectSingleNode(profileElem, CONF + "EUTSL"); + boolean tslEnabled = false; + if (eutslElem != null) { + tslEnabled = true; + } + + // load TSL configuration + final String countries = getElementValue(profileElem, CONF + "EUTSL" + "/" + CONF + "CountrySelection", + null); + final String allowedTspStatus = getElementValue(profileElem, CONF + "EUTSL" + "/" + CONF + + "AllowedTSPStatus", null); + final String allowedTspServiceTypes = getElementValue(profileElem, CONF + "EUTSL" + "/" + CONF + + "AllowedTSPServiceTypes", null); + + // create profile configuration + final TrustProfile profile = new TrustProfile(id, trustAnchorsLocURI.toString(), signerCertsLocStr, + tslEnabled, countries, allowedTspStatus, allowedTspServiceTypes); + trustProfiles.put(id, profile); - //check signerCertsLocation URL - String signerCertsLocStr = getElementValue(profileElem, CONF + "SignerCertsLocation", null); - URI signerCertsLocURI = null; - if (signerCertsLocStr != null && !"".equals(signerCertsLocStr)) - { - try - { - signerCertsLocURI = new URI(signerCertsLocStr); - if (!signerCertsLocURI.isAbsolute()) signerCertsLocURI = new URI(configRoot_.toURL() + signerCertsLocStr); - - File signerCertsDir = new File(signerCertsLocURI.getPath()); - if (!signerCertsDir.exists() || !signerCertsDir.isDirectory()) { - warn("config.27", new Object[] { "signerCertsUri", id }); - continue; - } - } - catch (URIException e) { - warn("config.14", new Object[] { "signerCertsUri", id, trustAnchorsLocStr }, e); - continue; - } - catch (MalformedURLException e) { - warn("config.15", new Object[] {id}, e); - continue; - } - } - signerCertsLocStr = (signerCertsLocURI != null) ? signerCertsLocURI.toString() : null; - - - //check if TSL support is enabled - Element eutslElem = (Element) XPathUtils.selectSingleNode(profileElem, CONF + "EUTSL"); - boolean tslEnabled = false; - if (eutslElem != null) //EUTSL element found --> TSL enabled - tslEnabled = true; - - //load TSL configuration - String countries = getElementValue(profileElem, CONF + "EUTSL" + "/" + CONF + "CountrySelection", null); - String allowedTspStatus = getElementValue(profileElem, CONF + "EUTSL" + "/" + CONF + "AllowedTSPStatus", null); - String allowedTspServiceTypes = getElementValue(profileElem, CONF + "EUTSL" + "/" + CONF + "AllowedTSPServiceTypes", null); - - - //create profile configuration - TrustProfile profile = new TrustProfile(id, trustAnchorsLocURI.toString(), signerCertsLocStr, - tslEnabled, countries, allowedTspStatus, allowedTspServiceTypes); - trustProfiles.put(id, profile); - } return trustProfiles; } - + /** * Returns the location of the certificate store. - * + * * @return the location of the certificate store. */ - public String getCertStoreLocation() - { - String certStoreLocStr = getElementValue(getConfigElem(), CERTSTORE_LOCATION_XPATH, null); + public String getCertStoreLocation() { + final String certStoreLocStr = getElementValue(getConfigElem(), CERTSTORE_LOCATION_XPATH, null); File certStoreLocFile; - - // No value specified in configuration file: Set it to a reasonable (absolute) default - if (certStoreLocStr == null) - return new File(configRoot_, "certstore").getAbsolutePath(); - + + // No value specified in configuration file: Set it to a reasonable (absolute) + // default + if (certStoreLocStr == null) { + return new File(configRoot_, "certstore").getAbsolutePath(); + } + // Make cert store location an absolute value certStoreLocFile = new File(certStoreLocStr); - if (!certStoreLocFile.isAbsolute()) - { + if (!certStoreLocFile.isAbsolute()) { certStoreLocFile = new File(configRoot_, certStoreLocStr); } - + // Check if cert store location exists, eventually try to create it - if (!certStoreLocFile.isDirectory()) - { + if (!certStoreLocFile.isDirectory()) { boolean created = false; - try - { + try { created = certStoreLocFile.mkdirs(); - } - finally - { - if (!created) - { + } finally { + if (!created) { warn("config.32", new Object[] { certStoreLocFile.getAbsolutePath() }); } } } - + return certStoreLocFile.getAbsolutePath(); } @@ -1380,437 +1303,429 @@ public class ConfigurationPartsBuilder { /** * Parse a configuration XML file. - * + * * @param inputStream The stream from which to read the XML data. * @return The DOM representation of the XML data. * @throws ParserConfigurationException XML parser not configured properly. - * @throws SAXException An error parsing the XML file. - * @throws IOException An error reading the stream. + * @throws SAXException An error parsing the XML file. + * @throws IOException An error reading the stream. */ private static Element parseXml(InputStream inputStream) - throws ParserConfigurationException, SAXException, IOException { + throws ParserConfigurationException, SAXException, IOException { return DOMUtils - .parseDocument(inputStream, true, Constants.ALL_SCHEMA_LOCATIONS, null) - .getDocumentElement(); + .parseDocument(inputStream, true, Constants.ALL_SCHEMA_LOCATIONS, null) + .getDocumentElement(); } /** * Return the value of an element located by an XPath. - * - * @param root The root element from which to evaluate the xpath. + * + * @param root The root element from which to evaluate the xpath. * @param xpath The XPath pointing to the element. - * @param def The default value, if no element can be found with the given - * xpath. + * @param def The default value, if no element can be found with the given + * xpath. * @return The element value or def, if the element cannot be - * found. + * found. */ private String getElementValue(Element root, String xpath, String def) { - Element elem = (Element) XPathUtils.selectSingleNode(root, xpath); + final Element elem = (Element) XPathUtils.selectSingleNode(root, xpath); return elem != null ? DOMUtils.getText(elem) : def; } /** * Return the value of an attribute located by an XPath. - * - * @param root The root element from which to evaluate the xpath. + * + * @param root The root element from which to evaluate the xpath. * @param xpath The XPath pointing to the attribute. - * @param def The default value, if no attribute can be found with the given - * xpath. + * @param def The default value, if no attribute can be found with the given + * xpath. * @return The element value or def, if the attribute cannot be - * found. + * found. */ private String getAttributeValue(Element root, String xpath, String def) { - Attr attr = (Attr) XPathUtils.selectSingleNode(root, xpath); + final Attr attr = (Attr) XPathUtils.selectSingleNode(root, xpath); return attr != null ? attr.getValue() : def; } /** * Log an info message. - * - * @param messageId The message ID. + * + * @param messageId The message ID. * @param parameters Additional parameters for the message. * @see at.gv.egovernment.moa.spss.server.util.MessageProvider */ private static void info(String messageId, Object[] parameters) { - MessageProvider msg = MessageProvider.getInstance(); + final MessageProvider msg = MessageProvider.getInstance(); Logger.info(new LogMsg(msg.getMessage(messageId, parameters))); } /** * Log a warning. - * + * * @param messageId The message ID. - * @param args Additional parameters for the message. + * @param args Additional parameters for the message. * @see at.gv.egovernment.moa.spss.server.util.MessageProvider */ private void warn(String messageId, Object[] args) { - MessageProvider msg = MessageProvider.getInstance(); - String txt = msg.getMessage(messageId, args); + final MessageProvider msg = MessageProvider.getInstance(); + final String txt = msg.getMessage(messageId, args); Logger.warn(new LogMsg(txt)); warnings.add(txt); } - + /** * Log a warning. - * + * * @param messageId The message ID. - * @param args Additional parameters for the message. + * @param args Additional parameters for the message. * @see at.gv.egovernment.moa.spss.server.util.MessageProvider */ private void debug(String messageId, Object[] args) { - MessageProvider msg = MessageProvider.getInstance(); - String txt = msg.getMessage(messageId, args); + final MessageProvider msg = MessageProvider.getInstance(); + final String txt = msg.getMessage(messageId, args); Logger.debug(new LogMsg(txt)); - + } - /** * Log a debug message. - * + * * @param messageId The message ID. - * @param args Additional parameters for the message. + * @param args Additional parameters for the message. * @see at.gv.egovernment.moa.spss.server.util.MessageProvider */ private void debug(String message) { Logger.debug(new LogMsg(message)); } - + /** * Log a warning. - * + * * @param messageId The message ID. - * @param args Additional parameters for the message. - * @param t An exception being the cause of the warning. + * @param args Additional parameters for the message. + * @param t An exception being the cause of the warning. * @see at.gv.egovernment.moa.spss.server.util.MessageProvider */ private void warn(String messageId, Object[] args, Throwable t) { - MessageProvider msg = MessageProvider.getInstance(); - String txt = msg.getMessage(messageId, args); + final MessageProvider msg = MessageProvider.getInstance(); + final String txt = msg.getMessage(messageId, args); - Logger.warn(new LogMsg(txt), t); + Logger.warn(new LogMsg(txt), t); warnings.add(txt); } /** * Log an error. - * + * * @param messageId The message ID. - * @param args Additional parameters for the message. + * @param args Additional parameters for the message. * @see at.gv.egovernment.moa.spss.server.util.MessageProvider */ private void error(String messageId, Object[] args) { - MessageProvider msg = MessageProvider.getInstance(); - String txt = msg.getMessage(messageId, args); + final MessageProvider msg = MessageProvider.getInstance(); + final String txt = msg.getMessage(messageId, args); Logger.error(new LogMsg(txt)); warnings.add(txt); } - + /** * Log an error. - * + * * @param messageId The message ID. - * @param args Additional parameters for the message. - * @param t An exception being the cause of the warning. + * @param args Additional parameters for the message. + * @param t An exception being the cause of the warning. * @see at.gv.egovernment.moa.spss.server.util.MessageProvider */ private void error(String messageId, Object[] args, Throwable t) { - MessageProvider msg = MessageProvider.getInstance(); - String txt = msg.getMessage(messageId, args); + final MessageProvider msg = MessageProvider.getInstance(); + final String txt = msg.getMessage(messageId, args); - Logger.error(new LogMsg(txt), t); + Logger.error(new LogMsg(txt), t); warnings.add(txt); } - + /** * Returns whether revocation information should be archived. - * + * * @return whether revocation information should be archived. */ - public boolean getEnableRevocationArchiving() - { - String enableArchiving = getElementValue(getConfigElem(), ENABLE_ARCHIVING_XPATH, null); + public boolean getEnableRevocationArchiving() { + final String enableArchiving = getElementValue(getConfigElem(), ENABLE_ARCHIVING_XPATH, null); return Boolean.valueOf(enableArchiving).booleanValue(); } /** * Returns the JDBC URL for the revocation archive database. - * - * @return the JDBC URL for the revocation archive database, or nullnullnullnullConfiguration data is read from an XML file, whose location is given by - * the moa.spss.server.configuration system property.

- *

This class implements the Singleton pattern. The reload() - * method can be used to update the configuration data. Therefore, it is not - * guaranteed that consecutive calls to getInstance() will return - * the same ConfigurationProvider all the time. During the - * processing of a web service request, the current - * TransactionContext should be used to obtain the - * ConfigurationProvider local to that request.

- * + * + *

+ * Configuration data is read from an XML file, whose location is given by the + * moa.spss.server.configuration system property. + *

+ *

+ * This class implements the Singleton pattern. The reload() method + * can be used to update the configuration data. Therefore, it is not guaranteed + * that consecutive calls to getInstance() will return the same + * ConfigurationProvider all the time. During the processing of a + * web service request, the current TransactionContext should be + * used to obtain the ConfigurationProvider local to that request. + *

+ * * @author Patrick Peck * @author Sven Aigner * @version $Id$ */ -public class ConfigurationProvider -{ - /** - * The name of the system property which contains the file name of the +public class ConfigurationProvider { + /** + * The name of the system property which contains the file name of the * configuration file. */ public static final String CONFIG_PROPERTY_NAME = - "moa.spss.server.configuration"; + "moa.spss.server.configuration"; - /** + /** * A fake IssuerAndSerial object for storing KeyGroup information * accessible by all clients. */ private static final IssuerAndSerial ANONYMOUS_ISSUER_SERIAL = - new IssuerAndSerial(new Name(), new BigInteger("0")); + new IssuerAndSerial(new Name(), new BigInteger("0")); /** Singleton instance. null, if none has been created. */ private static ConfigurationProvider instance; @@ -101,23 +100,23 @@ public class ConfigurationProvider /** The default canonicalization algorithm name */ private String canonicalizationAlgorithmName; - + /** The XAdES version used for signature creation */ private String xadesVersion; - + /** PDF AS Configuration */ private String pdfAsConfiguration; - + private int connectionTimeout; private int readTimeout; - - /** - * A List of HardwareCryptoModule objects for + + /** + * A List of HardwareCryptoModule objects for * configuring hardware modules. */ private List hardwareCryptoModules; - /** + /** * A List of HardwareKey objects containing the * configuration data for hardware keys. */ @@ -144,29 +143,29 @@ public class ConfigurationProvider /** The default chaining mode. */ private String defaultChainingMode; - /** + /** * A Map which contains the IssuerAndSerial to * chaining mode (a String) mapping. */ private Map chainingModes; /** - * A Map which contains the CAIssuerDN (a String) - * to distribution points (a Set of - * DistributionPoints) mapping. + * A Map which contains the CAIssuerDN (a String) to + * distribution points (a Set of DistributionPoints) + * mapping. */ private Map distributionPoints; - /** - * The CRL archive duration. + /** + * The CRL archive duration. */ private int cRLArchiveDuration; - + /** * Indicates whether revocation information should be archived. */ private boolean enableRevocationArchiving_; - + /** * The location of the certificate store. */ @@ -180,29 +179,29 @@ public class ConfigurationProvider private Map createSignatureEnvironmentProfiles; /** - * A Map which contains a mapping from - * CreateTransformsInfoProfile Ids (String) to - * CreateTransformsInfoProfile elements (an Element). + * A Map which contains a mapping from CreateTransformsInfoProfile + * Ids (String) to CreateTransformsInfoProfile elements (an + * Element). */ private Map createTransformsInfoProfiles; /** - * A Map which contains a mapping from - * VerifyTransformsInfoProfile Ids (String) to - * VerifyTransformsInfoProfile elements (an Element). + * A Map which contains a mapping from VerifyTransformsInfoProfile + * Ids (String) to VerifyTransformsInfoProfile elements (an + * Element). */ private Map verifyTransformsInfoProfiles; /** - * A Map which contains a mapping from - * SupplementProfile Ids (String) to SupplementProfile elements - * (an Element). + * A Map which contains a mapping from SupplementProfile Ids + * (String) to SupplementProfile elements (an + * Element). */ private Map supplementProfiles; /** - * A Map which contains a TrustProfile Id (a String - * to trust profile (a TrustProfile) mapping. + * A Map which contains a TrustProfile Id (a String to + * trust profile (a TrustProfile) mapping. */ private Map trustProfiles; @@ -222,7 +221,8 @@ public class ConfigurationProvider private boolean enableRevocationChecking_; /** - * The maximum age of a revocation information for considering it still as valid. + * The maximum age of a revocation information for considering it still as + * valid. */ private long maxRevocationAge_; @@ -232,63 +232,58 @@ public class ConfigurationProvider private String[] serviceOrder_; private boolean adesFormResults; - + /** - * Indicates whether certificates found during certificate path construction + * Indicates whether certificates found during certificate path construction * should be added to the certificate store. */ private boolean autoAddCertificates_; - private boolean autoAddEECertificates_; - - + /** - * Indicates whether the certificate extension Authority Info Access should - * be used during certificate path construction. + * Indicates whether the certificate extension Authority Info Access should be + * used during certificate path construction. */ private boolean useAuthorityInfoAccess_; /** - * Indicates whether file URIs are allowed or not + * Indicates whether file URIs are allowed or not */ private boolean permitFileURIs; - + /** * Indicates the CRL retention intervals */ private Map crlRetentionIntervals; - + /** * Indicates wether external URIs are allowed or not */ private boolean allowExternalUris_; - + /** * A List of black listed URIs (host and port) */ private List blackListedUris_; - + /** * A List of white listed URIs (host and port) */ private List whiteListedUris_; - + /** * A TSLConfiguration that represents the global TSL configuration */ private TSLConfiguration tslconfiguration_; - - - /** * Return the single instance of configuration data. - * + * * @return MOAConfigurationProvider The current configuration data. * @throws ConfigurationException Failure to load the configuration data. */ public static synchronized ConfigurationProvider getInstance() - throws ConfigurationException { + throws ConfigurationException { if (instance == null) { reload(); @@ -298,21 +293,21 @@ public class ConfigurationProvider /** * Reload the configuration data and set it if successful. - * + * * @return MOAConfigurationProvider The loaded configuration data. * @throws ConfigurationException Failure to load the configuration data. */ public static synchronized ConfigurationProvider reload() - throws ConfigurationException { + throws ConfigurationException { String fileName = System.getProperty(CONFIG_PROPERTY_NAME); if (fileName == null) { // find out where we are running and use the configuration provided // under WEB-INF/conf/moa-spss/MOA-SPSSConfiguration - URL url = ConfigurationProvider.class.getResource("/"); + final URL url = ConfigurationProvider.class.getResource("/"); fileName = - new File(url.getPath()).getParent() - + "/conf/moa-spss/MOA-SPSSConfiguration.xml"; + new File(url.getPath()).getParent() + + "/conf/moa-spss/MOA-SPSSConfiguration.xml"; info("config.05", new Object[] { CONFIG_PROPERTY_NAME }); } @@ -322,7 +317,7 @@ public class ConfigurationProvider /** * Constructor for ConfigurationProvider. - * + * * @param fileName The name of the configuration file. * @throws ConfigurationException An error occurred loading the configuration. */ @@ -331,12 +326,11 @@ public class ConfigurationProvider } /** - * Load the configuration data from XML file with the given name and build - * the internal data structures representing the MOA configuration. - * + * Load the configuration data from XML file with the given name and build the + * internal data structures representing the MOA configuration. + * * @param fileName The name of the XML file to load. - * @throws ConfigurationException The MOA configuration could not be - * read/built. + * @throws ConfigurationException The MOA configuration could not be read/built. */ private void load(String fileName) throws ConfigurationException { FileInputStream stream = null; @@ -345,16 +339,15 @@ public class ConfigurationProvider Element configElem; ConfigurationPartsBuilder builder; List allKeyModules; - // load the main config file try { configFile = new File(fileName); configRoot = new File(configFile.getParent()); - info("config.21", new Object[] { configFile.getAbsoluteFile()}); + info("config.21", new Object[] { configFile.getAbsoluteFile() }); stream = new FileInputStream(fileName); configElem = DOMUtils.parseXmlValidating(new FileInputStream(fileName)); - } catch (Throwable t) { + } catch (final Throwable t) { throw new ConfigurationException("config.10", null, t); } @@ -362,30 +355,29 @@ public class ConfigurationProvider try { builder = new ConfigurationPartsBuilder(configElem, configRoot); - //build TSL configuration + // build TSL configuration tslconfiguration_ = builder.getTSLConfiguration(); - - //build TrustProfile configuration - trustProfiles = builder.buildTrustProfiles(); - - //check TSL configuration + + // build TrustProfile configuration + trustProfiles = builder.buildTrustProfiles(); + + // check TSL configuration checkTSLConfiguration(); - - + digestMethodAlgorithmName = builder.getDigestMethodAlgorithmName(); canonicalizationAlgorithmName = - builder.getCanonicalizationAlgorithmName(); + builder.getCanonicalizationAlgorithmName(); hardwareCryptoModules = builder.buildHardwareCryptoModules(); hardwareKeyModules = - builder.buildHardwareKeyModules(Collections.EMPTY_LIST); + builder.buildHardwareKeyModules(Collections.EMPTY_LIST); softwareKeyModules = - builder.buildSoftwareKeyModules(hardwareKeyModules); + builder.buildSoftwareKeyModules(hardwareKeyModules); allKeyModules = new ArrayList(hardwareKeyModules); allKeyModules.addAll(softwareKeyModules); keyGroups = builder.buildKeyGroups(allKeyModules); keyGroupMappings = - builder.buildKeyGroupMappings(keyGroups, ANONYMOUS_ISSUER_SERIAL); - + builder.buildKeyGroupMappings(keyGroups, ANONYMOUS_ISSUER_SERIAL); + connectionTimeout = builder.getConnectionTimeout(); readTimeout = builder.getReadTimeout(); pdfAsConfiguration = builder.getPDFASConfiguration(); @@ -396,9 +388,9 @@ public class ConfigurationProvider useAuthorityInfoAccess_ = builder.getUseAuthorityInfoAccess(); autoAddCertificates_ = builder.getAutoAddCertificates(); autoAddEECertificates_ = builder.getAutoEEAddCertificates(); - //trustProfiles = builder.buildTrustProfiles(tslconfiguration_.getWorkingDirectory()); - - + // trustProfiles = + // builder.buildTrustProfiles(tslconfiguration_.getWorkingDirectory()); + distributionPoints = builder.buildDistributionPoints(); enableRevocationChecking_ = builder.getEnableRevocationChecking(); maxRevocationAge_ = builder.getMaxRevocationAge(); @@ -407,12 +399,10 @@ public class ConfigurationProvider cRLArchiveDuration = builder.getRevocationArchiveDuration(); revocationArchiveJDBCURL_ = builder.getRevocationArchiveJDBCURL(); revocationArchiveJDBCDriverClass_ = builder.getRevocationArchiveJDBCDriverClass(); - - - //TODO!!!! + + // TODO!!!! certStoreLocation_ = builder.getCertStoreLocation(); - - + createTransformsInfoProfiles = builder.buildCreateTransformsInfoProfiles(); createSignatureEnvironmentProfiles = builder.buildCreateSignatureEnvironmentProfiles(); verifyTransformsInfoProfiles = builder.buildVerifyTransformsInfoProfiles(); @@ -421,41 +411,37 @@ public class ConfigurationProvider permitFileURIs = builder.getPermitFileURIs(); crlRetentionIntervals = builder.getCrlRetentionIntervals(); - allowExternalUris_= builder.allowExternalUris(); - - if (allowExternalUris_) { - blackListedUris_ = builder.buildPermitExternalUris(); - whiteListedUris_ = null; - } - else { - info("config.35", null); - blackListedUris_ = null; - whiteListedUris_ = builder.buildForbidExternalUris(); + allowExternalUris_ = builder.allowExternalUris(); + + if (allowExternalUris_) { + blackListedUris_ = builder.buildPermitExternalUris(); + whiteListedUris_ = null; + } else { + info("config.35", null); + blackListedUris_ = null; + whiteListedUris_ = builder.buildForbidExternalUris(); } - - - + // Set set = crlRetentionIntervals.entrySet(); // Iterator i = set.iterator(); // while(i.hasNext()){ // Map.Entry me = (Map.Entry)i.next(); // System.out.println("Key: " + me.getKey() + " - Value: " + me.getValue() ); // } - - - } catch (Throwable t) { + + } catch (final Throwable t) { throw new ConfigurationException("config.11", null, t); } finally { try { if (stream != null) { stream.close(); } - } catch (IOException e) { + } catch (final IOException e) { // don't complain about this } } } - + // private boolean checkTSLenableTrustprofilesExist()throws ConfigurationException { // boolean bTSLEnabledTPExist = false; // Iterator it = trustProfiles.entrySet().iterator(); @@ -465,78 +451,75 @@ public class ConfigurationProvider // if (tp.isTSLEnabled()) // bTSLEnabledTPExist = bTSLEnabledTPExist || true; // } -// +// // return bTSLEnabledTPExist; -// +// // } - - private void checkTSLConfiguration() throws ConfigurationException { - boolean bTSLEnabledTPExist = false; - Iterator it = trustProfiles.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry pairs = (Map.Entry)it.next(); - TrustProfile tp = (TrustProfile) pairs.getValue(); - if (tp.isTSLEnabled()) - bTSLEnabledTPExist = bTSLEnabledTPExist || true; - } - - if (!bTSLEnabledTPExist) { - // if no trustprofile has TSL support enabled, delete TSL configuration - tslconfiguration_ = null; - return; - } - - if (bTSLEnabledTPExist && (tslconfiguration_ == null)) { - error("config.40", null); - throw new ConfigurationException("config.40", null); - } - - File workingDir = new File(tslconfiguration_.getWorkingDirectory()); - File eu_trust = new File(workingDir.getAbsolutePath() + "/trust/eu"); - if (!eu_trust.exists()) { - error("config.51", new Object[] {"Verzeichnis \"trust/eu\" existiert nicht"}); - throw new ConfigurationException("config.51", new Object[] {"Verzeichnis \"trust/eu\" existiert nicht"}); - } - else { - File[] eutrustFiles = eu_trust.listFiles(); - if (eutrustFiles == null) { - error("config.51", new Object[] {"Verzeichnis \"trust/eu\" ist leer"}); - throw new ConfigurationException("config.51", new Object[] {"Verzeichnis \"trust/eu\" ist leer"}); - } - else { - if (eutrustFiles.length == 0) { - error("config.51", new Object[] {"Verzeichnis \"trust/eu\" ist leer"}); - throw new ConfigurationException("config.51", new Object[] {"Verzeichnis \"trust/eu\" ist leer"}); - } - } - - } - - File hashcache = new File(tslconfiguration_.getWorkingDirectory(), "hashcache"); - if (!hashcache.exists()) { - hashcache.mkdir(); + + private void checkTSLConfiguration() throws ConfigurationException { + boolean bTSLEnabledTPExist = false; + final Iterator it = trustProfiles.entrySet().iterator(); + while (it.hasNext()) { + final Map.Entry pairs = (Map.Entry) it.next(); + final TrustProfile tp = (TrustProfile) pairs.getValue(); + if (tp.isTSLEnabled()) { + bTSLEnabledTPExist = bTSLEnabledTPExist || true; } - if (!hashcache.isDirectory()) { - error("config.38", new Object[] { hashcache.getAbsolutePath() }); - return; + } + + if (!bTSLEnabledTPExist) { + // if no trustprofile has TSL support enabled, delete TSL configuration + tslconfiguration_ = null; + return; + } + + if (bTSLEnabledTPExist && tslconfiguration_ == null) { + error("config.40", null); + throw new ConfigurationException("config.40", null); + } + + final File workingDir = new File(tslconfiguration_.getWorkingDirectory()); + final File eu_trust = new File(workingDir.getAbsolutePath() + "/trust/eu"); + if (!eu_trust.exists()) { + error("config.51", new Object[] { "Verzeichnis \"trust/eu\" existiert nicht" }); + throw new ConfigurationException("config.51", new Object[] { + "Verzeichnis \"trust/eu\" existiert nicht" }); + } else { + final File[] eutrustFiles = eu_trust.listFiles(); + if (eutrustFiles == null) { + error("config.51", new Object[] { "Verzeichnis \"trust/eu\" ist leer" }); + throw new ConfigurationException("config.51", new Object[] { "Verzeichnis \"trust/eu\" ist leer" }); + } else { + if (eutrustFiles.length == 0) { + error("config.51", new Object[] { "Verzeichnis \"trust/eu\" ist leer" }); + throw new ConfigurationException("config.51", new Object[] { "Verzeichnis \"trust/eu\" ist leer" }); + } } + } + + final File hashcache = new File(tslconfiguration_.getWorkingDirectory(), "hashcache"); + if (!hashcache.exists()) { + hashcache.mkdir(); + } + if (!hashcache.isDirectory()) { + error("config.38", new Object[] { hashcache.getAbsolutePath() }); + return; + } + // System.setProperty("iaik.xml.crypto.tsl.BinaryHashCache.DIR", hashcache.getAbsolutePath()); // String hashcachedir = System.getProperty("iaik.xml.crypto.tsl.BinaryHashCache.DIR"); // System.out.println("Hashcache: " + hashcachedir); + Logger.debug("TSL Konfiguration - Hashcache: " + hashcache.getAbsolutePath()); - Logger.debug("TSL Konfiguration - Hashcache: " + hashcache.getAbsolutePath()); - - } - /** * Returns the warnings encountered during building the configuration. - * - * @return A List of Strings, containing the - * warning messages. + * + * @return A List of Strings, containing the warning + * messages. */ public List getWarnings() { return warnings; @@ -544,57 +527,58 @@ public class ConfigurationProvider /** * Return the name of the digest algorithm used during signature creation. - * - * @return The digest method algorithm name, or an empty String, - * if none has been configured. + * + * @return The digest method algorithm name, or an empty String, if + * none has been configured. */ public String getDigestMethodAlgorithmName() { return digestMethodAlgorithmName; } - + /** * Return the XAdES version used for signature creation. - * - * @return The XAdES version used for signature creation, or an empty String, - * if none has been configured. + * + * @return The XAdES version used for signature creation, or an empty + * String, if none has been configured. */ public String getXAdESVersion() { return xadesVersion; } - + public String getPDFASConfiguration() { - return pdfAsConfiguration; + return pdfAsConfiguration; } - + public int getConnectionTimeout() { - return this.connectionTimeout; + return this.connectionTimeout; } - + public int getReadTimeout() { - return this.readTimeout; + return this.readTimeout; } - + public boolean getAdesFormResults() { - return this.adesFormResults; + return this.adesFormResults; } - + public boolean getAllowExternalUris() { - return this.allowExternalUris_; + return this.allowExternalUris_; } - + public List getBlackListedUris() { - return this.blackListedUris_; + return this.blackListedUris_; } + public List getWhiteListedUris() { - return this.whiteListedUris_; + return this.whiteListedUris_; } - + /** * Return the name of the canonicalization algorithm used during signature * creation. - * - * @return The canonicalization algorithm name, or an empty - * String if none has been configured. + * + * @return The canonicalization algorithm name, or an empty String + * if none has been configured. */ public String getCanonicalizationAlgorithmName() { return canonicalizationAlgorithmName; @@ -602,9 +586,9 @@ public class ConfigurationProvider /** * Return the configured hardware crypto modules. - * + * * @return A List of HardwareCryptoModule objects - * containing the hardware crypto module configurations. + * containing the hardware crypto module configurations. */ public List getHardwareCryptoModules() { return hardwareCryptoModules; @@ -612,9 +596,9 @@ public class ConfigurationProvider /** * Return the hardware key modules configuration. - * + * * @return A List of HardwareKeyModule objects - * containing the configuration of the hardware key modules. + * containing the configuration of the hardware key modules. */ public List getHardwareKeyModules() { return hardwareKeyModules; @@ -622,9 +606,9 @@ public class ConfigurationProvider /** * Return the software key module configuration. - * + * * @return A List of SoftwareKeyModule objects - * containing the configuration of the software key modules. + * containing the configuration of the software key modules. */ public List getSoftwareKeyModules() { return softwareKeyModules; @@ -632,38 +616,38 @@ public class ConfigurationProvider /** * Return the key group mapping. - * - * @return A mapping from key group ID (a String) to - * KeyGroup mapping. + * + * @return A mapping from key group ID (a String) to + * KeyGroup mapping. */ public Map getKeyGroups() { return keyGroups; } - + public KeyGroup getKeyGroup(String keyGroupId) { - if (MiscUtil.isNotEmpty(keyGroupId)) - return (KeyGroup) keyGroups.get(keyGroupId.trim().toLowerCase()); - - else - return null; + if (MiscUtil.isNotEmpty(keyGroupId)) { + return (KeyGroup) keyGroups.get(keyGroupId.trim().toLowerCase()); + } else { + return null; + } } /** * Return the set of KeyGroupEntrys of a given key group, which a * client (identified by an issuer/serial pair) may access. - * - * @param issuer The issuer of the client certificate. - * @param serial The serial number of the client certificate. + * + * @param issuer The issuer of the client certificate. + * @param serial The serial number of the client certificate. * @param keyGroupId The ID of the key group. * @return A Set of all the KeyGroupEntrys in the - * given key group, if the user may access them. Returns null, if - * the user may not access the given key group or if the key group does not - * exist. + * given key group, if the user may access them. Returns + * null, if the user may not access the given key group or + * if the key group does not exist. */ public Set getKeyGroupEntries( - Principal issuer, - BigInteger serial, - String keyGroupId) { + Principal issuer, + BigInteger serial, + String keyGroupId) { IssuerAndSerial issuerAndSerial; Map mapping; @@ -676,118 +660,115 @@ public class ConfigurationProvider // System.out.println("Issuer: " + issuer); // System.out.println("serial: " + serial); -// +// // Iterator entries = keyGroupMappings.entrySet().iterator(); // while (entries.hasNext()) { // Entry thisEntry = (Entry) entries.next(); // System.out.println("Entry: " + thisEntry.getKey()); // System.out.println("Value: " + thisEntry.getValue()); // } - + mapping = (Map) keyGroupMappings.get(issuerAndSerial); if (mapping != null) { - KeyGroup keyGroup = (KeyGroup) mapping.get(keyGroupId); + final KeyGroup keyGroup = (KeyGroup) mapping.get(keyGroupId); if (keyGroup != null) { return keyGroup.getKeyGroupEntries(); } } - + // If no key group is available for a client identified by a certificate, // try to find a key group in the anonymous key group mapping - if (issuer != null || serial != null) - { + if (issuer != null || serial != null) { mapping = (Map) keyGroupMappings.get(ANONYMOUS_ISSUER_SERIAL); - if (mapping != null) - { - KeyGroup keyGroup = (KeyGroup) mapping.get(keyGroupId); - if (keyGroup != null) return keyGroup.getKeyGroupEntries(); + if (mapping != null) { + final KeyGroup keyGroup = (KeyGroup) mapping.get(keyGroupId); + if (keyGroup != null) { + return keyGroup.getKeyGroupEntries(); + } } } - + return null; } /** * Return the chaining mode for a given trust anchor. - * + * * @param trustAnchor The trust anchor for which the chaining mode should be - * returned. - * @return The chaining mode for the given trust anchor. If the trust anchor - * has not been configured separately, the system default will be returned. + * returned. + * @return The chaining mode for the given trust anchor. If the trust anchor has + * not been configured separately, the system default will be returned. */ public String getChainingMode(X509Certificate trustAnchor) { - Principal issuer = trustAnchor.getIssuerDN(); - BigInteger serial = trustAnchor.getSerialNumber(); - IssuerAndSerial issuerAndSerial = new IssuerAndSerial(issuer, serial); + final Principal issuer = trustAnchor.getIssuerDN(); + final BigInteger serial = trustAnchor.getSerialNumber(); + final IssuerAndSerial issuerAndSerial = new IssuerAndSerial(issuer, serial); - String mode = (String) chainingModes.get(issuerAndSerial); + final String mode = (String) chainingModes.get(issuerAndSerial); return mode != null ? mode : defaultChainingMode; } /** * Return the distribution points for a given CA. - * + * * @param cert The certificate for which the distribution points should be * looked up. The issuer information is used to perform the lookup. - * - * @return A Set of DistributionPoint objects. The - * set will be empty, if no distribution points have been configured - * for this certificate. + * + * @return A Set of DistributionPoint objects. The set + * will be empty, if no distribution points have been configured for + * this certificate. */ - public Set getDistributionPoints(X509Certificate cert) - { + public Set getDistributionPoints(X509Certificate cert) { try { - RFC2253NameParser nameParser = - new RFC2253NameParser(cert.getIssuerDN().toString()); - String caIssuerDN = nameParser.parse().getName(); - Set dps = (Set) distributionPoints.get(caIssuerDN); + final RFC2253NameParser nameParser = + new RFC2253NameParser(cert.getIssuerDN().toString()); + final String caIssuerDN = nameParser.parse().getName(); + final Set dps = (Set) distributionPoints.get(caIssuerDN); if (dps == null) { return Collections.EMPTY_SET; } return dps; - } catch (RFC2253NameParserException e) { + } catch (final RFC2253NameParserException e) { return Collections.EMPTY_SET; } } /** * Return the CRL archive duration. - * + * * @return The duration of how long to keep CRL archive entries (measured in - * days). + * days). */ public int getCRLArchiveDuration() { return cRLArchiveDuration; } - + /** * Returns whether revocation information should be archived. - * + * * @return whether revocation information should be archived. */ - public boolean getEnableRevocationArchiving() - { + public boolean getEnableRevocationArchiving() { return enableRevocationArchiving_; } - + /** * Returns the location of the certificate store. - * + * * @return the location of the certificate store. */ - public String getCertStoreLocation() - { + public String getCertStoreLocation() { return certStoreLocation_; } /** * Return a CreateTransformsInfoProfile with the given ID. - * + * * @param id The CreateTransformsInfoProfile ID. - * @return The CreateTransformsInfoProfile with the given - * ID or null, if none exists. + * @return The CreateTransformsInfoProfile with the given ID or + * null, if none exists. */ public Element getCreateTransformsInfoProfile(String id) { return (Element) createTransformsInfoProfiles.get(id); @@ -795,10 +776,10 @@ public class ConfigurationProvider /** * Return a CreateSignatureEnvironmentProfile with the given ID. - * + * * @param id The CreateSignatureEnvironmentProfile ID. - * @return The CreateSignatureEnvironmentProfile with the given - * ID or null, if none exists. + * @return The CreateSignatureEnvironmentProfile with the given ID + * or null, if none exists. */ public Element getCreateSignatureEnvironmentProfile(String id) { return (Element) createSignatureEnvironmentProfiles.get(id); @@ -806,10 +787,10 @@ public class ConfigurationProvider /** * Return a VerifyTransformsInfoProfile with the given ID. - * + * * @param id The VerifyTransformsInfoProfile ID. * @return The VerifyTransformsInfoProfile with the given ID or - * null, if none exists. + * null, if none exists. */ public Element getVerifyTransformsInfoProfile(String id) { return (Element) verifyTransformsInfoProfiles.get(id); @@ -817,10 +798,10 @@ public class ConfigurationProvider /** * Return a SupplementProfile with the given ID. - * + * * @param id The SupplementProfile ID. * @return The SupplementProfile with the given ID or - * null, if none exists. + * null, if none exists. */ public Element getSupplementProfile(String id) { return (Element) supplementProfiles.get(id); @@ -828,63 +809,64 @@ public class ConfigurationProvider /** * Return a TrustProfile with the given ID. - * + * * @param id The TrustProfile ID. - * @return The TrustProfile with the given ID or - * null, if none exists. + * @return The TrustProfile with the given ID or null, + * if none exists. */ public TrustProfile getTrustProfile(String id) { - if (MiscUtil.isNotEmpty(id)) { - id = id.trim().toLowerCase(); - return (TrustProfile) trustProfiles.get(id); - - } - - return null; + if (MiscUtil.isNotEmpty(id)) { + id = id.trim().toLowerCase(); + return (TrustProfile) trustProfiles.get(id); + + } + + return null; } - + /** * Returns a map of TrustProfiles + * * @return */ public Map getTrustProfiles() { - return trustProfiles; + return trustProfiles; } /** * Log a warning. - * - * @param messageId The message ID. + * + * @param messageId The message ID. * @param parameters Additional parameters for the message. * @see at.gv.egovernment.moa.spss.server.util.MessageProvider */ private static void info(String messageId, Object[] parameters) { - MessageProvider msg = MessageProvider.getInstance(); + final MessageProvider msg = MessageProvider.getInstance(); Logger.info(new LogMsg(msg.getMessage(messageId, parameters))); } - + /** * Log a debug message. - * - * @param messageId The message ID. + * + * @param messageId The message ID. * @param parameters Additional parameters for the message. * @see at.gv.egovernment.moa.spss.server.util.MessageProvider */ private static void debug(String message) { Logger.debug(message); } - - /** + + /** * Log a warning. - * + * * @param messageId The message ID. - * @param args Additional parameters for the message. + * @param args Additional parameters for the message. * @see at.gv.egovernment.moa.spss.server.util.MessageProvider */ private void warn(String messageId, Object[] args) { - MessageProvider msg = MessageProvider.getInstance(); - String txt = msg.getMessage(messageId, args); + final MessageProvider msg = MessageProvider.getInstance(); + final String txt = msg.getMessage(messageId, args); Logger.warn(new LogMsg(txt)); warnings.add(txt); @@ -892,133 +874,126 @@ public class ConfigurationProvider /** * Log an error. - * + * * @param messageId The message ID. - * @param args Additional parameters for the message. + * @param args Additional parameters for the message. * @see at.gv.egovernment.moa.spss.server.util.MessageProvider */ private void error(String messageId, Object[] args) { - MessageProvider msg = MessageProvider.getInstance(); - String txt = msg.getMessage(messageId, args); + final MessageProvider msg = MessageProvider.getInstance(); + final String txt = msg.getMessage(messageId, args); Logger.warn(new LogMsg(txt)); // warnings.add(txt); } - + /** * Returns the JDBC URL for the revocation archive database. - * + * * @return the JDBC URL for the revocation archive database. */ - public String getRevocationArchiveJDBCURL() - { + public String getRevocationArchiveJDBCURL() { return revocationArchiveJDBCURL_; } /** * Returns the JDBC driver class name for the revocation archive database. - * + * * @return the JDBC driver class name for the revocation archive database. */ - public String getRevocationArchiveJDBCDriverClass() - { + public String getRevocationArchiveJDBCDriverClass() { return revocationArchiveJDBCDriverClass_; } /** * Returns whether revocation checking should be done. - * + * * @return whether revocation checking should be done. */ - public boolean getEnableRevocationChecking() - { + public boolean getEnableRevocationChecking() { return enableRevocationChecking_; } /** - * Returns the maximum age of a revocation information for considering it - * still as valid. - * - * @return the maximum age of a revocation information for considering it - * still as valid. + * Returns the maximum age of a revocation information for considering it still + * as valid. + * + * @return the maximum age of a revocation information for considering it still + * as valid. */ - public long getMaxRevocationAge() - { + public long getMaxRevocationAge() { return maxRevocationAge_; } /** * Returns the service order for revocation checking. - * + * * @return the service order for revocation checking. Valid array entries are - * {@link RevocationSourceTypes#OCSP} and {@link RevocationSourceTypes#CRL}. + * {@link RevocationSourceTypes#OCSP} and + * {@link RevocationSourceTypes#CRL}. */ - public String[] getServiceOrder() - { + public String[] getServiceOrder() { return serviceOrder_; } /** - * Returns whether certificates found during certificate path construction + * Returns whether certificates found during certificate path construction * should be added to the certificate store. - * - * @return whether certificates found during certificate path construction + * + * @return whether certificates found during certificate path construction * should be added to the certificate store. */ - public boolean getAutoAddCertificates() - { + public boolean getAutoAddCertificates() { return autoAddCertificates_; } /** - * Returns whether EE certificates found during certificate path construction + * Returns whether EE certificates found during certificate path construction * should be added to the certificate store. - * - * @return whether certificates found during certificate path construction + * + * @return whether certificates found during certificate path construction * should be added to the certificate store. */ - public boolean getAutoAddEECertificates() - { + public boolean getAutoAddEECertificates() { return autoAddEECertificates_; } - + /** - * Returns whether the certificate extension Authority Info Access should - * be used during certificate path construction. - * - * @return whether the certificate extension Authority Info Access should - * be used during certificate path construction. + * Returns whether the certificate extension Authority Info Access should be + * used during certificate path construction. + * + * @return whether the certificate extension Authority Info Access should be + * used during certificate path construction. */ - public boolean getUseAuthorityInfoAccess() - { + public boolean getUseAuthorityInfoAccess() { return useAuthorityInfoAccess_; } - + /** * Returns whether the file URIs are permitted or not + * * @return whether the file URIs are permitted or not */ - public boolean getPermitFileURIs() - { - return permitFileURIs; + public boolean getPermitFileURIs() { + return permitFileURIs; } - + /** * Returns the map of retention intervals + * * @return The map of retention intervals */ public Map getCrlRetentionIntervals() { - return crlRetentionIntervals; + return crlRetentionIntervals; } - + /** * Returns the global TSL configuration + * * @return The global TSL configuration */ public TSLConfiguration getTSLConfiguration() { - return tslconfiguration_; + return tslconfiguration_; } - - } \ No newline at end of file diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/DistributionPoint.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/DistributionPoint.java index a2e5b93..bf911df 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/DistributionPoint.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/DistributionPoint.java @@ -21,42 +21,40 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.config; /** * Abstract base class for distribution points. - * + * * @author Gregor Karlinger * @version $Id$ - * */ -public abstract class DistributionPoint implements iaik.pki.revocation.DistributionPoint -{ - /** - * The distribution point URI. + */ +public abstract class DistributionPoint implements iaik.pki.revocation.DistributionPoint { + /** + * The distribution point URI. */ - private String uri_; + private final String uri_; /** * Create a DistributionPoint with a URI. - * + * * @param uri The URI of the distribution point. */ - public DistributionPoint(String uri) - { + public DistributionPoint(String uri) { uri_ = uri; } - + /** * @see iaik.pki.revocation.DistributionPoint#getType() */ + @Override public abstract String getType(); /** * @see iaik.pki.revocation.DistributionPoint#getUri() */ - public String getUri() - { + @Override + public String getUri() { return uri_; } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/HardwareCryptoModule.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/HardwareCryptoModule.java index c0487f6..99ca1c3 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/HardwareCryptoModule.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/HardwareCryptoModule.java @@ -21,40 +21,38 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.config; /** * Contains configuration data for a hardware crypto module. - * + * * @author Patrick Peck * @version $Id$ */ public class HardwareCryptoModule { /** The name of the module. */ - private String name; + private final String name; /** The slod ID of the module. */ - private String slotID; + private final String slotID; /** The user PIN of the module. */ - private String userPIN; - + private final String userPIN; + /** * Create a new HardwareCryptoModule. - * - * @param name The name of this HardwareCryptoModule. - * @param slotID The slot ID of this HardwareCryptoModule. - * @param userPIN The user PIN to access this - * HardwareCryptoModule. + * + * @param name The name of this HardwareCryptoModule. + * @param slotID The slot ID of this HardwareCryptoModule. + * @param userPIN The user PIN to access this HardwareCryptoModule. */ public HardwareCryptoModule(String name, String slotID, String userPIN) { this.name = name; this.slotID = slotID; this.userPIN = userPIN; } - + /** * Returns the name of this HardwareCryptoModule. - * + * * @return The name of this HardwareCryptoModule. */ public String getName() { @@ -63,22 +61,20 @@ public class HardwareCryptoModule { /** * Returns the slot ID of this HardwareCryptoModule. - * + * * @return The slot ID. */ public String getSlotID() { return slotID; } - /** * Returns the user PIN of this HardwareCryptoModule. - * + * * @return The user PIN used to access the module. */ public String getUserPIN() { return userPIN; } - } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/HardwareKeyModule.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/HardwareKeyModule.java index 18fd085..5fa408c 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/HardwareKeyModule.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/HardwareKeyModule.java @@ -21,60 +21,59 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.config; /** * A class that contains information about a hardware key module. - * + * * @author Patrick Peck * @version $Id$ */ public class HardwareKeyModule extends KeyModule { /** The name of the module. */ - private String name; + private final String name; /** The slod ID of the module. */ - private String slotID; + private final String slotID; /** The user PIN of the module. */ - private String userPIN; - + private final String userPIN; + /** * Create a new HardwareKey. - * - * @param id The key module ID. - * @param name The name of the key. - * @param slotID The slot ID of the key within the hardware module. May be - * null. + * + * @param id The key module ID. + * @param name The name of the key. + * @param slotID The slot ID of the key within the hardware module. May be + * null. * @param userPIN The user PIN to access the key. */ public HardwareKeyModule(String id, String name, String slotID, String userPIN) { super(id); this.name = name; this.slotID = slotID; - this.userPIN = userPIN; + this.userPIN = userPIN; } - + /** * Return the name of this HardwareKey. - * + * * @return The name of this HardwareKey. */ public String getName() { return name; } - + /** * Return the slot ID of this HardwareKey. - * + * * @return The slot ID of this HardwareKey. */ public String getSlotID() { return slotID; } - + /** * Return the user PIN to access this HardwareKey. - * + * * @return The user PIN to access this HardwareKey. */ public String getUserPIN() { diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/IssuerAndSerial.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/IssuerAndSerial.java index 38a3ae9..03827f2 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/IssuerAndSerial.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/IssuerAndSerial.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.config; import java.math.BigInteger; @@ -34,25 +33,25 @@ import iaik.utils.RFC2253NameParserException; /** * A class containing the issuer and serial number of a certificate, which can * be used to uniquely identify the certificate. - * + * * The issuer is contained as an RFC2253 encoded String. - * + * * @author Patrick Peck * @version $Id$ */ public class IssuerAndSerial { /** The issuer distinguished name. */ - private String issuerDN; + private final String issuerDN; /** The certificate serial number. */ - private BigInteger serial; + private final BigInteger serial; /** * Create an IssuerAndSerial object. - * + * * The name of the issuer is converted to RFC2253. If it cannot be parsed, the - * DN contained in the issuer is set. - * + * DN contained in the issuer is set. + * * @param issuer The isser of a certificate. * @param serial The serial number of the certificate. */ @@ -60,28 +59,28 @@ public class IssuerAndSerial { String issuerDN = null; if (issuer instanceof Name) { try { - issuerDN = ((Name)issuer).getRFC2253String(); - } catch (RFC2253NameParserException e) { + issuerDN = ((Name) issuer).getRFC2253String(); + } catch (final RFC2253NameParserException e) { // do nothing } } if (issuerDN == null) { - RFC2253NameParser parser = new RFC2253NameParser(issuer.getName()); + final RFC2253NameParser parser = new RFC2253NameParser(issuer.getName()); try { - issuerDN = ((Name)parser.parse()).getRFC2253String(); - } catch (RFC2253NameParserException e) { + issuerDN = parser.parse().getRFC2253String(); + } catch (final RFC2253NameParserException e) { issuerDN = issuer.getName(); } } this.serial = serial; this.issuerDN = issuerDN; } - + /** * Create an IssuerAndSerial object. - * + * * @param issuerDN The issuer distinguished name. Should be an RFC2253 name. - * @param serial The serial number of the certificate. + * @param serial The serial number of the certificate. */ public IssuerAndSerial(String issuerDN, BigInteger serial) { this.issuerDN = issuerDN; @@ -90,7 +89,7 @@ public class IssuerAndSerial { /** * Return the issuer DN in RFC2253 format. - * + * * @return The issuer part of this object. */ public String getIssuerDN() { @@ -99,7 +98,7 @@ public class IssuerAndSerial { /** * Return the serial number. - * + * * @return The serial number of this object. */ public BigInteger getSerial() { @@ -108,28 +107,31 @@ public class IssuerAndSerial { /** * Compare this IssuerAndSerial to another object. - * + * * @param other The object to compare this IssuerAndSerial to. * @return true, if other is an - * IssuerAndSerial object and the issuer and - * serial fields are both equal. false otherwise. + * IssuerAndSerial object and the issuer and + * serial fields are both equal. false + * otherwise. * @see java.lang.Object#equals(java.lang.Object) */ + @Override public boolean equals(Object other) { if (other instanceof IssuerAndSerial) { - IssuerAndSerial ias = (IssuerAndSerial) other; + final IssuerAndSerial ias = (IssuerAndSerial) other; return getIssuerDN().equals(ias.getIssuerDN()) - && getSerial().equals(ias.getSerial()); + && getSerial().equals(ias.getSerial()); } return false; } /** * Return the hash code of this IssuerAndSerial. - * + * * @return The hash code of this IssuerAndSerial. * @see java.lang.Object#hashCode() */ + @Override public int hashCode() { return issuerDN.hashCode() ^ serial.hashCode(); } @@ -137,13 +139,14 @@ public class IssuerAndSerial { /** * Return a String representation of this * IssuerAndSerial object. - * + * * @return The String representation. * @see java.lang.Object#toString() */ + @Override public String toString() { - return ("(IssuerAndSerial - Issuer<" + getIssuerDN()) - + ("> Serial<" + serial.toString() + ">)"); + return "(IssuerAndSerial - Issuer<" + getIssuerDN() + + "> Serial<" + serial.toString() + ">)"; } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/KeyGroup.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/KeyGroup.java index c2490f9..faeaf82 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/KeyGroup.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/KeyGroup.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.config; import java.util.Iterator; @@ -29,7 +28,7 @@ import java.util.Set; /** * A collection of KeyGroupEntrys with its own ID. - * + * * @author Sven Aigner * @author Patrick Peck * @version $Id$ @@ -37,59 +36,62 @@ import java.util.Set; public class KeyGroup { /** The keys belonging to this key group. */ - private Set keyGroupEntries; + private final Set keyGroupEntries; /** The key group ID. */ - private String id; + private final String id; /** The digest method algorithm for the key group */ - private String digestMethodAlgorithm; + private final String digestMethodAlgorithm; /** * Create a KeyGroup. - * - * @param id The ID of this KeyGroup. - * @param keyGroupEntries The keys belonging to this KeyGroup. + * + * @param id The ID of this KeyGroup. + * @param keyGroupEntries The keys belonging to this + * KeyGroup. * @param digestMethodAlgorithm The signature algorithm used for this key group */ public KeyGroup(String id, Set keyGroupEntries, String digestMethodAlgorithm) { this.id = id; this.keyGroupEntries = keyGroupEntries; - this.digestMethodAlgorithm = digestMethodAlgorithm; + this.digestMethodAlgorithm = digestMethodAlgorithm; } /** * Return the KeyEntrys contained in this KeyGroup. - * + * * @return The KeyEntrys contained in this KeyGroup. */ public Set getKeyGroupEntries() { return keyGroupEntries; } - + /** * Returnd the digest method algorithm used for this key group + * * @return The digest method signature algorithm used for this key group */ public String getDigestMethodAlgorithm() { - return digestMethodAlgorithm; + return digestMethodAlgorithm; } /** * Return the ID of this KeyGroup. - * + * * @return The KeyGroup ID. */ public String getId() { return id; } - /** + /** * Return a String representation of this KeyGroup. - * + * * @return The String representation. * @see java.lang.Object#toString() */ + @Override public String toString() { - StringBuffer sb = new StringBuffer(); + final StringBuffer sb = new StringBuffer(); Iterator i; if (getKeyGroupEntries() != null) { @@ -99,7 +101,8 @@ public class KeyGroup { sb.append(" " + i.next()); } } - return "(KeyGroup - ID:" + id + " " + sb.toString() + ")" + "DigestMethodAlgorithm: " + digestMethodAlgorithm; + return "(KeyGroup - ID:" + id + " " + sb.toString() + ")" + "DigestMethodAlgorithm: " + + digestMethodAlgorithm; } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/KeyGroupEntry.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/KeyGroupEntry.java index fcedfb0..d73b755 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/KeyGroupEntry.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/KeyGroupEntry.java @@ -21,31 +21,30 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.config; import java.math.BigInteger; /** * A class containing information about an entry in a key group. - * + * * @author Patrick Peck * @version $Id$ */ public class KeyGroupEntry { /** The module ID of the key. */ - private String moduleID; + private final String moduleID; /** The issuer DN of the certificate identifying the key. */ - private String issuerDN; + private final String issuerDN; /** The serial number of the certificate identifying the key. */ - private BigInteger serialNumber; + private final BigInteger serialNumber; /** * Create a new KeyGroupEntry. - * - * @param moduleID The key module ID to which this entry belongs to. - * @param issuerAndSerial The issuer and serial number which uniquely - * identifies a certificate within the key module. + * + * @param moduleID The key module ID to which this entry belongs to. + * @param issuerAndSerial The issuer and serial number which uniquely identifies + * a certificate within the key module. */ public KeyGroupEntry(String moduleID, IssuerAndSerial issuerAndSerial) { this.moduleID = moduleID; @@ -55,25 +54,24 @@ public class KeyGroupEntry { /** * Create a new KeyGroupEntry. - * - * @param moduleID The key module ID to which this entry belongs to. - * @param issuerDN The isser DN of the certificate within the key module. + * + * @param moduleID The key module ID to which this entry belongs to. + * @param issuerDN The isser DN of the certificate within the key module. * @param serialNumber The serial number of the certificate within the key - * module. + * module. */ public KeyGroupEntry( - String moduleID, - String issuerDN, - BigInteger serialNumber) { + String moduleID, + String issuerDN, + BigInteger serialNumber) { this.moduleID = moduleID; this.issuerDN = issuerDN; this.serialNumber = serialNumber; } /** - * Return the key module ID to which this KeyGroupEntry belongs - * to. - * + * Return the key module ID to which this KeyGroupEntry belongs to. + * * @return The key module ID. */ public String getModuleID() { @@ -83,7 +81,7 @@ public class KeyGroupEntry { /** * Return the issuer DN of this KeyGroupEntry for identifying the * certificate within the key module. - * + * * @return The issuer DN of the certificate. */ public String getIssuerDN() { @@ -93,7 +91,7 @@ public class KeyGroupEntry { /** * Return the serial number of this KeyGroupEntry for identifying * the certificate within the key module. - * + * * @return The serial number of the certificate. */ public BigInteger getSerialNumber() { @@ -105,26 +103,28 @@ public class KeyGroupEntry { * * @param other The KeyGroupEntry to compare to. * @return true, if module ID, isser DN and serial number of - * other match the ones contained in this object, otherwise - * false. + * other match the ones contained in this object, otherwise + * false. * @see java.lang.Object#equals(Object) */ + @Override public boolean equals(Object other) { if (other instanceof KeyGroupEntry) { - KeyGroupEntry entry = (KeyGroupEntry) other; + final KeyGroupEntry entry = (KeyGroupEntry) other; return getModuleID().equals(entry.getModuleID()) - && getIssuerDN().equals(entry.getIssuerDN()) - && getSerialNumber().equals(entry.getSerialNumber()); + && getIssuerDN().equals(entry.getIssuerDN()) + && getSerialNumber().equals(entry.getSerialNumber()); } return false; } - + /** * @see java.lang.Object#hashCode() */ + @Override public int hashCode() { return getModuleID().hashCode() - ^ getIssuerDN().hashCode() - ^ getSerialNumber().hashCode(); + ^ getIssuerDN().hashCode() + ^ getSerialNumber().hashCode(); } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/KeyModule.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/KeyModule.java index 45d8d7e..6a665d6 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/KeyModule.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/KeyModule.java @@ -21,23 +21,22 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.config; /** * A class that contains information about a key module. - * + * * @author Patrick Peck * @version $Id$ */ public class KeyModule { /** The key module ID. */ - private String id; + private final String id; /** * Create a Key object. - * + * * @param id The key module ID. */ public KeyModule(String id) { @@ -46,7 +45,7 @@ public class KeyModule { /** * Return the key ID. - * + * * @return The key ID. */ public String getId() { @@ -55,10 +54,11 @@ public class KeyModule { /** * Return a String representation of this Key. - * + * * @return The String representation. * @see java.lang.Object#toString() */ + @Override public String toString() { return "(Key - Id<" + id + ">)"; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/OCSPDistributionPoint.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/OCSPDistributionPoint.java index 2e91c6b..97ced05 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/OCSPDistributionPoint.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/OCSPDistributionPoint.java @@ -21,36 +21,33 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.config; import iaik.pki.revocation.RevocationSourceTypes; /** * A class representing a CRL distribution point. - * + * * @author Gregor Karlinger * @version $Id$ */ -public class OCSPDistributionPoint - extends DistributionPoint - implements iaik.pki.revocation.DistributionPoint -{ +public class OCSPDistributionPoint + extends DistributionPoint + implements iaik.pki.revocation.DistributionPoint { /** * Create a OCSPDistributionPoint with a URI. - * + * * @param uri The URI of the ocsp distribution point. */ - public OCSPDistributionPoint(String uri) - { + public OCSPDistributionPoint(String uri) { super(uri); } /** * @see iaik.pki.revocation.DistributionPoint#getType() */ - public String getType() - { + @Override + public String getType() { return RevocationSourceTypes.OCSP; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/SoftwareKeyModule.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/SoftwareKeyModule.java index 0ed83bb..3c038cf 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/SoftwareKeyModule.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/SoftwareKeyModule.java @@ -21,25 +21,24 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.config; /** * A class containing information about a software key, stored in PKCS12 format. - * + * * @author Patrick Peck * @version $Id$ */ public class SoftwareKeyModule extends KeyModule { /** The name of the file containing the keys. */ - private String fileName; + private final String fileName; /** The password for accessing the file. */ - private String passWord; - + private final String passWord; + /** * Create a new SoftwareKey. - * - * @param id The key ID. + * + * @param id The key ID. * @param fileName The name of the PKCS12 keystore file containing the key. * @param passWord The password to access the keystore file. */ @@ -48,25 +47,24 @@ public class SoftwareKeyModule extends KeyModule { this.fileName = fileName; this.passWord = passWord; } - + /** * Return the name of the PKCS12 keystore file containing this * SoftwareKey. - * + * * @return The name of the PKCS12 keystore file. */ public String getFileName() { return fileName; } - + /** * Return the password to access the keystore file. - * + * * @return The password to access the keystore file. */ public String getPassWord() { return passWord; } - } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/TrustProfile.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/TrustProfile.java index 0063c7f..94155d6 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/TrustProfile.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/config/TrustProfile.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.config; import java.net.URI; @@ -35,129 +34,139 @@ import java.util.regex.PatternSyntaxException; import at.gv.egovernment.moa.sig.tsl.TslConstants; import at.gv.egovernment.moaspss.logging.Logger; import at.gv.egovernment.moaspss.util.MiscUtil; -import iaik.x509.X509Certificate; /** * Information about a trust profile. - * + * * @author Patrick Peck * @version $Id$ */ public class TrustProfile { /** The ID of the trust profile. */ - private String id; + private final String id; /** The URI giving the location of the trust profile. */ - private String uri; + private final String uri; /** The URI giving the location of the allowed signer certificates. */ - private String signerCertsUri; - - /** Defines if Trustprofile makes use of EU TSL*/ - private boolean tslEnabled; - /** The countries given */ - private List countries = new ArrayList(); - - private List allowedTspStatus = new ArrayList(); - private List allowedTspServiceTypes = new ArrayList(); - - + private final String signerCertsUri; + + /** Defines if Trustprofile makes use of EU TSL */ + private final boolean tslEnabled; + /** The countries given */ + private final List countries = new ArrayList<>(); + + private final List allowedTspStatus = new ArrayList<>(); + private final List allowedTspServiceTypes = new ArrayList<>(); + /** * Create a TrustProfile. - * - * @param id The ID of the TrustProfile to create. - * @param uri The URI of the TrustProfile to create. - * @param signerCertsUri The URI of the location of the allowed signer - * certificates of the TrustProfile to create. - * @param allowedTspServiceTypes - * @param allowedTspStatus + * + * @param id The ID of the TrustProfile to + * create. + * @param uri The URI of the TrustProfile to + * create. + * @param signerCertsUri The URI of the location of the allowed signer + * certificates of the TrustProfile + * to create. + * @param allowedTspServiceTypes + * @param allowedTspStatus */ - public TrustProfile(String id, String uri, String signerCertsUri, - boolean tslEnabled, String countries, String allowedTspStatus, String allowedTspServiceTypes) { + public TrustProfile(String id, String uri, String signerCertsUri, + boolean tslEnabled, String countries, String allowedTspStatus, String allowedTspServiceTypes) { this.id = id; this.uri = uri; this.signerCertsUri = signerCertsUri; - - //TSL configuration parameters + + // TSL configuration parameters this.tslEnabled = tslEnabled; - if (tslEnabled) { - setCountries(countries); - if (!this.countries.isEmpty()) - Logger.info("TrustProfile "+ id + " allows " + Arrays.toString(this.countries.toArray()) + " TSL countries"); - else - Logger.info("TrustProfile "+ id + " allows " + "ALL" + " TSL countries"); - - setAllowedTspStatus(allowedTspStatus); - Logger.info("TrustProfile "+ id + " allows " + Arrays.toString(this.allowedTspStatus.toArray()) + " TSP status identifier"); - - setAllowedTspServiceTypes(allowedTspServiceTypes); - Logger.info("TrustProfile "+ id + " allows " + Arrays.toString(this.allowedTspServiceTypes.toArray()) + " TSL service-type identifier"); - - } + if (tslEnabled) { + setCountries(countries); + if (!this.countries.isEmpty()) { + Logger.info("TrustProfile " + id + " allows " + Arrays.toString(this.countries.toArray()) + + " TSL countries"); + } else { + Logger.info("TrustProfile " + id + " allows " + "ALL" + " TSL countries"); + } + + setAllowedTspStatus(allowedTspStatus); + Logger.info("TrustProfile " + id + " allows " + Arrays.toString(this.allowedTspStatus.toArray()) + + " TSP status identifier"); + + setAllowedTspServiceTypes(allowedTspServiceTypes); + Logger.info("TrustProfile " + id + " allows " + Arrays.toString(this.allowedTspServiceTypes.toArray()) + + " TSL service-type identifier"); + + } } private void setCountries(String countries) { - if (MiscUtil.isNotEmpty(countries)) { - String[] ccArray = countries.split(","); - for (String el : ccArray) - this.countries.add(el.trim()); - - } + if (MiscUtil.isNotEmpty(countries)) { + final String[] ccArray = countries.split(","); + for (final String el : ccArray) { + this.countries.add(el.trim()); + } + + } } - + private void setAllowedTspStatus(String allowedTspStatus) { - if (MiscUtil.isNotEmpty(allowedTspStatus)) { - String[] ccArray = allowedTspStatus.split(","); - for (String el : ccArray) { - try { - this.allowedTspStatus.add(new URI(el.trim())); - - } catch (URISyntaxException e) { - Logger.warn("TrustProfile: " + this.id + " contains a non-valid TSP Status identifier (" + el + ")"); - - } - - } - - } else { - Logger.debug("Use default set of TSP Status identifier"); - this.allowedTspStatus.addAll( - Arrays.asList( - TslConstants.SERVICE_STATUS_SORT_TO_URI.get(TslConstants.SERVICE_STATUS_SHORT.granted), - TslConstants.SERVICE_STATUS_SORT_TO_URI.get(TslConstants.SERVICE_STATUS_SHORT.recognisedatnationallevel), - TslConstants.SERVICE_STATUS_SORT_TO_URI.get(TslConstants.SERVICE_STATUS_SHORT.accredited), - TslConstants.SERVICE_STATUS_SORT_TO_URI.get(TslConstants.SERVICE_STATUS_SHORT.undersupervision))); - - } - + if (MiscUtil.isNotEmpty(allowedTspStatus)) { + final String[] ccArray = allowedTspStatus.split(","); + for (final String el : ccArray) { + try { + this.allowedTspStatus.add(new URI(el.trim())); + + } catch (final URISyntaxException e) { + Logger.warn("TrustProfile: " + this.id + " contains a non-valid TSP Status identifier (" + el + + ")"); + + } + + } + + } else { + Logger.debug("Use default set of TSP Status identifier"); + this.allowedTspStatus.addAll( + Arrays.asList( + TslConstants.SERVICE_STATUS_SORT_TO_URI.get(TslConstants.SERVICE_STATUS_SHORT.granted), + TslConstants.SERVICE_STATUS_SORT_TO_URI.get( + TslConstants.SERVICE_STATUS_SHORT.recognisedatnationallevel), + TslConstants.SERVICE_STATUS_SORT_TO_URI.get(TslConstants.SERVICE_STATUS_SHORT.accredited), + TslConstants.SERVICE_STATUS_SORT_TO_URI.get( + TslConstants.SERVICE_STATUS_SHORT.undersupervision))); + + } + } - + private void setAllowedTspServiceTypes(String allowedTspServiceTypes) { - if (MiscUtil.isNotEmpty(allowedTspServiceTypes)) { - String[] ccArray = allowedTspServiceTypes.split(","); - for (String el : ccArray) { - try { - this.allowedTspServiceTypes.add(Pattern.compile(el.trim())); - - } catch (PatternSyntaxException e) { - Logger.warn("TrustProfile: " + this.id + " contains a non-valid TSP Service-Type identifier Regex pattern(" + el + ")"); - - } - - } - - } else { - Logger.debug("Use default set of TSP Service-Type identifier"); - this.allowedTspServiceTypes.addAll( - Arrays.asList( - Pattern.compile(TslConstants.DEFAULT_REGEX_PATTERN_ALLOW_ALL))); - - } - + if (MiscUtil.isNotEmpty(allowedTspServiceTypes)) { + final String[] ccArray = allowedTspServiceTypes.split(","); + for (final String el : ccArray) { + try { + this.allowedTspServiceTypes.add(Pattern.compile(el.trim())); + + } catch (final PatternSyntaxException e) { + Logger.warn("TrustProfile: " + this.id + + " contains a non-valid TSP Service-Type identifier Regex pattern(" + el + ")"); + + } + + } + + } else { + Logger.debug("Use default set of TSP Service-Type identifier"); + this.allowedTspServiceTypes.addAll( + Arrays.asList( + Pattern.compile(TslConstants.DEFAULT_REGEX_PATTERN_ALLOW_ALL))); + + } + } - + /** * Return the ID of this TrustProfile. - * + * * @return The TrustProfile ID. */ public String getId() { @@ -166,49 +175,51 @@ public class TrustProfile { /** * Return the URI of this TrustProfile. - * + * * @return The URI of TrustProfile. */ public String getUri() { return uri; } - /** - * Return the URI giving the location of the allowed signer certificates - * of this TrustProfile. - * + * Return the URI giving the location of the allowed signer certificates of this + * TrustProfile. + * * @return The URI of TrustProfile. */ public String getSignerCertsUri() { return signerCertsUri; } + /** * Returns if Trustprofile is TSL enabled + * * @return */ public boolean isTSLEnabled() { - return tslEnabled; + return tslEnabled; } + /** * Returns the given countries + * * @return Given countries */ public List getCountries() { - if (!tslEnabled) - return null; - else - return countries; + if (!tslEnabled) { + return null; + } else { + return countries; + } } public List getAllowedTspStatus() { - return allowedTspStatus; + return allowedTspStatus; } public List getAllowedTspServiceTypes() { - return allowedTspServiceTypes; + return allowedTspServiceTypes; } - - - + } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/cmssign/CMSSignatureCreationProfileImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/cmssign/CMSSignatureCreationProfileImpl.java index a465049..d660c7a 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/cmssign/CMSSignatureCreationProfileImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/cmssign/CMSSignatureCreationProfileImpl.java @@ -21,17 +21,8 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.cmssign; -import iaik.server.modules.algorithms.SignatureAlgorithms; -import iaik.server.modules.cmssign.CMSSignatureCreationProfile; -import iaik.server.modules.keys.AlgorithmUnavailableException; -import iaik.server.modules.keys.KeyEntryID; -import iaik.server.modules.keys.KeyModule; -import iaik.server.modules.keys.KeyModuleFactory; -import iaik.server.modules.keys.UnknownKeyException; - import java.util.List; import java.util.Set; @@ -39,61 +30,71 @@ 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.Logger; +import iaik.server.modules.algorithms.SignatureAlgorithms; +import iaik.server.modules.cmssign.CMSSignatureCreationProfile; +import iaik.server.modules.keys.AlgorithmUnavailableException; +import iaik.server.modules.keys.KeyEntryID; +import iaik.server.modules.keys.KeyModule; +import iaik.server.modules.keys.KeyModuleFactory; +import iaik.server.modules.keys.UnknownKeyException; /** * An object providing auxiliary information for creating a CMS signature. - * + * * @author Patrick Peck * @version $Id$ */ public class CMSSignatureCreationProfileImpl - implements CMSSignatureCreationProfile { + implements CMSSignatureCreationProfile { /** The set of keys available to the signing process. */ private Set keySet; - /** The MIME type of the data to be signed*/ - private String mimeType; - /** Whether the created signature is to be Security Layer conform. */ + /** The MIME type of the data to be signed */ + private final String mimeType; + /** Whether the created signature is to be Security Layer conform. */ private boolean securityLayerConform; - /** Properties to be signed during signature creation. */ - private List signedProperties; - /** Specifies whether the content data shall be included in the CMS SignedData or shall be not included. */ - private boolean includeData; - /** Digest Method algorithm */ + /** Properties to be signed during signature creation. */ + private final List signedProperties; + /** + * Specifies whether the content data shall be included in the CMS SignedData or + * shall be not included. + */ + private final boolean includeData; + /** Digest Method algorithm */ private String digestMethod; - private boolean isPAdESConform; - - + private final boolean isPAdESConform; + /** * Create a new XMLSignatureCreationProfileImpl. - * - * @param createProfileCount Provides external information about the - * number of calls to the signature creation module, using the same request. - * @param reservedIDs The set of IDs that must not be used while generating - * new IDs. + * + * @param createProfileCount Provides external information about the number of + * calls to the signature creation module, using the + * same request. + * @param reservedIDs The set of IDs that must not be used while + * generating new IDs. */ public CMSSignatureCreationProfileImpl( - Set keySet, - String digestMethod, - List signedProperties, - boolean securityLayerConform, - boolean includeData, - String mimeType, - boolean isPAdESConform) { - this.keySet = keySet; - this.signedProperties = signedProperties; - this.securityLayerConform = securityLayerConform; - this.includeData = includeData; - this.mimeType = mimeType; - this.digestMethod = digestMethod; - this.isPAdESConform = isPAdESConform; + Set keySet, + String digestMethod, + List signedProperties, + boolean securityLayerConform, + boolean includeData, + String mimeType, + boolean isPAdESConform) { + this.keySet = keySet; + this.signedProperties = signedProperties; + this.securityLayerConform = securityLayerConform; + this.includeData = includeData; + this.mimeType = mimeType; + this.digestMethod = digestMethod; + this.isPAdESConform = isPAdESConform; } - /** * @see iaik.server.modules.xmlsign.XMLSignatureCreationProfile#getKeySet() */ + @Override public Set getKeySet() { return keySet; } @@ -101,119 +102,116 @@ public class CMSSignatureCreationProfileImpl /** * Set the set of KeyEntryIDs which may be used for signature * creation. - * + * * @param keySet The set of KeyEntryIDs to set. */ public void setKeySet(Set keySet) { this.keySet = keySet; } - /** * @see iaik.server.modules.xmlsign.XMLSignatureCreationProfile#getSignatureAlgorithmName(KeyEntryID) */ + @Override public String getSignatureAlgorithmName(KeyEntryID selectedKeyID) - throws AlgorithmUnavailableException { + throws AlgorithmUnavailableException { - - TransactionContext context = - TransactionContextManager.getInstance().getTransactionContext(); - TransactionId tid = new TransactionId(context.getTransactionID()); - KeyModule module = KeyModuleFactory.getInstance(tid); + final TransactionContext context = + TransactionContextManager.getInstance().getTransactionContext(); + final TransactionId tid = new TransactionId(context.getTransactionID()); + final KeyModule module = KeyModuleFactory.getInstance(tid); Set algorithms; try { algorithms = module.getSupportedSignatureAlgorithms(selectedKeyID); - } catch (UnknownKeyException e) { + } catch (final UnknownKeyException e) { throw new AlgorithmUnavailableException( - "Unknown key entry: " + selectedKeyID, - e, - null); + "Unknown key entry: " + selectedKeyID, + e, + null); } - - if (digestMethod.compareTo("SHA-1") == 0) { - Logger.warn("SHA-1 is configured as digest algorithm. Please revise a use of a more secure digest algorithm out of the SHA-2 family (e.g. SHA-256, SHA-384, SHA-512)"); - - if (algorithms.contains(SignatureAlgorithms.SHA1_WITH_RSA)) { - return SignatureAlgorithms.SHA1_WITH_RSA; - - } else if (algorithms.contains(SignatureAlgorithms.ECDSA)) { - return SignatureAlgorithms.ECDSA; - - } else if (algorithms.contains(SignatureAlgorithms.DSA)) { - return SignatureAlgorithms.DSA; - - } else { - throw new AlgorithmUnavailableException( - "No algorithm for key entry: " + selectedKeyID, - null, - null); - } - - } else if (digestMethod.compareTo("SHA-256") == 0) { - if (algorithms.contains(SignatureAlgorithms.SHA256_WITH_RSA)) { - return SignatureAlgorithms.SHA256_WITH_RSA; - - } else if (algorithms.contains(SignatureAlgorithms.SHA256_WITH_ECDSA)) { - return SignatureAlgorithms.SHA256_WITH_ECDSA; - - } else if (algorithms.contains(SignatureAlgorithms.DSA)) { - return SignatureAlgorithms.DSA; - - } else { - throw new AlgorithmUnavailableException( - "No algorithm for key entry: " + selectedKeyID, - null, - null); - } - } else if (digestMethod.compareTo("SHA-384") == 0) { - if (algorithms.contains(SignatureAlgorithms.SHA384_WITH_RSA)) { - return SignatureAlgorithms.SHA384_WITH_RSA; - - } else if (algorithms.contains(SignatureAlgorithms.SHA384_WITH_ECDSA)) { - return SignatureAlgorithms.SHA384_WITH_ECDSA; - - } else if (algorithms.contains(SignatureAlgorithms.DSA)) { - return SignatureAlgorithms.DSA; - - } else { - throw new AlgorithmUnavailableException( - "No algorithm for key entry: " + selectedKeyID, - null, - null); - } - } else if (digestMethod.compareTo("SHA-512") == 0) { - if (algorithms.contains(SignatureAlgorithms.SHA512_WITH_RSA)) { - return SignatureAlgorithms.SHA512_WITH_RSA; - - } else if (algorithms.contains(SignatureAlgorithms.SHA512_WITH_ECDSA)) { - return SignatureAlgorithms.SHA512_WITH_ECDSA; - - } else if (algorithms.contains(SignatureAlgorithms.DSA)) { - return SignatureAlgorithms.DSA; - - } else { - throw new AlgorithmUnavailableException( - "No algorithm for key entry: " + selectedKeyID, - null, - null); - } - } - else { - throw new AlgorithmUnavailableException( - "No signature algorithm found for digest algorithm '" + digestMethod, - null, - null); - } - - } + if (digestMethod.compareTo("SHA-1") == 0) { + Logger.warn( + "SHA-1 is configured as digest algorithm. Please revise a use of a more secure digest algorithm out of the SHA-2 family (e.g. SHA-256, SHA-384, SHA-512)"); + + if (algorithms.contains(SignatureAlgorithms.SHA1_WITH_RSA)) { + return SignatureAlgorithms.SHA1_WITH_RSA; + + } else if (algorithms.contains(SignatureAlgorithms.ECDSA)) { + return SignatureAlgorithms.ECDSA; + + } else if (algorithms.contains(SignatureAlgorithms.DSA)) { + return SignatureAlgorithms.DSA; + + } else { + throw new AlgorithmUnavailableException( + "No algorithm for key entry: " + selectedKeyID, + null, + null); + } + + } else if (digestMethod.compareTo("SHA-256") == 0) { + if (algorithms.contains(SignatureAlgorithms.SHA256_WITH_RSA)) { + return SignatureAlgorithms.SHA256_WITH_RSA; + + } else if (algorithms.contains(SignatureAlgorithms.SHA256_WITH_ECDSA)) { + return SignatureAlgorithms.SHA256_WITH_ECDSA; + + } else if (algorithms.contains(SignatureAlgorithms.DSA)) { + return SignatureAlgorithms.DSA; + + } else { + throw new AlgorithmUnavailableException( + "No algorithm for key entry: " + selectedKeyID, + null, + null); + } + } else if (digestMethod.compareTo("SHA-384") == 0) { + if (algorithms.contains(SignatureAlgorithms.SHA384_WITH_RSA)) { + return SignatureAlgorithms.SHA384_WITH_RSA; + + } else if (algorithms.contains(SignatureAlgorithms.SHA384_WITH_ECDSA)) { + return SignatureAlgorithms.SHA384_WITH_ECDSA; + } else if (algorithms.contains(SignatureAlgorithms.DSA)) { + return SignatureAlgorithms.DSA; + + } else { + throw new AlgorithmUnavailableException( + "No algorithm for key entry: " + selectedKeyID, + null, + null); + } + } else if (digestMethod.compareTo("SHA-512") == 0) { + if (algorithms.contains(SignatureAlgorithms.SHA512_WITH_RSA)) { + return SignatureAlgorithms.SHA512_WITH_RSA; + + } else if (algorithms.contains(SignatureAlgorithms.SHA512_WITH_ECDSA)) { + return SignatureAlgorithms.SHA512_WITH_ECDSA; + + } else if (algorithms.contains(SignatureAlgorithms.DSA)) { + return SignatureAlgorithms.DSA; + + } else { + throw new AlgorithmUnavailableException( + "No algorithm for key entry: " + selectedKeyID, + null, + null); + } + } else { + throw new AlgorithmUnavailableException( + "No signature algorithm found for digest algorithm '" + digestMethod, + null, + null); + } + + } - /** * @see iaik.server.modules.xmlsign.XMLSignatureCreationProfile#getSignedProperties() */ + @Override public List getSignedProperties() { return signedProperties; } @@ -221,38 +219,38 @@ public class CMSSignatureCreationProfileImpl /** * @see iaik.server.modules.xmlsign.XMLSignatureCreationProfile#isSecurityLayerConform() */ + @Override public boolean isSecurityLayerConform() { return securityLayerConform; } /** * Sets the security layer conformity. - * - * @param securityLayerConform true, if the created signature - * is to be conform to the Security Layer specification. + * + * @param securityLayerConform true, if the created signature is to + * be conform to the Security Layer specification. */ public void setSecurityLayerConform(boolean securityLayerConform) { this.securityLayerConform = securityLayerConform; } - public void setDigestMethod(String digestMethod) { - this.digestMethod = digestMethod; + this.digestMethod = digestMethod; } - + @Override public String getMimeType() { - return mimeType; + return mimeType; } + @Override public boolean includeData() { - return this.includeData; + return this.includeData; } - -@Override -public boolean isPAdESConform() { - return this.isPAdESConform; -} + @Override + public boolean isPAdESConform() { + return this.isPAdESConform; + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/cmsverify/CMSSignatureVerificationProfileImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/cmsverify/CMSSignatureVerificationProfileImpl.java index ab807ae..2247090 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/cmsverify/CMSSignatureVerificationProfileImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/cmsverify/CMSSignatureVerificationProfileImpl.java @@ -24,40 +24,42 @@ package at.gv.egovernment.moa.spss.server.iaik.cmsverify; import iaik.pki.PKIProfile; +import iaik.server.modules.SignatureVerificationProfile; import iaik.server.modules.cmsverify.CMSSignatureVerificationProfile; /** * An implementation of the CMSSignatureVerificationProfile * interface. - * + * * @see iaik.server.modules.cmsverify.CMSSignatureVerificationProfile * @author Patrick Peck * @version $Id$ */ public class CMSSignatureVerificationProfileImpl implements CMSSignatureVerificationProfile { - /** The profile for validating the certificate. */ - private PKIProfile certificateValidationProfile; + /** The profile for validating the certificate. */ + private PKIProfile certificateValidationProfile; - /** - * @see iaik.server.modules.cmsverify.CMSSignatureVerificationProfile#getCertificateValidationProfile() - */ - public PKIProfile getCertificateValidationProfile() { - return certificateValidationProfile; - } + /** + * @see iaik.server.modules.cmsverify.CMSSignatureVerificationProfile#getCertificateValidationProfile() + */ + @Override + public PKIProfile getCertificateValidationProfile() { + return certificateValidationProfile; + } - /** - * Sets the profile for validating the signer certificate. - * - * @param certificateValidationProfile - * The certificate validation profile to set. - */ - public void setCertificateValidationProfile(PKIProfile certificateValidationProfile) { - this.certificateValidationProfile = certificateValidationProfile; - } + /** + * Sets the profile for validating the signer certificate. + * + * @param certificateValidationProfile The certificate validation profile to + * set. + */ + public void setCertificateValidationProfile(PKIProfile certificateValidationProfile) { + this.certificateValidationProfile = certificateValidationProfile; + } - @Override - public String getTargetLevel() { - return CMSSignatureVerificationProfile.LEVEL_LTA; - } + @Override + public String getTargetLevel() { + return SignatureVerificationProfile.LEVEL_LTA; + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/cmsverify/PDFSignatureVerificationProfileImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/cmsverify/PDFSignatureVerificationProfileImpl.java index 785c85b..18a9f9c 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/cmsverify/PDFSignatureVerificationProfileImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/cmsverify/PDFSignatureVerificationProfileImpl.java @@ -3,6 +3,6 @@ package at.gv.egovernment.moa.spss.server.iaik.cmsverify; import iaik.server.modules.pdfverify.PDFSignatureVerificationProfile; public class PDFSignatureVerificationProfileImpl extends CMSSignatureVerificationProfileImpl - implements PDFSignatureVerificationProfile { + implements PDFSignatureVerificationProfile { } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/AbstractKeyModuleConfigurationImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/AbstractKeyModuleConfigurationImpl.java index 90e6793..1cd4b64 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/AbstractKeyModuleConfigurationImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/AbstractKeyModuleConfigurationImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.config; import iaik.server.modules.keys.KeyModuleConfiguration; @@ -29,22 +28,22 @@ import iaik.server.modules.keys.KeyModuleConfiguration; /** * Base implementation class for the KeyModuleConfiguration * interface and the interfaces derived from it. - * + * * @see iaik.server.modules.keys.KeyModuleConfiguration * @author Patrick Peck * @version $Id$ */ public abstract class AbstractKeyModuleConfigurationImpl - implements KeyModuleConfiguration { + implements KeyModuleConfiguration { + + /** The module ID. */ + private final String moduleID; - /** The module ID. */ - private String moduleID; - /** * Creata new AbstractKeyModuleConfigurationImpl. - * + * * @param moduleID The key module ID of this - * KeyModuleConfiguration. + * KeyModuleConfiguration. */ public AbstractKeyModuleConfigurationImpl(String moduleID) { this.moduleID = moduleID; @@ -53,6 +52,7 @@ public abstract class AbstractKeyModuleConfigurationImpl /** * @see iaik.server.modules.keys.KeyModuleConfiguration#getModuleID() */ + @Override public String getModuleID() { return moduleID; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/AbstractObservableConfiguration.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/AbstractObservableConfiguration.java index e2d828b..a9dfe2d 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/AbstractObservableConfiguration.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/AbstractObservableConfiguration.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.config; import java.util.ArrayList; @@ -34,18 +33,19 @@ import iaik.pki.store.observer.Observer; /** * A base class for observable configuration data. - * + * * @author Patrick Peck * @version $Id$ */ public abstract class AbstractObservableConfiguration implements Observable { /** The observers registered with this Observable. */ - private List observers = new ArrayList(); + private final List observers = new ArrayList(); /** * @see iaik.pki.store.observer.Observable#addObserver(iaik.pki.store.observer.Observer) */ + @Override public void addObserver(Observer observer) { observers.add(observer); } @@ -53,6 +53,7 @@ public abstract class AbstractObservableConfiguration implements Observable { /** * @see iaik.pki.store.observer.Observable#removeObserver(iaik.pki.store.observer.Observer) */ + @Override public boolean removeObserver(Observer observer) { return observers.remove(observer); } @@ -60,13 +61,14 @@ public abstract class AbstractObservableConfiguration implements Observable { /** * @see iaik.pki.store.observer.Observable#notify(iaik.pki.store.observer.NotificationData) */ + @Override public void notify(NotificationData data) { Iterator iter = observers.iterator(); for (iter = observers.iterator(); iter.hasNext();) { - Observer observer = (Observer) iter.next(); + final Observer observer = (Observer) iter.next(); observer.notify(data); } } - + } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/ArchiveConfigurationImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/ArchiveConfigurationImpl.java index 4a300a2..ff9927b 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/ArchiveConfigurationImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/ArchiveConfigurationImpl.java @@ -21,76 +21,68 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.config; -import iaik.pki.store.revocation.archive.ArchiveConfiguration; -import iaik.pki.store.revocation.archive.ArchiveParameters; -import iaik.pki.store.revocation.archive.ArchiveTypes; - import java.sql.Driver; import java.sql.DriverManager; import java.util.Enumeration; import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; +import iaik.pki.store.revocation.archive.ArchiveConfiguration; +import iaik.pki.store.revocation.archive.ArchiveParameters; +import iaik.pki.store.revocation.archive.ArchiveTypes; /** - * An implementation of the ArchiveConfiguration interface - * using configuration data provided by the MOA configuration file. - * + * An implementation of the ArchiveConfiguration interface using + * configuration data provided by the MOA configuration file. + * * @see iaik.pki.store.revocation.archive.ArchiveConfiguration * @author Patrick Peck * @version $Id$ */ public class ArchiveConfigurationImpl - extends AbstractObservableConfiguration - implements ArchiveConfiguration { - + extends AbstractObservableConfiguration + implements ArchiveConfiguration { + /** The configuration parameters of the archive. */ - private ArchiveParameters archiveParameters; + private final ArchiveParameters archiveParameters; /** * Create a new ArchiveConfigurationImpl. - * - * @param config The MOA configuration from which the configuration data is being read. + * + * @param config The MOA configuration from which the configuration data is + * being read. */ - public ArchiveConfigurationImpl(ConfigurationProvider config) - { - String jdbcUrl = config.getRevocationArchiveJDBCURL(); + public ArchiveConfigurationImpl(ConfigurationProvider config) { + final String jdbcUrl = config.getRevocationArchiveJDBCURL(); this.archiveParameters = new DataBaseArchiveParameterImpl(jdbcUrl); - - // Register JDBC driver class - if (jdbcUrl != null) - { - String jdbcDriverClass = config.getRevocationArchiveJDBCDriverClass(); - try - { + + // Register JDBC driver class + if (jdbcUrl != null) { + final String jdbcDriverClass = config.getRevocationArchiveJDBCDriverClass(); + try { Class.forName(jdbcDriverClass); - } - catch (ClassNotFoundException e) - { + } catch (final ClassNotFoundException e) { // TODO 20030709 GK Improve exception handling - throw new RuntimeException("JDBC driver class \"" + jdbcDriverClass + " could not be found."); + throw new RuntimeException("JDBC driver class \"" + jdbcDriverClass + " could not be found."); } - - Enumeration regDrivers = DriverManager.getDrivers(); + + final Enumeration regDrivers = DriverManager.getDrivers(); boolean isRegistered = false; - while (regDrivers.hasMoreElements()) - { - Object currentDriver = regDrivers.nextElement(); - if (jdbcDriverClass.equals(currentDriver.getClass().getName())) isRegistered = true; - } - if (!isRegistered) - { - // Workaround for a driver which does not register itselve at invocation of Class.forName(drvname) - try - { - DriverManager.registerDriver((Driver)Class.forName(jdbcDriverClass).newInstance()); + while (regDrivers.hasMoreElements()) { + final Object currentDriver = regDrivers.nextElement(); + if (jdbcDriverClass.equals(currentDriver.getClass().getName())) { + isRegistered = true; } - catch (Exception e) - { + } + if (!isRegistered) { + // Workaround for a driver which does not register itselve at invocation of + // Class.forName(drvname) + try { + DriverManager.registerDriver((Driver) Class.forName(jdbcDriverClass).newInstance()); + } catch (final Exception e) { // TODO 20030709 GK Improve exception handling - throw new RuntimeException("Registering JDBC driver \"" + jdbcDriverClass + " failed."); + throw new RuntimeException("Registering JDBC driver \"" + jdbcDriverClass + " failed."); } } } @@ -98,11 +90,13 @@ public class ArchiveConfigurationImpl /** * Return the type of archive. - * + * * This will always return ArchiveTypes.DATABASE. + * * @return ArchiveTypes.DATABASE. * @see iaik.pki.store.revocation.archive.ArchiveConfiguration#getType() */ + @Override public String getType() { return ArchiveTypes.DATABASE; } @@ -110,10 +104,11 @@ public class ArchiveConfigurationImpl /** * Return the ArchiveParameters describing this * ArchiveConfiguration. - * + * * @return The archive parameters. * @see iaik.pki.store.revocation.archive.ArchiveConfiguration#getArchiveParameters() */ + @Override public ArchiveParameters getArchiveParameters() { return archiveParameters; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/CRLRetriever.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/CRLRetriever.java index d752a63..d1b776b 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/CRLRetriever.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/CRLRetriever.java @@ -23,13 +23,6 @@ package at.gv.egovernment.moa.spss.server.iaik.config; -import iaik.logging.TransactionId; -import iaik.pki.revocation.RevocationSourceTypes; -import iaik.pki.store.revocation.RevocationInfoRetriever; -import iaik.pki.store.revocation.RevocationSource; -import iaik.pki.store.revocation.RevocationStoreException; -import iaik.pki.ldap.Handler; - import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; @@ -39,6 +32,12 @@ import java.util.Collection; import java.util.Date; import at.gv.egovernment.moaspss.logging.Logger; +import iaik.logging.TransactionId; +import iaik.pki.ldap.Handler; +import iaik.pki.revocation.RevocationSourceTypes; +import iaik.pki.store.revocation.RevocationInfoRetriever; +import iaik.pki.store.revocation.RevocationSource; +import iaik.pki.store.revocation.RevocationStoreException; /** * A customized implementation of @@ -47,55 +46,56 @@ import at.gv.egovernment.moaspss.logging.Logger; * {@link iaik.pki.store.revocation.CRLRetriever} to overcome a classloader * problem in connection with the {@link java.net.URL} class in a Tomcat * deployment environment. - * + * * @author Gregor Karlinger * @version $$ */ public class CRLRetriever implements RevocationInfoRetriever { - - private int connectTimeout = 5; - private int readTimeout = 5; - - - public void update(RevocationSource source, Collection supplementalRequestData, TransactionId tid) - throws RevocationStoreException { - if (source == null) { - throw new NullPointerException("RevocationSource parameter mustn't be null."); - } - Logger.info("Downloading crl from " + source.getUri()); - if (!source.getType().equals(RevocationSourceTypes.CRL)) { - throw new RevocationStoreException(source.getType() + " not supported", null, getClass().getName() + ":1"); - } - try { - URL crlUrl; - try { - crlUrl = new URL(source.getUri()); - } catch (MalformedURLException e) { - // Workaround for classloader problem with deployment in Tomcat - // 4.1 - URLStreamHandler handler = new Handler(); - crlUrl = new URL(null, source.getUri(), handler); - } - URLConnection con = crlUrl.openConnection(); - con.setConnectTimeout(connectTimeout); - con.setReadTimeout(readTimeout); - InputStream crlInputStream = con.getInputStream(); - source.readFrom(crlInputStream, tid); - source.setDownloadTime(new Date()); - crlInputStream.close(); - } catch (Exception iox) { - Logger.warn("Cannot retrieve crl", iox); - throw new RevocationStoreException("Cannot retrieve CRL", iox, getClass().getName() + ":1"); - } - } - @Override - public void setConnectTimeout(int arg0) { - this.connectTimeout = arg0; - } + private int connectTimeout = 5; + private int readTimeout = 5; + + @Override + public void update(RevocationSource source, Collection supplementalRequestData, TransactionId tid) + throws RevocationStoreException { + if (source == null) { + throw new NullPointerException("RevocationSource parameter mustn't be null."); + } + Logger.info("Downloading crl from " + source.getUri()); + if (!source.getType().equals(RevocationSourceTypes.CRL)) { + throw new RevocationStoreException(source.getType() + " not supported", null, getClass().getName() + + ":1"); + } + try { + URL crlUrl; + try { + crlUrl = new URL(source.getUri()); + } catch (final MalformedURLException e) { + // Workaround for classloader problem with deployment in Tomcat + // 4.1 + final URLStreamHandler handler = new Handler(); + crlUrl = new URL(null, source.getUri(), handler); + } + final URLConnection con = crlUrl.openConnection(); + con.setConnectTimeout(connectTimeout); + con.setReadTimeout(readTimeout); + final InputStream crlInputStream = con.getInputStream(); + source.readFrom(crlInputStream, tid); + source.setDownloadTime(new Date()); + crlInputStream.close(); + } catch (final Exception iox) { + Logger.warn("Cannot retrieve crl", iox); + throw new RevocationStoreException("Cannot retrieve CRL", iox, getClass().getName() + ":1"); + } + } + + @Override + public void setConnectTimeout(int arg0) { + this.connectTimeout = arg0; + } - @Override - public void setReadTimeout(int arg0) { - this.readTimeout = arg0; - } + @Override + public void setReadTimeout(int arg0) { + this.readTimeout = arg0; + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/CertStoreConfigurationImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/CertStoreConfigurationImpl.java index 43483a0..052a3c5 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/CertStoreConfigurationImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/CertStoreConfigurationImpl.java @@ -23,77 +23,71 @@ package at.gv.egovernment.moa.spss.server.iaik.config; -import java.io.File; -import java.io.IOException; - -import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import at.gv.egovernment.moa.sig.tsl.exception.TslException; import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; -import at.gv.egovernment.moa.spss.server.logging.IaikLog; -import at.gv.egovernment.moa.spss.server.logging.TransactionId; import at.gv.egovernment.moa.spss.tsl.TSLServiceFactory; -import iaik.logging.Log; import iaik.pki.store.certstore.CertStoreConfiguration; import iaik.pki.store.certstore.CertStoreParameters; import iaik.pki.store.certstore.directory.DirectoryCertStoreParameters; -import iaik.pki.store.certstore.directory.DirectoryStoreException; -import iaik.pki.store.certstore.utils.DirectoryCertStoreConverter; /** * An implementation of the CertStoreConfiguration interface based * on MOA configuration data. - * + * * @see iaik.pki.store.certstore.CertStoreConfiguration * @author Patrick Peck * @version $Id$ */ -public class CertStoreConfigurationImpl extends AbstractObservableConfiguration implements CertStoreConfiguration { +public class CertStoreConfigurationImpl extends AbstractObservableConfiguration implements + CertStoreConfiguration { + + private static final Logger logger = LoggerFactory.getLogger(CertStoreConfigurationImpl.class); + + /** The configuration parameters of the CertStore. */ + private CertStoreParameters[] parameters; + + /** + * Create a new CertStoreConfigurationImpl. + * + * @param config The MOA configuration from which the configuration data is + * being read. + */ + public CertStoreConfigurationImpl(ConfigurationProvider config) { + final String certStoreRoot = config.getCertStoreLocation(); + + final DirectoryCertStoreParameters dirParameters = new DirectoryCertStoreParametersImpl( + "MOA Directory CertStore", + certStoreRoot, true, false); - private static final Logger logger = LoggerFactory.getLogger(CertStoreConfigurationImpl.class); + if (TSLServiceFactory.isInitialized()) { + try { + final CertStoreParameters tslCertStore = TSLServiceFactory.getTSLServiceClient() + .getCertStoreWithTSLCertificates(); + parameters = new CertStoreParameters[] { dirParameters, tslCertStore }; - /** The configuration parameters of the CertStore. */ - private CertStoreParameters[] parameters; + } catch (final TslException e) { + logger.warn("TSL based CertStore initialisation FAILED.", e); + logger.warn("Only Directory based CertStore is used ... "); + parameters = new CertStoreParameters[] { dirParameters }; + } - /** - * Create a new CertStoreConfigurationImpl. - * - * @param config - * The MOA configuration from which the configuration data is - * being read. - */ - public CertStoreConfigurationImpl(ConfigurationProvider config) { - String certStoreRoot = config.getCertStoreLocation(); + } else { + logger.info("Trust-Status List support is not active. Use only Directory based CertStore."); + parameters = new CertStoreParameters[] { dirParameters }; - DirectoryCertStoreParameters dirParameters = new DirectoryCertStoreParametersImpl("MOA Directory CertStore", - certStoreRoot, true, false); + } - if (TSLServiceFactory.isInitialized()) { - try { - CertStoreParameters tslCertStore = TSLServiceFactory.getTSLServiceClient().getCertStoreWithTSLCertificates(); - parameters = new CertStoreParameters[] { dirParameters, tslCertStore}; - - } catch (TslException e) { - logger.warn("TSL based CertStore initialisation FAILED.", e); - logger.warn("Only Directory based CertStore is used ... "); - parameters = new CertStoreParameters[] { dirParameters }; - } - - } else { - logger.info("Trust-Status List support is not active. Use only Directory based CertStore."); - parameters = new CertStoreParameters[] { dirParameters }; - - } - - } + } - /** - * @see iaik.pki.store.certstore.CertStoreConfiguration#getParameters() - */ - public CertStoreParameters[] getParameters() { - return parameters; - } + /** + * @see iaik.pki.store.certstore.CertStoreConfiguration#getParameters() + */ + @Override + public CertStoreParameters[] getParameters() { + return parameters; + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/ConfigurationDataImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/ConfigurationDataImpl.java index dff78d6..891f078 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/ConfigurationDataImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/ConfigurationDataImpl.java @@ -21,43 +21,41 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.config; import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import iaik.logging.LoggerConfig; -import iaik.pki.PKIConfiguration; -import iaik.server.ConfigurationData; - +import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; import at.gv.egovernment.moa.spss.server.config.HardwareCryptoModule; import at.gv.egovernment.moa.spss.server.config.HardwareKeyModule; -import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; import at.gv.egovernment.moa.spss.server.config.SoftwareKeyModule; +import iaik.logging.LoggerConfig; +import iaik.pki.PKIConfiguration; +import iaik.server.ConfigurationData; /** - * An implementation of the ConfigurationData interface using - * MOA configuration data. - * + * An implementation of the ConfigurationData interface using MOA + * configuration data. + * * @see iaik.server.ConfigurationData * @author Patrick Peck * @version $Id$ */ public class ConfigurationDataImpl implements ConfigurationData { /** PKI configuration data. */ - private PKIConfiguration pkiConfiguration; + private final PKIConfiguration pkiConfiguration; /** Crypto modules configuration data. */ - private List cryptoModuleConfigurations; + private final List cryptoModuleConfigurations; /** Key modules configuration data. */ - private List keyModuleConfigurations; + private final List keyModuleConfigurations; /** Logging configuration data. */ - private LoggerConfig loggerConfig; + private final LoggerConfig loggerConfig; /** * Create a new ConfigurationDataImpl. - * + * * @param config The underlying MOA configuration data. */ public ConfigurationDataImpl(ConfigurationProvider config) { @@ -69,54 +67,55 @@ public class ConfigurationDataImpl implements ConfigurationData { /** * Build the list of CryptoModuleConfigurations. - * + * * @param config The underlying MOA configuration data. - * @return The list of CryptoModuleConfigurations configured in - * the MOA configuration. + * @return The list of CryptoModuleConfigurations configured in the + * MOA configuration. */ private List buildCryptoModuleConfigurations(ConfigurationProvider config) { - List modules = new ArrayList(); - Iterator iter = config.getHardwareCryptoModules().iterator(); - + final List modules = new ArrayList(); + final Iterator iter = config.getHardwareCryptoModules().iterator(); + while (iter.hasNext()) { - HardwareCryptoModule module = (HardwareCryptoModule) iter.next(); + final HardwareCryptoModule module = (HardwareCryptoModule) iter.next(); modules.add(new HardwareCryptoModuleConfigurationImpl(module)); } - + return modules; } - + /** * Build the list of KeyModuleConfigurations. - * + * * @param config The underlying MOA configuration data. * @return The list of KeyModuleConfigurations configured in the - * MOA configuration. + * MOA configuration. */ private List buildKeyModuleConfigurations(ConfigurationProvider config) { - List keys = new ArrayList(); + final List keys = new ArrayList(); Iterator iter; - + // add the hardware keys iter = config.getHardwareKeyModules().iterator(); while (iter.hasNext()) { - HardwareKeyModule key = (HardwareKeyModule) iter.next(); + final HardwareKeyModule key = (HardwareKeyModule) iter.next(); keys.add(new HardwareKeyModuleConfigurationImpl(key)); } - + // add the software keys iter = config.getSoftwareKeyModules().iterator(); while (iter.hasNext()) { - SoftwareKeyModule key = (SoftwareKeyModule) iter.next(); + final SoftwareKeyModule key = (SoftwareKeyModule) iter.next(); keys.add(new SoftwareKeyModuleConfigurationImpl(key)); } - + return keys; } /** * @see iaik.server.ConfigurationData#getPKIConfiguration() */ + @Override public PKIConfiguration getPKIConfiguration() { return pkiConfiguration; } @@ -124,6 +123,7 @@ public class ConfigurationDataImpl implements ConfigurationData { /** * @see iaik.server.ConfigurationData#getCryptoModuleConfigurations() */ + @Override public List getCryptoModuleConfigurations() { return cryptoModuleConfigurations; } @@ -131,6 +131,7 @@ public class ConfigurationDataImpl implements ConfigurationData { /** * @see iaik.server.ConfigurationData#getKeyModuleConfigurations() */ + @Override public List getKeyModuleConfigurations() { return keyModuleConfigurations; } @@ -138,6 +139,7 @@ public class ConfigurationDataImpl implements ConfigurationData { /** * @see iaik.server.ConfigurationData#getLoggerConfig() */ + @Override public LoggerConfig getLoggerConfig() { return loggerConfig; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/DataBaseArchiveParameterImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/DataBaseArchiveParameterImpl.java index f4658a2..22cceeb 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/DataBaseArchiveParameterImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/DataBaseArchiveParameterImpl.java @@ -21,14 +21,13 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.config; import iaik.pki.store.revocation.archive.DataBaseArchiveParameters; /** * An implementation of the DataBaseArchiveParameter interface. - * + * * @see iaik.pki.store.revocation.archive.db.DataBaseArchiveParameter * @author Patrick Peck * @version $Id$ @@ -36,11 +35,11 @@ import iaik.pki.store.revocation.archive.DataBaseArchiveParameters; public class DataBaseArchiveParameterImpl implements DataBaseArchiveParameters { /** The JDBC URL for accessing the archive. */ - private String jDBCUrl; + private final String jDBCUrl; /** * Create a new DataBaseArchiveParameterImpl. - * + * * @param jDBCUrl The JDBC URL of the archive. */ public DataBaseArchiveParameterImpl(String jDBCUrl) { @@ -50,6 +49,7 @@ public class DataBaseArchiveParameterImpl implements DataBaseArchiveParameters { /** * @see iaik.pki.store.revocation.archive.db.DataBaseArchiveParameter#getJDBCUrl() */ + @Override public String getJDBCUrl() { return jDBCUrl; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/DirectoryCertStoreParametersImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/DirectoryCertStoreParametersImpl.java index 39da9cf..e48c7e7 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/DirectoryCertStoreParametersImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/DirectoryCertStoreParametersImpl.java @@ -21,50 +21,48 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.config; import java.util.Collections; import java.util.Set; -import iaik.pki.store.certstore.CertStoreParameters; import iaik.pki.store.certstore.CertStoreTypes; import iaik.pki.store.certstore.directory.DirectoryCertStoreParameters; /** * An implementation of the DirectoryCertStoreParameters interface. - * + * * @see iaik.pki.store.certstore.directory.DirectoryCertStoreParameters * @author Patrick Peck * @version $Id$ */ public class DirectoryCertStoreParametersImpl - implements DirectoryCertStoreParameters { + implements DirectoryCertStoreParameters { /** The root directory of the CertStore. */ - private String rootDirectory; + private final String rootDirectory; /** Whether a new directory may be created. */ - private boolean createNew; + private final boolean createNew; /** The CertStore ID. */ - private String id; + private final String id; /** Whether the CertStore is read-only. */ - private boolean readOnly; + private final boolean readOnly; /** * Create a new DirectoryCertStoreParameterImpl. - * - * @param id The CertStore ID. + * + * @param id The CertStore ID. * @param rootDirectory The root directory of the CertStore. - * @param createNew Whether a new directory may be created. - * @param readOnly Whether the CertStore is read-only. + * @param createNew Whether a new directory may be created. + * @param readOnly Whether the CertStore is read-only. */ public DirectoryCertStoreParametersImpl( - String id, - String rootDirectory, - boolean createNew, - boolean readOnly) { - - this.id = id; + String id, + String rootDirectory, + boolean createNew, + boolean readOnly) { + + this.id = id; this.rootDirectory = rootDirectory; this.createNew = createNew; this.readOnly = readOnly; @@ -73,6 +71,7 @@ public class DirectoryCertStoreParametersImpl /** * @see iaik.pki.store.certstore.directory.DirectoryCertStoreParameters#getRootDirectory() */ + @Override public String getRootDirectory() { return rootDirectory; } @@ -80,6 +79,7 @@ public class DirectoryCertStoreParametersImpl /** * @see iaik.pki.store.certstore.directory.DirectoryCertStoreParameters#createNew() */ + @Override public boolean createNew() { return createNew; } @@ -87,6 +87,7 @@ public class DirectoryCertStoreParametersImpl /** * @see iaik.pki.store.certstore.CertStoreParameters#getId() */ + @Override public String getId() { return id; } @@ -94,6 +95,7 @@ public class DirectoryCertStoreParametersImpl /** * @see iaik.pki.store.certstore.CertStoreParameters#isReadOnly() */ + @Override public boolean isReadOnly() { return readOnly; } @@ -102,14 +104,15 @@ public class DirectoryCertStoreParametersImpl * @return CertStoreTypes.DIRECTORY * @see iaik.pki.store.certstore.CertStoreParameters#getType() */ + @Override public String getType() { return CertStoreTypes.DIRECTORY; } -@Override -public Set getVirtualStores() { - // TODO AFITZEK IMPLEMENT THIS METHOD - return Collections.EMPTY_SET; -} + @Override + public Set getVirtualStores() { + // TODO AFITZEK IMPLEMENT THIS METHOD + return Collections.EMPTY_SET; + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/HardwareCryptoModuleConfigurationImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/HardwareCryptoModuleConfigurationImpl.java index c9904c5..6275e08 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/HardwareCryptoModuleConfigurationImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/HardwareCryptoModuleConfigurationImpl.java @@ -21,32 +21,30 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.config; -import iaik.server.modules.crypto.HardwareCryptoModuleConfiguration; - import at.gv.egovernment.moa.spss.server.config.HardwareCryptoModule; +import iaik.server.modules.crypto.HardwareCryptoModuleConfiguration; /** * An implementation of the HardwareCryptoModuleConfiguration * wrapping a HardwareCryptoModule from the MOA configuration. - * + * * @author Patrick Peck * @version $Id$ */ public class HardwareCryptoModuleConfigurationImpl - implements HardwareCryptoModuleConfiguration { - - /** The wrapped HardwareCryptoModule. */ - private HardwareCryptoModule module; - + implements HardwareCryptoModuleConfiguration { + + /** The wrapped HardwareCryptoModule. */ + private final HardwareCryptoModule module; + /** * Create a new HardwareCryptoModuleConfigurationImpl. - * + * * @param module The HardwareCryptoModule from the underlying MOA - * configuration. - */ + * configuration. + */ public HardwareCryptoModuleConfigurationImpl(HardwareCryptoModule module) { this.module = module; } @@ -54,6 +52,7 @@ public class HardwareCryptoModuleConfigurationImpl /** * @see iaik.server.modules.crypto.HardwareCryptoModuleConfiguration#getModuleName() */ + @Override public String getModuleName() { return module.getName(); } @@ -61,6 +60,7 @@ public class HardwareCryptoModuleConfigurationImpl /** * @see iaik.server.modules.crypto.HardwareCryptoModuleConfiguration#getSlotID() */ + @Override public String getSlotID() { return module.getSlotID(); } @@ -68,6 +68,7 @@ public class HardwareCryptoModuleConfigurationImpl /** * @see iaik.server.modules.crypto.HardwareCryptoModuleConfiguration#getUserPIN() */ + @Override public char[] getUserPIN() { return module.getUserPIN().toCharArray(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/HardwareKeyModuleConfigurationImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/HardwareKeyModuleConfigurationImpl.java index 05f5633..9b37c60 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/HardwareKeyModuleConfigurationImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/HardwareKeyModuleConfigurationImpl.java @@ -21,34 +21,32 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.config; -import iaik.server.modules.keys.HardwareKeyModuleConfiguration; - import at.gv.egovernment.moa.spss.server.config.HardwareKeyModule; +import iaik.server.modules.keys.HardwareKeyModuleConfiguration; /** * An implementation of the HardwareKeyModuleConfiguration * interface wrapping a HardwareKeyModule from the MOA * configuration. - * + * * @see iaik.server.modules.keys.HardwareKeyModuleConfiguration * @author Patrick Peck * @version $Id$ */ public class HardwareKeyModuleConfigurationImpl - extends AbstractKeyModuleConfigurationImpl - implements HardwareKeyModuleConfiguration { + extends AbstractKeyModuleConfigurationImpl + implements HardwareKeyModuleConfiguration { /** The wrapped HardwareKeyModule. */ - private HardwareKeyModule keyModule; + private final HardwareKeyModule keyModule; /** * Create a new HardwareKeyModuleConfigurationImpl. - * - * @param keyModule The HardwareKeyModule from the underlying - * MOA configuration. + * + * @param keyModule The HardwareKeyModule from the underlying MOA + * configuration. */ public HardwareKeyModuleConfigurationImpl(HardwareKeyModule keyModule) { super(keyModule.getId()); @@ -58,6 +56,7 @@ public class HardwareKeyModuleConfigurationImpl /** * @see iaik.server.modules.keys.HardwareKeyModuleConfiguration#getModuleName() */ + @Override public String getModuleName() { return keyModule.getName(); } @@ -65,6 +64,7 @@ public class HardwareKeyModuleConfigurationImpl /** * @see iaik.server.modules.keys.HardwareKeyModuleConfiguration#getSlotID() */ + @Override public String getSlotID() { return keyModule.getSlotID(); } @@ -72,6 +72,7 @@ public class HardwareKeyModuleConfigurationImpl /** * @see iaik.server.modules.keys.HardwareKeyModuleConfiguration#getUserPIN() */ + @Override public char[] getUserPIN() { return keyModule.getUserPIN().toCharArray(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/IaikConfigurator.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/IaikConfigurator.java index 1a41499..8ca19e4 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/IaikConfigurator.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/IaikConfigurator.java @@ -21,27 +21,10 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.config; -import iaik.cms.IaikCCProvider; -import iaik.esi.sva.Configuration; -import iaik.logging.LogFactory; -import iaik.pki.store.revocation.RevocationFactory; -import iaik.pki.store.revocation.RevocationSourceStore; -import iaik.pki.store.truststore.TrustStoreFactory; -import iaik.security.ec.provider.ECCelerate; -import iaik.server.ConfigurationData; -import iaik.server.Configurator; -import iaik.server.modules.keys.KeyEntryID; -import iaik.server.modules.keys.KeyModule; -import iaik.server.modules.keys.KeyModuleFactory; - -import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; -import java.security.Provider; -import java.security.Security; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -54,99 +37,109 @@ 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.config.KeyGroup; import at.gv.egovernment.moa.spss.server.config.KeyGroupEntry; -import at.gv.egovernment.moa.spss.server.init.SystemInitializer; import at.gv.egovernment.moa.spss.server.logging.TransactionId; import at.gv.egovernment.moa.spss.util.CertStoreConverter; import at.gv.egovernment.moa.spss.util.MessageProvider; import at.gv.egovernment.moa.spss.util.SecProviderUtils; import at.gv.egovernment.moaspss.logging.LogMsg; import at.gv.egovernment.moaspss.logging.Logger; +import iaik.logging.LogFactory; +import iaik.pki.store.revocation.RevocationFactory; +import iaik.pki.store.revocation.RevocationSourceStore; +import iaik.pki.store.truststore.TrustStoreFactory; +import iaik.server.ConfigurationData; +import iaik.server.Configurator; +import iaik.server.modules.keys.KeyEntryID; +import iaik.server.modules.keys.KeyModule; +import iaik.server.modules.keys.KeyModuleFactory; /** * A class responsible for configuring the IAIK MOA modules. - * + * * @author Patrick Peck * @version $Id$ */ public class IaikConfigurator { - private static final org.slf4j.Logger logger = LoggerFactory.getLogger(IaikConfigurator.class); - + private static final org.slf4j.Logger logger = LoggerFactory.getLogger(IaikConfigurator.class); + /** The warnings encountered during configuration. */ private List warnings = new ArrayList(); /** * Configure the IAIK MOA subsystem. - * - * + * + * * @param moaConfig The underlying MOA configuration. * @return Returns the config data of the underlying MOA subsystem - * @throws ConfigurationException An error occurred configuring the IAIK - * MOA subsystem. + * @throws ConfigurationException An error occurred configuring the IAIK MOA + * subsystem. */ public ConfigurationData configure(ConfigurationProvider moaConfig) - throws ConfigurationException { - ConfigurationData configData = new ConfigurationDataImpl(moaConfig); - + throws ConfigurationException { + final ConfigurationData configData = new ConfigurationDataImpl(moaConfig); + warnings = new ArrayList(); try { - TransactionId transId = new TransactionId("IaikConfigurator"); - - //iaik.esi.sva.Configuration config = new Configuration(IaikConfigurator.class.getResourceAsStream("/sva.config")); - - //SecProviderUtils.dumpSecProviders("Starting configuration"); - + final TransactionId transId = new TransactionId("IaikConfigurator"); + + // iaik.esi.sva.Configuration config = new + // Configuration(IaikConfigurator.class.getResourceAsStream("/sva.config")); + + // SecProviderUtils.dumpSecProviders("Starting configuration"); + LogFactory.configure(configData.getLoggerConfig()); - + try { - iaik.pki.Configurator.initCommon(configData.getLoggerConfig(), - transId); - //SecProviderUtils.dumpSecProviders("initCommon"); - String certStoreRoot = moaConfig.getCertStoreLocation(); - CertStoreConverter.convert(certStoreRoot, transId); + iaik.pki.Configurator.initCommon(configData.getLoggerConfig(), + transId); + // SecProviderUtils.dumpSecProviders("initCommon"); + final String certStoreRoot = moaConfig.getCertStoreLocation(); + CertStoreConverter.convert(certStoreRoot, transId); } finally { - //Security.removeProvider(ECCelerate.getInstance().getName()); + // Security.removeProvider(ECCelerate.getInstance().getName()); } - + Configurator.init(configData, transId); - + SecProviderUtils.dumpSecProviders("Fully configured!"); - - // Set customized CRL retriever to overcome a classloader problem when MOA is deployed in Tomcat - RevocationSourceStore rss = RevocationFactory.getInstance(transId).getRevocationSourceStore(); - //rss.setRetriever(new CRLRetriever(), RevocationSourceTypes.CRL); - if ((moaConfig.getSoftwareKeyModules().size() > 0) || (moaConfig.getHardwareKeyModules().size() > 0)) { + + // Set customized CRL retriever to overcome a classloader problem when MOA is + // deployed in Tomcat + final RevocationSourceStore rss = RevocationFactory.getInstance(transId).getRevocationSourceStore(); + // rss.setRetriever(new CRLRetriever(), RevocationSourceTypes.CRL); + if (moaConfig.getSoftwareKeyModules().size() > 0 || moaConfig.getHardwareKeyModules().size() > 0) { dumpKeyEntryIDs(); } checkKeyGroupConfig(moaConfig); TrustStoreFactory.reset(); - + return configData; - } catch (iaik.server.ConfigurationException e) { - logException(e); - throw new ConfigurationException("config.08", null, e); - - } catch (Throwable t) { - logException(t); - throw new ConfigurationException("config.08", null, t); - + } catch (final iaik.server.ConfigurationException e) { + logException(e); + throw new ConfigurationException("config.08", null, e); + + } catch (final Throwable t) { + logException(t); + throw new ConfigurationException("config.08", null, t); + } } - private void logException(Throwable e) { - StringWriter out = new StringWriter(); - PrintWriter writer = new PrintWriter(out); + private void logException(Throwable e) { + final StringWriter out = new StringWriter(); + final PrintWriter writer = new PrintWriter(out); e.printStackTrace(writer); - logger.error("IAIK_Module error: {}",out.toString()); - + logger.error("IAIK_Module error: {}", out.toString()); + } -/** + /** * Return the warnings encountered during configuration. - * + * * @return The warnings. - */ + */ public List getWarnings() { return warnings; } @@ -156,71 +149,71 @@ public class IaikConfigurator { * KeyModules to the log file. */ private void dumpKeyEntryIDs() { - MessageProvider msg = MessageProvider.getInstance(); - KeyModule module = KeyModuleFactory.getInstance(new TransactionId("dump")); - Set keyEntryIds = module.getPrivateKeyEntryIDs(); + final MessageProvider msg = MessageProvider.getInstance(); + final KeyModule module = KeyModuleFactory.getInstance(new TransactionId("dump")); + final Set keyEntryIds = module.getPrivateKeyEntryIDs(); Iterator iter; for (iter = keyEntryIds.iterator(); iter.hasNext();) { - KeyEntryID keyEntryId = (KeyEntryID) iter.next(); + final KeyEntryID keyEntryId = (KeyEntryID) iter.next(); Logger.info( - new LogMsg(msg.getMessage("config.19", new Object[] { keyEntryId }))); + new LogMsg(msg.getMessage("config.19", new Object[] { keyEntryId }))); } } /** - * Check that each key group entry in each key group can be resolved to a + * Check that each key group entry in each key group can be resolved to a * KeyEntryID. - * + * * Logs a warning for each key group entry that cannot be resolved. - * + * * @param moaConfig The MOA configuration to check. */ private void checkKeyGroupConfig(ConfigurationProvider moaConfig) { - Map keyGroups = moaConfig.getKeyGroups(); + final Map keyGroups = moaConfig.getKeyGroups(); Iterator iter; for (iter = keyGroups.values().iterator(); iter.hasNext();) { - KeyGroup keyGroup = (KeyGroup) iter.next(); - Set keyGroupEntries = keyGroup.getKeyGroupEntries(); + final KeyGroup keyGroup = (KeyGroup) iter.next(); + final Set keyGroupEntries = keyGroup.getKeyGroupEntries(); Iterator kgIter; for (kgIter = keyGroupEntries.iterator(); kgIter.hasNext();) { - KeyGroupEntry entry = (KeyGroupEntry) kgIter.next(); + final KeyGroupEntry entry = (KeyGroupEntry) kgIter.next(); if (!findKeyEntryID(entry)) { warn( - "config.31", - new Object[] { - keyGroup.getId(), - entry.getModuleID(), - entry.getIssuerDN(), - entry.getSerialNumber()}); + "config.31", + new Object[] { + keyGroup.getId(), + entry.getModuleID(), + entry.getIssuerDN(), + entry.getSerialNumber() }); } } } } /** - * Find out that a certain KeyGroupEntry could be resolved to a KeyEntryID - * by the Configurator. + * Find out that a certain KeyGroupEntry could be resolved to a KeyEntryID by + * the Configurator. * * @param keyGroupEntry The key group entry to find. * @return true, if the keyGroupEntry could be - * resolved to a KeyEntryID; otherwise false. + * resolved to a KeyEntryID; otherwise false. */ private boolean findKeyEntryID(KeyGroupEntry keyGroupEntry) { - KeyModule module = KeyModuleFactory.getInstance(new TransactionId("check")); - Set keyEntryIDs = module.getPrivateKeyEntryIDs(); + final KeyModule module = KeyModuleFactory.getInstance(new TransactionId("check")); + final Set keyEntryIDs = module.getPrivateKeyEntryIDs(); Iterator iter; for (iter = keyEntryIDs.iterator(); iter.hasNext();) { - KeyEntryID entry = (KeyEntryID) iter.next(); + final KeyEntryID entry = (KeyEntryID) iter.next(); if (entry.getCertificateIssuer().equals(keyGroupEntry.getIssuerDN()) - && entry.getCertificateSerialNumber().equals( - keyGroupEntry.getSerialNumber()) - && entry.getModuleID().equals(keyGroupEntry.getModuleID())) { + && entry.getCertificateSerialNumber().equals( + keyGroupEntry.getSerialNumber()) + && entry.getModuleID().equals(keyGroupEntry.getModuleID())) { return true; } } @@ -230,14 +223,14 @@ public class IaikConfigurator { /** * Log a warning. - * + * * @param messageId The message ID. - * @param args Additional parameters for the message. + * @param args Additional parameters for the message. * @see at.gv.egovernment.moa.spss.server.util.MessageProvider */ private void warn(String messageId, Object[] args) { - MessageProvider msg = MessageProvider.getInstance(); - String txt = msg.getMessage(messageId, args); + final MessageProvider msg = MessageProvider.getInstance(); + final String txt = msg.getMessage(messageId, args); Logger.warn(new LogMsg(txt)); warnings.add(txt); diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/LoggerConfigImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/LoggerConfigImpl.java index 317fcca..7ba2122 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/LoggerConfigImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/LoggerConfigImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.config; import java.util.Properties; @@ -32,24 +31,27 @@ import iaik.logging.LoggerConfig; /** * Default implementation of the LoggerConfig interface. - * + * * @author Patrick Peck * @version $Id$ */ public class LoggerConfigImpl implements LoggerConfig { - + /** The implementation of iaik.logging.LogFactory. */ - private static final String DEFAULT_IMPLEMENTATION = - "at.gv.egovernment.moa.spss.server.logging.IaikLogFactory"; + private static final String DEFAULT_IMPLEMENTATION = + "at.gv.egovernment.moa.spss.server.logging.IaikLogFactory"; + @Override public String getFactory() { return DEFAULT_IMPLEMENTATION; } + @Override public Properties getProperties() throws LogConfigurationException { return new Properties(); } + @Override public String getNodeId() { return LoggingContextManager.getInstance().getLoggingContext().getNodeID(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/PKIConfigurationImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/PKIConfigurationImpl.java index 6341609..d54bcfd 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/PKIConfigurationImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/PKIConfigurationImpl.java @@ -23,93 +23,96 @@ package at.gv.egovernment.moa.spss.server.iaik.config; +import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; import iaik.pki.PKIConfiguration; import iaik.pki.pathvalidation.ValidationConfiguration; import iaik.pki.revocation.RevocationConfiguration; import iaik.pki.store.certstore.CertStoreConfiguration; import iaik.pki.store.revocation.archive.ArchiveConfiguration; -import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; /** * An implementation of the PKIConfiguration interface using data * from the MOA configuration. - * + * * @see iaik.pki.PKIConfiguration * @author Patrick Peck * @version $Id$ */ public class PKIConfigurationImpl implements PKIConfiguration { - /** The CertStore configuration. */ - private CertStoreConfiguration certStoreConfiguration; - /** The revocation checking configuration. */ - private RevocationConfiguration revocationConfiguration; - /** The revocation archive configuration. */ - private ArchiveConfiguration archiveConfiguration; - /** The certificate validation configuration. */ - private ValidationConfiguration validationConfiguration; - private int connectionTimeout; - private int readTimeout; + /** The CertStore configuration. */ + private final CertStoreConfiguration certStoreConfiguration; + /** The revocation checking configuration. */ + private final RevocationConfiguration revocationConfiguration; + /** The revocation archive configuration. */ + private ArchiveConfiguration archiveConfiguration; + /** The certificate validation configuration. */ + private final ValidationConfiguration validationConfiguration; + private final int connectionTimeout; + private final int readTimeout; - /** - * Create a new PKIConfigurationImpl. - * - * @param config - * The underlying MOA configuration which will be used to build - * the configuration data contained in this object. - */ - public PKIConfigurationImpl(ConfigurationProvider config) { + /** + * Create a new PKIConfigurationImpl. + * + * @param config The underlying MOA configuration which will be used to build + * the configuration data contained in this object. + */ + public PKIConfigurationImpl(ConfigurationProvider config) { - this.certStoreConfiguration = new CertStoreConfigurationImpl(config); - this.revocationConfiguration = new RevocationConfigurationImpl(config); + this.certStoreConfiguration = new CertStoreConfigurationImpl(config); + this.revocationConfiguration = new RevocationConfigurationImpl(config); - boolean archiveInfo = config.getEnableRevocationArchiving(); - if (archiveInfo) { - this.archiveConfiguration = new ArchiveConfigurationImpl(config); - } else { - this.archiveConfiguration = null; - } + final boolean archiveInfo = config.getEnableRevocationArchiving(); + if (archiveInfo) { + this.archiveConfiguration = new ArchiveConfigurationImpl(config); + } else { + this.archiveConfiguration = null; + } - this.validationConfiguration = new ValidationConfigurationImpl(config); - this.connectionTimeout = config.getConnectionTimeout(); - this.readTimeout = config.getReadTimeout(); - } + this.validationConfiguration = new ValidationConfigurationImpl(config); + this.connectionTimeout = config.getConnectionTimeout(); + this.readTimeout = config.getReadTimeout(); + } - /** - * @see iaik.pki.PKIConfiguration#getCertStoreConfiguration() - */ - public CertStoreConfiguration getCertStoreConfiguration() { - return certStoreConfiguration; - } + /** + * @see iaik.pki.PKIConfiguration#getCertStoreConfiguration() + */ + @Override + public CertStoreConfiguration getCertStoreConfiguration() { + return certStoreConfiguration; + } - /** - * @see iaik.pki.PKIConfiguration#getRevocationConfiguration() - */ - public RevocationConfiguration getRevocationConfiguration() { - return revocationConfiguration; - } + /** + * @see iaik.pki.PKIConfiguration#getRevocationConfiguration() + */ + @Override + public RevocationConfiguration getRevocationConfiguration() { + return revocationConfiguration; + } - /** - * @see iaik.pki.PKIConfiguration#getArchiveConfiguration() - */ - public ArchiveConfiguration getArchiveConfiguration() { - return archiveConfiguration; - } + /** + * @see iaik.pki.PKIConfiguration#getArchiveConfiguration() + */ + @Override + public ArchiveConfiguration getArchiveConfiguration() { + return archiveConfiguration; + } - /** - * @see iaik.pki.PKIConfiguration#getValidationConfiguration() - */ - public ValidationConfiguration getValidationConfiguration() { - return validationConfiguration; - } + /** + * @see iaik.pki.PKIConfiguration#getValidationConfiguration() + */ + @Override + public ValidationConfiguration getValidationConfiguration() { + return validationConfiguration; + } - @Override - public int getConnectTimeout() { - return this.connectionTimeout; - } + @Override + public int getConnectTimeout() { + return this.connectionTimeout; + } - @Override - public int getReadTimeout() { - return this.readTimeout; - } + @Override + public int getReadTimeout() { + return this.readTimeout; + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/RevocationConfigurationImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/RevocationConfigurationImpl.java index 5df84c9..6aa20cf 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/RevocationConfigurationImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/RevocationConfigurationImpl.java @@ -23,9 +23,6 @@ package at.gv.egovernment.moa.spss.server.iaik.config; -import iaik.pki.revocation.RevocationConfiguration; -import iaik.pki.revocation.dbcrl.config.DBCrlConfig; - import java.security.cert.X509Certificate; import java.util.Collections; import java.util.Date; @@ -33,81 +30,85 @@ import java.util.Map; import java.util.Set; import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; +import iaik.pki.revocation.RevocationConfiguration; +import iaik.pki.revocation.dbcrl.config.DBCrlConfig; /** * An implementation of the RevocationConfiguration interface using * MOA configuration data. - * + * * @see iaik.pki.revocation.RevocationConfiguration * @author Patrick Peck * @version $Id$ */ -public class RevocationConfigurationImpl extends AbstractObservableConfiguration implements RevocationConfiguration { - - /** - * The ConfigurationProvider to read the configuration data - * from. - */ - private ConfigurationProvider config; - - /** - * Create a new RevocationConfigurationImpl. - * - * @param config - * The underlying MOA configuration containing the configuration - * data. - */ - public RevocationConfigurationImpl(ConfigurationProvider config) { - this.config = config; - } - - /** - * @see iaik.pki.revocation.RevocationConfiguration#getAlternativeDistributionPoints - */ - public Set getAlternativeDistributionPoints(X509Certificate cert, X509Certificate issuer, Date date) { - return config.getDistributionPoints(cert); - } - - /** - * @see iaik.pki.revocation.RevocationConfiguration#archiveRevocationInfo(java.lang.String, - * java.lang.String) - */ - public boolean archiveRevocationInfo(String type, String uri) { - return config.getEnableRevocationArchiving(); - } - - /** - * @see iaik.pki.revocation.RevocationConfiguration#getCrlRetentionInterval(java.lang.String) - */ - public Integer getCrlRetentionInterval(String issuername) { - Map map = config.getCrlRetentionIntervals(); - Integer interval = (Integer) map.get(issuername); - - return interval; - } - - @Override - public DBCrlConfig getDataBaseCRLConfig() { - // TODO AFITZEK IMPLEMENT THIS METHOD - return null; - } - - @Override - public boolean getKeepRevocationInfo() { - // TODO AFITZEK IMPLEMENT THIS METHOD - return false; - } - - @Override - public Set getPositiveOCSPResponders() { - // TODO AFITZEK IMPLEMENT THIS METHOD - return Collections.EMPTY_SET; - } - - @Override - public boolean skipIndirectCRLCheckForAlternativeDistributionPoints() { - // TODO AFITZEK IMPLEMENT THIS METHOD - return false; - } +public class RevocationConfigurationImpl extends AbstractObservableConfiguration implements + RevocationConfiguration { + + /** + * The ConfigurationProvider to read the configuration data from. + */ + private final ConfigurationProvider config; + + /** + * Create a new RevocationConfigurationImpl. + * + * @param config The underlying MOA configuration containing the configuration + * data. + */ + public RevocationConfigurationImpl(ConfigurationProvider config) { + this.config = config; + } + + /** + * @see iaik.pki.revocation.RevocationConfiguration#getAlternativeDistributionPoints + */ + @Override + public Set getAlternativeDistributionPoints(X509Certificate cert, X509Certificate issuer, Date date) { + return config.getDistributionPoints(cert); + } + + /** + * @see iaik.pki.revocation.RevocationConfiguration#archiveRevocationInfo(java.lang.String, + * java.lang.String) + */ + @Override + public boolean archiveRevocationInfo(String type, String uri) { + return config.getEnableRevocationArchiving(); + } + + /** + * @see iaik.pki.revocation.RevocationConfiguration#getCrlRetentionInterval(java.lang.String) + */ + @Override + public Integer getCrlRetentionInterval(String issuername) { + final Map map = config.getCrlRetentionIntervals(); + final Integer interval = (Integer) map.get(issuername); + + return interval; + } + + @Override + public DBCrlConfig getDataBaseCRLConfig() { + // TODO AFITZEK IMPLEMENT THIS METHOD + return null; + } + + @Override + public boolean getKeepRevocationInfo() { + // TODO AFITZEK IMPLEMENT THIS METHOD + return false; + } + + @Override + public Set getPositiveOCSPResponders() { + // TODO AFITZEK IMPLEMENT THIS METHOD + return Collections.EMPTY_SET; + } + + @Override + public boolean skipIndirectCRLCheckForAlternativeDistributionPoints() { + // TODO AFITZEK IMPLEMENT THIS METHOD + return false; + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/SoftwareKeyModuleConfigurationImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/SoftwareKeyModuleConfigurationImpl.java index 1aed76e..767b3f2 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/SoftwareKeyModuleConfigurationImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/SoftwareKeyModuleConfigurationImpl.java @@ -21,40 +21,39 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.config; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; -import iaik.server.modules.keys.ConfigurationException; -import iaik.server.modules.keys.SoftwareKeyModuleConfiguration; import at.gv.egovernment.moa.spss.server.config.SoftwareKeyModule; import at.gv.egovernment.moa.spss.util.MessageProvider; import at.gv.egovernment.moaspss.logging.LogMsg; import at.gv.egovernment.moaspss.logging.Logger; +import iaik.server.modules.keys.ConfigurationException; +import iaik.server.modules.keys.SoftwareKeyModuleConfiguration; /** * An implementation of the SoftwareKeyModuleConfiguration wrapping * a SoftwareKeyModule from the MOA configuration. - * + * * @see iaik.server.modules.keys.SoftwareKeyModuleConfiguration * @author Patrick Peck * @version $Id$ */ public class SoftwareKeyModuleConfigurationImpl - extends AbstractKeyModuleConfigurationImpl - implements SoftwareKeyModuleConfiguration { + extends AbstractKeyModuleConfigurationImpl + implements SoftwareKeyModuleConfiguration { /** The wrapped SoftwareKeyModule. */ - private SoftwareKeyModule keyModule; + private final SoftwareKeyModule keyModule; /** * Create a new SoftwareKeyModuleConfigurationImpl. - * + * * @param keyModule The SoftwareKeyModule from the underlying MOA - * configuration. + * configuration. */ public SoftwareKeyModuleConfigurationImpl(SoftwareKeyModule keyModule) { super(keyModule.getId()); @@ -64,6 +63,7 @@ public class SoftwareKeyModuleConfigurationImpl /** * @see iaik.server.modules.keys.SoftwareKeyModuleConfiguration#getKeyStoreTypeName() */ + @Override public String getKeyStoreTypeName() { return KEY_STORE_TYPE_NAME_PKCS12; } @@ -71,17 +71,18 @@ public class SoftwareKeyModuleConfigurationImpl /** * @see iaik.server.modules.keys.SoftwareKeyModuleConfiguration#getKeyStoreAsStream() */ + @Override public InputStream getKeyStoreAsStream() { - MessageProvider msg = MessageProvider.getInstance(); + final MessageProvider msg = MessageProvider.getInstance(); try { - String message = - msg.getMessage("config.18", new Object[] { keyModule.getFileName()}); + final String message = + msg.getMessage("config.18", new Object[] { keyModule.getFileName() }); Logger.info(new LogMsg(message)); return new FileInputStream(keyModule.getFileName()); - } catch (FileNotFoundException e) { - String message = - msg.getMessage("config.09", new Object[] { keyModule.getFileName()}); + } catch (final FileNotFoundException e) { + final String message = + msg.getMessage("config.09", new Object[] { keyModule.getFileName() }); throw new ConfigurationException(message, e, null); } @@ -90,6 +91,7 @@ public class SoftwareKeyModuleConfigurationImpl /** * @see iaik.server.modules.keys.SoftwareKeyModuleConfiguration#getKeyStoreAuthenticationData() */ + @Override public char[] getKeyStoreAuthenticationData() { return keyModule.getPassWord().toCharArray(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/ValidationConfigurationImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/ValidationConfigurationImpl.java index 9e26fb8..50c3926 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/ValidationConfigurationImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/config/ValidationConfigurationImpl.java @@ -21,35 +21,34 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.config; import java.security.cert.X509Certificate; import java.security.spec.AlgorithmParameterSpec; -import iaik.pki.pathvalidation.ValidationConfiguration; - import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; +import iaik.pki.pathvalidation.ValidationConfiguration; /** * An implementation of the ValidationConfiguration interface using * MOA configuration data. - * + * * @see iaik.pki.pathvalidation.ValidationConfiguration * @author Patrick Peck * @version $Id$ */ public class ValidationConfigurationImpl - extends AbstractObservableConfiguration - implements ValidationConfiguration { + extends AbstractObservableConfiguration + implements ValidationConfiguration { - /** The ConfigurationProvider to read the configuration data - * from. */ - private ConfigurationProvider config; + /** + * The ConfigurationProvider to read the configuration data from. + */ + private final ConfigurationProvider config; /** * Create a new ValidationConfigurationImpl. - * + * * @param config The underlying MOA configuration data. */ public ValidationConfigurationImpl(ConfigurationProvider config) { @@ -59,6 +58,7 @@ public class ValidationConfigurationImpl /** * @see iaik.pki.pathvalidation.ValidationConfiguration#getChainingMode(java.security.cert.X509Certificate) */ + @Override public String getChainingMode(X509Certificate cert) { return config.getChainingMode(cert); } @@ -66,6 +66,7 @@ public class ValidationConfigurationImpl /** * @see iaik.pki.pathvalidation.ValidationConfiguration#getPublicKeyParamsAsSpec(java.security.cert.X509Certificate) */ + @Override public AlgorithmParameterSpec getPublicKeyParamsAsSpec(X509Certificate cert) { return null; } @@ -73,6 +74,7 @@ public class ValidationConfigurationImpl /** * @see iaik.pki.pathvalidation.ValidationConfiguration#getPublicKeyParamsAsCert(java.security.cert.X509Certificate) */ + @Override public X509Certificate getPublicKeyParamsAsCert(X509Certificate cert) { return null; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/pki/PKIProfileImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/pki/PKIProfileImpl.java index 97eb6ef..0032dc6 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/pki/PKIProfileImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/pki/PKIProfileImpl.java @@ -23,15 +23,8 @@ package at.gv.egovernment.moa.spss.server.iaik.pki; -import iaik.pki.PKIProfile; -import iaik.pki.pathvalidation.ValidationProfile; -import iaik.pki.revocation.RevocationProfile; -import iaik.pki.store.truststore.TrustStoreProfile; -import iaik.pki.store.truststore.TrustStoreTypes; - import java.util.Arrays; -import at.gv.egovernment.moa.sig.tsl.api.ITslService; import at.gv.egovernment.moa.sig.tsl.exception.TslPKIException; import at.gv.egovernment.moa.sig.tsl.pki.TslTrustStoreProfile; import at.gv.egovernment.moa.sig.tsl.pki.chaining.ChainingTrustStoreProfile; @@ -43,189 +36,195 @@ import at.gv.egovernment.moa.spss.server.iaik.pki.revocation.RevocationProfileIm import at.gv.egovernment.moa.spss.server.iaik.pki.store.truststore.TrustStoreProfileImpl; import at.gv.egovernment.moa.spss.tsl.TSLServiceFactory; import at.gv.egovernment.moaspss.logging.Logger; +import iaik.pki.PKIProfile; +import iaik.pki.pathvalidation.ValidationProfile; +import iaik.pki.revocation.RevocationProfile; +import iaik.pki.store.truststore.TrustStoreProfile; /** * Implementation of the PKIProfile interface containing * information needed for certificate path validation. It uses configuration * data from the MOA configuration. - * + * * @author Patrick Peck * @version $Id$ */ public class PKIProfileImpl implements PKIProfile { - /** Profile information for revocation checking. */ - private RevocationProfile revocationProfile; - /** Profile information about the trust profile to use. */ - private TrustStoreProfile trustStoreProfile; - /** Profile information about the certificate validation. */ - private ValidationProfile validationProfile; - /** - * The ConfigurationProvider to read the MOA configuration data - * from. - */ - private ConfigurationProvider config; - - /** - * Create a new PKIProfileImpl. - * - * @param config - * The MOA configuration providing configuration data about - * certificate path validation. - * @param trustProfileID - * The trust profile ID denoting the location of the trust store. - * @throws MOAApplicationException - * An error occurred building the profile. - */ - public PKIProfileImpl(ConfigurationProvider config, String trustProfileID) throws MOAApplicationException { - - this.config = config; - setRevocationProfile(new RevocationProfileImpl(config)); - setValidationProfile(new ValidationProfileImpl(config)); - - //generate TrustStoreProfile from TrustStore configuration - internalTrustProfileBuilder(trustProfileID); - - } - - - private void internalTrustProfileBuilder(String trustProfileId) throws MOAApplicationException { - TrustProfile tp = (TrustProfile) config.getTrustProfile(trustProfileId); - if (tp != null) { - //build directory based trust store as default - - - if (tp.isTSLEnabled()) { - TslTrustStoreProfile tslTrustStore; - try { - if (!TSLServiceFactory.isInitialized()) { - Logger.error("Can not build TrustProfile:" + trustProfileId - + " Reason: TrustProfile needs TSL support but TSL client NOT initialized."); - throw new TslPKIException("Trust Status-List service client is NOT initialized"); - - } - - //build TSL truststore if enabled - tslTrustStore = TSLServiceFactory.getTSLServiceClient(). - buildTrustStoreProfile( - tp.getCountries(), - tp.getAllowedTspStatus(), - tp.getAllowedTspServiceTypes(), - trustProfileId + "_TSL"); - - //build Directory based TrustStore - TrustStoreProfileImpl directoryTrustStore = new TrustStoreProfileImpl(trustProfileId + "_Directory", tp.getUri()); - - //generate a virtual truststore that concatenates the TSL TrustStore and the directory TrustStore - ChainingTrustStoreProfile chainedProfile = new ChainingTrustStoreProfile( - Arrays.asList(tslTrustStore, directoryTrustStore), - trustProfileId); - - //set this virtual truststore - setTrustStoreProfile(chainedProfile); - - } catch (TslPKIException e) { - Logger.error("Virtual TSL based TrustProfile generation FAILED.", e); - throw new MOAApplicationException("2900", new Object[] { trustProfileId }); - - } - - } else - setTrustStoreProfile(new TrustStoreProfileImpl(trustProfileId, tp.getUri())); - - } else { - throw new MOAApplicationException("2203", new Object[] { trustProfileId }); - - } - - } - - /** - * @see iaik.pki.PKIProfile#autoAddCertificates() - */ - /*public boolean autoAddCertificates() { - return useAuthorityInfoAccess() ? true : config.getAutoAddCertificates(); - }*/ - - /** - * @see iaik.pki.PKIProfile#getRevocationProfile() - */ - public RevocationProfile getRevocationProfile() { - return revocationProfile; - } - - /** - * Sets the RevocationProfile. - * - * @param revocationProfile - * The RevocationProfile used for revocation - * checking. - */ - protected void setRevocationProfile(RevocationProfile revocationProfile) { - this.revocationProfile = revocationProfile; - } - - /** - * @see iaik.pki.PKIProfile#getTrustStoreProfile() - */ - public TrustStoreProfile getTrustStoreProfile() { - return trustStoreProfile; - } - - /** - * Sets the TrustStoreProfile. - * - * @param trustStoreProfile - * The TrustStoreProfile. - */ - protected void setTrustStoreProfile(TrustStoreProfile trustStoreProfile) { - this.trustStoreProfile = trustStoreProfile; - } - - /** - * @see iaik.pki.PKIProfile#getValidationProfile() - */ - public ValidationProfile getValidationProfile() { - return validationProfile; - } - - /** - * Sets the ValidationProfile. - * - * @param validationProfile - * The ValidationProfile to set. - */ - protected void setValidationProfile(ValidationProfile validationProfile) { - this.validationProfile = validationProfile; - } - - /** - * @see iaik.pki.PKIProfile#useAuthorityInfoAccess() - */ - public boolean useAuthorityInfoAccess() { - return config.getUseAuthorityInfoAccess(); - } - - /** - * @see iaik.pki.PKIProfile#autoAddCertificates() - */ - @Override - public int autoAddCertificates() { - if(config.getAutoAddCertificates()) { - if (config.getAutoAddEECertificates()) - return PKIProfile.AUTO_ADD_ENABLE; - else - return PKIProfile.AUTO_ADD_EE_DISABLE; - - } else - return PKIProfile.AUTO_ADD_DISABLE; - - } - - @Override - public TrustStoreProfile getIndirectRevocationTrustStoreProfile() { - // TODO AFITZEK IMPLEMENT THIS METHOD - return null; - } + /** Profile information for revocation checking. */ + private RevocationProfile revocationProfile; + /** Profile information about the trust profile to use. */ + private TrustStoreProfile trustStoreProfile; + /** Profile information about the certificate validation. */ + private ValidationProfile validationProfile; + /** + * The ConfigurationProvider to read the MOA configuration data + * from. + */ + private final ConfigurationProvider config; + + /** + * Create a new PKIProfileImpl. + * + * @param config The MOA configuration providing configuration data + * about certificate path validation. + * @param trustProfileID The trust profile ID denoting the location of the trust + * store. + * @throws MOAApplicationException An error occurred building the profile. + */ + public PKIProfileImpl(ConfigurationProvider config, String trustProfileID) throws MOAApplicationException { + + this.config = config; + setRevocationProfile(new RevocationProfileImpl(config)); + setValidationProfile(new ValidationProfileImpl(config)); + + // generate TrustStoreProfile from TrustStore configuration + internalTrustProfileBuilder(trustProfileID); + + } + + private void internalTrustProfileBuilder(String trustProfileId) throws MOAApplicationException { + final TrustProfile tp = config.getTrustProfile(trustProfileId); + if (tp != null) { + // build directory based trust store as default + + if (tp.isTSLEnabled()) { + TslTrustStoreProfile tslTrustStore; + try { + if (!TSLServiceFactory.isInitialized()) { + Logger.error("Can not build TrustProfile:" + trustProfileId + + " Reason: TrustProfile needs TSL support but TSL client NOT initialized."); + throw new TslPKIException("Trust Status-List service client is NOT initialized"); + + } + + // build TSL truststore if enabled + tslTrustStore = TSLServiceFactory.getTSLServiceClient().buildTrustStoreProfile( + tp.getCountries(), + tp.getAllowedTspStatus(), + tp.getAllowedTspServiceTypes(), + trustProfileId + "_TSL"); + + // build Directory based TrustStore + final TrustStoreProfileImpl directoryTrustStore = new TrustStoreProfileImpl(trustProfileId + + "_Directory", tp.getUri()); + + // generate a virtual truststore that concatenates the TSL TrustStore and the + // directory TrustStore + final ChainingTrustStoreProfile chainedProfile = new ChainingTrustStoreProfile( + Arrays.asList(tslTrustStore, directoryTrustStore), + trustProfileId); + + // set this virtual truststore + setTrustStoreProfile(chainedProfile); + + } catch (final TslPKIException e) { + Logger.error("Virtual TSL based TrustProfile generation FAILED.", e); + throw new MOAApplicationException("2900", new Object[] { trustProfileId }); + + } + + } else { + setTrustStoreProfile(new TrustStoreProfileImpl(trustProfileId, tp.getUri())); + } + + } else { + throw new MOAApplicationException("2203", new Object[] { trustProfileId }); + + } + + } + + /** + * @see iaik.pki.PKIProfile#autoAddCertificates() + */ + /* + * public boolean autoAddCertificates() { return useAuthorityInfoAccess() ? true + * : config.getAutoAddCertificates(); } + */ + + /** + * @see iaik.pki.PKIProfile#getRevocationProfile() + */ + @Override + public RevocationProfile getRevocationProfile() { + return revocationProfile; + } + + /** + * Sets the RevocationProfile. + * + * @param revocationProfile The RevocationProfile used for + * revocation checking. + */ + protected void setRevocationProfile(RevocationProfile revocationProfile) { + this.revocationProfile = revocationProfile; + } + + /** + * @see iaik.pki.PKIProfile#getTrustStoreProfile() + */ + @Override + public TrustStoreProfile getTrustStoreProfile() { + return trustStoreProfile; + } + + /** + * Sets the TrustStoreProfile. + * + * @param trustStoreProfile The TrustStoreProfile. + */ + protected void setTrustStoreProfile(TrustStoreProfile trustStoreProfile) { + this.trustStoreProfile = trustStoreProfile; + } + + /** + * @see iaik.pki.PKIProfile#getValidationProfile() + */ + @Override + public ValidationProfile getValidationProfile() { + return validationProfile; + } + + /** + * Sets the ValidationProfile. + * + * @param validationProfile The ValidationProfile to set. + */ + protected void setValidationProfile(ValidationProfile validationProfile) { + this.validationProfile = validationProfile; + } + + /** + * @see iaik.pki.PKIProfile#useAuthorityInfoAccess() + */ + @Override + public boolean useAuthorityInfoAccess() { + return config.getUseAuthorityInfoAccess(); + } + + /** + * @see iaik.pki.PKIProfile#autoAddCertificates() + */ + @Override + public int autoAddCertificates() { + if (config.getAutoAddCertificates()) { + if (config.getAutoAddEECertificates()) { + return PKIProfile.AUTO_ADD_ENABLE; + } else { + return PKIProfile.AUTO_ADD_EE_DISABLE; + } + + } else { + return PKIProfile.AUTO_ADD_DISABLE; + } + + } + + @Override + public TrustStoreProfile getIndirectRevocationTrustStoreProfile() { + // TODO AFITZEK IMPLEMENT THIS METHOD + return null; + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/pki/pathvalidation/ValidationProfileImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/pki/pathvalidation/ValidationProfileImpl.java index 7e62d60..76e1ed0 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/pki/pathvalidation/ValidationProfileImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/pki/pathvalidation/ValidationProfileImpl.java @@ -21,40 +21,39 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.pki.pathvalidation; -import iaik.pki.pathvalidation.ValidationProfile; - import java.util.Collections; import java.util.Set; import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; +import iaik.pki.pathvalidation.ValidationProfile; /** * An implementation of the ValidationProfile interface providing - * information about certificat path validation. - * + * information about certificat path validation. + * * @author Patrick Peck * @version $Id$ */ public class ValidationProfileImpl implements ValidationProfile { - /** The ConfigurationProvider to read the configuration data - * from. */ - private ConfigurationProvider config; - private boolean initialAnyPolicyInhibit; - private boolean initialExplicitPolicy; - private boolean initialPolicyMappingInhibit; - private Set initialPolicySet; - private boolean nameConstraintsProcessing; - private boolean policyProcessing; + /** + * The ConfigurationProvider to read the configuration data from. + */ + private final ConfigurationProvider config; + private final boolean initialAnyPolicyInhibit; + private final boolean initialExplicitPolicy; + private final boolean initialPolicyMappingInhibit; + private final Set initialPolicySet; + private final boolean nameConstraintsProcessing; + private final boolean policyProcessing; /** * Create a new ValidationProfileImpl object. - * + * * This objects's fields are preset to the following values: - * + * *
    *
  • initialAnyPolicyInhibit = true
  • *
  • initialExplicitPoliy = true
  • @@ -64,9 +63,9 @@ public class ValidationProfileImpl implements ValidationProfile { *
  • nameConstraintsProcessing = false
  • *
  • revocationChecking = false
  • *
- * - * @param config MOA configuration data for additional configuration - * information (currently unused). + * + * @param config MOA configuration data for additional configuration information + * (currently unused). */ public ValidationProfileImpl(ConfigurationProvider config) { this.config = config; @@ -81,6 +80,7 @@ public class ValidationProfileImpl implements ValidationProfile { /** * @see iaik.pki.pathvalidation.ValidationProfile#getInitialAnyPolicyInhibit() */ + @Override public boolean getInitialAnyPolicyInhibit() { return initialAnyPolicyInhibit; } @@ -88,6 +88,7 @@ public class ValidationProfileImpl implements ValidationProfile { /** * @see iaik.pki.pathvalidation.ValidationProfile#getInitialExplicitPolicy() */ + @Override public boolean getInitialExplicitPolicy() { return initialExplicitPolicy; } @@ -95,6 +96,7 @@ public class ValidationProfileImpl implements ValidationProfile { /** * @see iaik.pki.pathvalidation.ValidationProfile#getInitialPolicyMappingInhibit() */ + @Override public boolean getInitialPolicyMappingInhibit() { return initialPolicyMappingInhibit; } @@ -102,6 +104,7 @@ public class ValidationProfileImpl implements ValidationProfile { /** * @see iaik.pki.pathvalidation.ValidationProfile#getInitialPolicySet() */ + @Override public Set getInitialPolicySet() { return initialPolicySet; } @@ -109,6 +112,7 @@ public class ValidationProfileImpl implements ValidationProfile { /** * @see iaik.pki.pathvalidation.ValidationProfile#getPolicyProcessing() */ + @Override public boolean getPolicyProcessing() { return policyProcessing; } @@ -116,6 +120,7 @@ public class ValidationProfileImpl implements ValidationProfile { /** * @see iaik.pki.pathvalidation.ValidationProfile#getNameConstraintsProcessing() */ + @Override public boolean getNameConstraintsProcessing() { return nameConstraintsProcessing; } @@ -123,8 +128,8 @@ public class ValidationProfileImpl implements ValidationProfile { /** * @see iaik.pki.pathvalidation.ValidationProfile#getRevocationChecking() */ - public boolean getRevocationChecking() - { + @Override + public boolean getRevocationChecking() { return config.getEnableRevocationChecking(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/pki/revocation/RevocationProfileImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/pki/revocation/RevocationProfileImpl.java index 14627b2..5215131 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/pki/revocation/RevocationProfileImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/pki/revocation/RevocationProfileImpl.java @@ -21,37 +21,37 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.pki.revocation; import java.security.cert.X509Certificate; +import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; import iaik.pki.revocation.RevocationProfile; import iaik.pki.revocation.RevocationSourceTypes; -import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; - /** * An implementation of the RevocationProfile interface providing * information about revocation status checking, based on MOA configuration * data. - * + * * @author Patrick Peck * @version $Id$ */ public class RevocationProfileImpl implements RevocationProfile { /** The default service order. */ private static final String[] DEFAULT_SERVICE_ORDER = - { RevocationSourceTypes.CRL, RevocationSourceTypes.OCSP }; - /** The ConfigurationProvider to read the MOA configuration data - * from. */ - private ConfigurationProvider config; + { RevocationSourceTypes.CRL, RevocationSourceTypes.OCSP }; + /** + * The ConfigurationProvider to read the MOA configuration data + * from. + */ + private final ConfigurationProvider config; /** The OCSP request hash algorithm. Currently only "SHA" is supported. */ private static final String oCSPRequestHashAlgorithm = "SHA"; /** * Create a new RevocationProfileImpl. - * + * * @param config The MOA configuration data. */ public RevocationProfileImpl(ConfigurationProvider config) { @@ -63,14 +63,15 @@ public class RevocationProfileImpl implements RevocationProfile { /** * @see iaik.pki.revocation.RevocationProfile#getMaxRevocationAge(String) */ - public long getMaxRevocationAge(String distributionPointUri) - { + @Override + public long getMaxRevocationAge(String distributionPointUri) { return config.getMaxRevocationAge(); } /** * @see iaik.pki.revocation.RevocationProfile#getOCSPRequestHashAlgorithm() */ + @Override public String getOCSPRequestHashAlgorithm() { return oCSPRequestHashAlgorithm; } @@ -78,10 +79,12 @@ public class RevocationProfileImpl implements RevocationProfile { /** * @see iaik.pki.revocation.RevocationProfile#getPreferredServiceOrder(java.security.cert.X509Certificate) */ - public String[] getPreferredServiceOrder(X509Certificate cert) - { - String[] serviceOrder = config.getServiceOrder(); - if (serviceOrder == null || serviceOrder.length == 0) return DEFAULT_SERVICE_ORDER; + @Override + public String[] getPreferredServiceOrder(X509Certificate cert) { + final String[] serviceOrder = config.getServiceOrder(); + if (serviceOrder == null || serviceOrder.length == 0) { + return DEFAULT_SERVICE_ORDER; + } return serviceOrder; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/pki/store/truststore/TrustStoreProfileImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/pki/store/truststore/TrustStoreProfileImpl.java index c9f4f28..9ef3764 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/pki/store/truststore/TrustStoreProfileImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/pki/store/truststore/TrustStoreProfileImpl.java @@ -21,89 +21,82 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.pki.store.truststore; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; -import iaik.pki.store.truststore.TrustStoreProfile; -import iaik.pki.store.truststore.TrustStoreTypes; -import iaik.pki.store.observer.NotificationData; -import iaik.pki.store.observer.Observer; - import at.gv.egovernment.moa.spss.MOAApplicationException; import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; import at.gv.egovernment.moa.spss.server.config.TrustProfile; +import iaik.pki.store.observer.NotificationData; +import iaik.pki.store.observer.Observer; +import iaik.pki.store.truststore.TrustStoreProfile; +import iaik.pki.store.truststore.TrustStoreTypes; /** * An implementation of the TrustStoreProfile interface, using data * from the MOA configuration. - * - * @see iaik.pki.store.truststore.TrustStoreProfile + * + * @see iaik.pki.store.truststore.TrustStoreProfile * @author Patrick Peck * @version $Id$ */ public class TrustStoreProfileImpl implements TrustStoreProfile { /** The observers of this profile. */ - private List observers = new ArrayList(); - + private final List observers = new ArrayList(); + /** - * The trust profile identifier. + * The trust profile identifier. */ private String id_; - + /** The type of the trust profile. */ private String type; - /** The URI of the trust profile.*/ + /** The URI of the trust profile. */ private String URI; - /** * Create a new TrustStoreProfileImpl. - * - * @param config The MOA configuration data, from which trust store - * configuration data is read. + * + * @param config The MOA configuration data, from which trust store + * configuration data is read. * @param trustProfileId The trust profile id on which this - * TrustStoreProfile is based. - * @throws MOAApplicationException The trustProfileId could not - * be found in the MOA configuration. + * TrustStoreProfile is based. + * @throws MOAApplicationException The trustProfileId could not be + * found in the MOA configuration. */ public TrustStoreProfileImpl(String trustProfileId, String trustProfileUri) - throws MOAApplicationException { - id_ = trustProfileId; - setURI(trustProfileUri); - setType(TrustStoreTypes.DIRECTORY); - + throws MOAApplicationException { + id_ = trustProfileId; + setURI(trustProfileUri); + setType(TrustStoreTypes.DIRECTORY); + } - + /** * Create a new TrustStoreProfileImpl. - * - * @param config The MOA configuration data, from which trust store - * configuration data is read. + * + * @param config The MOA configuration data, from which trust store + * configuration data is read. * @param trustProfileId The trust profile id on which this - * TrustStoreProfile is based. - * @throws MOAApplicationException The trustProfileId could not - * be found in the MOA configuration. + * TrustStoreProfile is based. + * @throws MOAApplicationException The trustProfileId could not be + * found in the MOA configuration. */ @Deprecated public TrustStoreProfileImpl( - ConfigurationProvider config, - String trustProfileId) - throws MOAApplicationException { + ConfigurationProvider config, + String trustProfileId) + throws MOAApplicationException { - TrustProfile tp = (TrustProfile) config.getTrustProfile(trustProfileId); - if (tp != null) - { + final TrustProfile tp = config.getTrustProfile(trustProfileId); + if (tp != null) { id_ = trustProfileId; setURI(tp.getUri()); setType(TrustStoreTypes.DIRECTORY); - } - else - { + } else { throw new MOAApplicationException("2203", new Object[] { trustProfileId }); } } @@ -111,14 +104,15 @@ public class TrustStoreProfileImpl implements TrustStoreProfile { /** * @see iaik.pki.store.truststore.TrustStoreProfile#getType() */ + @Override public String getType() { return type; } /** * Sets the the trust store type. - * - * @param type The trust store type to set. + * + * @param type The trust store type to set. */ protected void setType(String type) { this.type = type; @@ -127,13 +121,14 @@ public class TrustStoreProfileImpl implements TrustStoreProfile { /** * @see iaik.pki.store.truststore.TrustStoreProfile#getURI() */ + @Override public String getURI() { return URI; } /** * Sets the trust store URI. - * + * * @param URI The trust store URI to set. */ protected void setURI(String URI) { @@ -162,8 +157,8 @@ public class TrustStoreProfileImpl implements TrustStoreProfile { * @see iaik.pki.store.observer.Observable#notify(iaik.pki.store.observer.NotificationData) */ public void notify(NotificationData notificationData) { - for (Iterator iter = observers.iterator(); iter.hasNext();) { - Observer observer = (Observer) iter.next(); + for (final Object observer2 : observers) { + final Observer observer = (Observer) observer2; observer.notify(notificationData); } } @@ -171,8 +166,8 @@ public class TrustStoreProfileImpl implements TrustStoreProfile { /** * @see iaik.pki.store.truststore.TrustStoreProfile#getId() */ - public String getId() - { + @Override + public String getId() { return id_; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/Base64TransformationImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/Base64TransformationImpl.java index cc12861..1bba712 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/Base64TransformationImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/Base64TransformationImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.xml; import iaik.server.modules.xml.Base64Transformation; @@ -29,39 +28,39 @@ import iaik.server.modules.xml.Base64Transformation; /** * An implementation of the Base64Transformation * Transformation type. - * + * * @author Patrick Peck * @version $Id$ */ public class Base64TransformationImpl - extends TransformationImpl - implements Base64Transformation { - + extends TransformationImpl + implements Base64Transformation { + /** * Create a new Base64TransformationImpl. - * + * * @see java.lang.Object#Object() - */ + */ public Base64TransformationImpl() { setAlgorithmURI(Base64Transformation.BASE64_DECODING); } /** * Compare this Base64Transformation to another. - * - * @param other The object to compare thisBase64Transformation - * to. + * + * @param other The object to compare thisBase64Transformation to. * @return true, if other is a - * Base64Transformation and the algorithm URIs match, otherwise - * false. + * Base64Transformation and the algorithm URIs match, + * otherwise false. * @see java.lang.Object#equals(Object) - */ + */ + @Override public boolean equals(Object other) { if (other instanceof Base64Transformation) { - Base64Transformation transform = (Base64Transformation) other; + final Base64Transformation transform = (Base64Transformation) other; return getAlgorithmURI().equals(transform.getAlgorithmURI()); } return false; } - + } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/ByteArrayDataObjectImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/ByteArrayDataObjectImpl.java index 4d627d7..e498842 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/ByteArrayDataObjectImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/ByteArrayDataObjectImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.xml; import java.io.ByteArrayInputStream; @@ -31,22 +30,21 @@ import iaik.server.modules.xml.BinaryDataObject; /** * A BinaryDataObject encapsulating Base64 data. - * + * * @author Patrick Peck * @version $Id$ */ public class ByteArrayDataObjectImpl - extends DataObjectImpl - implements BinaryDataObject { + extends DataObjectImpl + implements BinaryDataObject { /** The binary data contained in this BinaryDataObject. */ private byte[] bytes; /** * Create a new ByteArrayDataObjectImpl. - * - * @param bytes The binary data contained in this - * BinaryDataObject. + * + * @param bytes The binary data contained in this BinaryDataObject. */ public ByteArrayDataObjectImpl(byte[] bytes) { setBytes(bytes); @@ -54,23 +52,22 @@ public class ByteArrayDataObjectImpl /** * Set the Base64 data. - * - * @param bytes The binary data contained in this - * BinaryDataObject. + * + * @param bytes The binary data contained in this BinaryDataObject. */ public void setBytes(byte[] bytes) { this.bytes = bytes; } /** - * Return the binary data encoded in the Base64 String as a - * stream. - * + * Return the binary data encoded in the Base64 String as a stream. + * * @return The binary data contained in this object, as a - * InputStream. Repeated calls to this function will return a - * new stream to the Base64 data. + * InputStream. Repeated calls to this function will return + * a new stream to the Base64 data. * @see iaik.server.modules.xml.BinaryDataObject#getInputStream() */ + @Override public InputStream getInputStream() { return new ByteArrayInputStream(bytes); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/ByteStreamDataObjectImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/ByteStreamDataObjectImpl.java index b982c8e..af8ee66 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/ByteStreamDataObjectImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/ByteStreamDataObjectImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.xml; import java.io.InputStream; @@ -29,21 +28,21 @@ import java.io.InputStream; import iaik.server.modules.xml.BinaryDataObject; /** - * A BinaryDataObject encapsulating binary data from a stream. - * + * A BinaryDataObject encapsulating binary data from a stream. + * * @author Patrick Peck * @version $Id$ */ public class ByteStreamDataObjectImpl - extends DataObjectImpl - implements BinaryDataObject { + extends DataObjectImpl + implements BinaryDataObject { /** The InputStream containing the binary data. */ private InputStream inputStream; /** * Create a new ByteStreamDataObjectImpl. - * + * * @param inputStream The stream from which to read the binary data. */ public ByteStreamDataObjectImpl(InputStream inputStream) { @@ -52,7 +51,7 @@ public class ByteStreamDataObjectImpl /** * Set the input stream from which to read the binary data. - * + * * @param inputStream The input stream from which to read the binary data. */ public void setInputStream(InputStream inputStream) { @@ -61,11 +60,12 @@ public class ByteStreamDataObjectImpl /** * Return the binary data from this object as a stream. - * + * * @return The stream containing the binary data. Calling this function - * repeatedly will always return the same InputStream. + * repeatedly will always return the same InputStream. * @see iaik.server.modules.xml.BinaryDataObject#getInputStream() */ + @Override public InputStream getInputStream() { return inputStream; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/CanonicalizationImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/CanonicalizationImpl.java index 0c3a8da..1e2a651 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/CanonicalizationImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/CanonicalizationImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.xml; import iaik.server.modules.xml.Canonicalization; @@ -29,36 +28,36 @@ import iaik.server.modules.xml.Canonicalization; /** * An implementation of the CanonicalizationTransform * Transformation type. - * + * * @author Patrick Peck * @version $Id$ */ public class CanonicalizationImpl - extends TransformationImpl - implements Canonicalization { - + extends TransformationImpl + implements Canonicalization { + /** * Create a new CanonicalizationTransformImpl object. - * + * * @param algorithmURI The canonicalization algorithm URI. - */ + */ public CanonicalizationImpl(String algorithmURI) { setAlgorithmURI(algorithmURI); } - + /** * Compare this object to another Canonicalization. - * - * @param other The object to compare this - * Canonicalization to. + * + * @param other The object to compare this Canonicalization to. * @return true, if other is a - * Canonicalization and the algorithm URIs match, otherwise - * false. + * Canonicalization and the algorithm URIs match, otherwise + * false. * @see java.lang.Object#equals(Object) */ + @Override public boolean equals(Object other) { if (other instanceof Canonicalization) { - Canonicalization c14n = (Canonicalization) other; + final Canonicalization c14n = (Canonicalization) other; return getAlgorithmURI().equals(c14n.getAlgorithmURI()); } return false; diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/DataObjectImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/DataObjectImpl.java index 702caaf..ac36875 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/DataObjectImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/DataObjectImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.xml; import iaik.server.modules.xml.DataObject; @@ -29,12 +28,12 @@ import iaik.server.modules.xml.DataObject; /** * Abstract base implementation for the classes derived from * DataObject. - * + * * @author Patrick Peck * @version $Id$ */ public abstract class DataObjectImpl implements DataObject { - + /** The MIME type of the data object. */ private String mimeType; /** The refernce ID. */ @@ -43,33 +42,35 @@ public abstract class DataObjectImpl implements DataObject { private String typeURI; /** The URI identifying the data. */ private String URI; - + /** * @see iaik.server.modules.xml.DataObject#getMimeType() */ + @Override public String getMimeType() { return mimeType; } /** * Set the mime type. - * + * * @param mimeType The mime type to set. */ public void setMimeType(String mimeType) { this.mimeType = mimeType; } - + /** * @see iaik.server.modules.xml.DataObject#getReferenceID() */ + @Override public String getReferenceID() { return referenceID; } - + /** * Set the reference ID. - * + * * @param referenceID The reference ID. */ public void setReferenceID(String referenceID) { @@ -79,13 +80,14 @@ public abstract class DataObjectImpl implements DataObject { /** * @see iaik.server.modules.xml.DataObject#getTypeURI() */ + @Override public String getTypeURI() { return typeURI; } /** * Set the type URI. - * + * * @param typeURI The type URI. */ public void setTypeURI(String typeURI) { @@ -95,13 +97,14 @@ public abstract class DataObjectImpl implements DataObject { /** * @see iaik.server.modules.xml.DataObject#getURI() */ + @Override public String getURI() { return URI; } - + /** * Set the URI. - * + * * @param URI The URI. */ public void setURI(String URI) { diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/EnvelopedSignatureTransformationImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/EnvelopedSignatureTransformationImpl.java index d582594..2c9f0e3 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/EnvelopedSignatureTransformationImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/EnvelopedSignatureTransformationImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.xml; import iaik.server.modules.xml.EnvelopedSignatureTransformation; @@ -29,13 +28,13 @@ import iaik.server.modules.xml.EnvelopedSignatureTransformation; /** * An implementation of the EnvelopedSignatureTransformation * Transformation type. - * + * * @author Patrick Peck * @version $Id$ */ public class EnvelopedSignatureTransformationImpl - extends TransformationImpl - implements EnvelopedSignatureTransformation { + extends TransformationImpl + implements EnvelopedSignatureTransformation { /** * Create a new EnvelopedSignatureTransformationImpl. @@ -46,18 +45,19 @@ public class EnvelopedSignatureTransformationImpl /** * Compare this object to another EnvelopedSignatureTransformation. - * - * @param other The object to compare this - * EnvelopedSignatureTransformation to. + * + * @param other The object to compare this + * EnvelopedSignatureTransformation to. * @return true, if other is a - * EnvelopedSignatureTransformation, otherwise - * false. + * EnvelopedSignatureTransformation, otherwise + * false. * @see java.lang.Object#equals(Object) */ + @Override public boolean equals(Object other) { if (other instanceof EnvelopedSignatureTransformation) { - EnvelopedSignatureTransformation transform = - (EnvelopedSignatureTransformation) other; + final EnvelopedSignatureTransformation transform = + (EnvelopedSignatureTransformation) other; return getAlgorithmURI().equals(transform.getAlgorithmURI()); } return false; diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/ExclusiveCanonicalizationImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/ExclusiveCanonicalizationImpl.java index dfadf0c..ce98e7f 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/ExclusiveCanonicalizationImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/ExclusiveCanonicalizationImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.xml; import java.util.List; @@ -29,38 +28,39 @@ import java.util.List; import iaik.server.modules.xml.ExclusiveCanonicalization; /** - * An implementation of the ExclusiveCanonicalization type - * of Transformation. - * + * An implementation of the ExclusiveCanonicalization type of + * Transformation. + * * @author Patrick Peck * @version $Id$ */ public class ExclusiveCanonicalizationImpl - extends TransformationImpl - implements ExclusiveCanonicalization { + extends TransformationImpl + implements ExclusiveCanonicalization { /** The prefixes of the namespaces to treat according to canonical XML. */ private List inclusiveNamespacePrefixes; /** * Create a new ExclusiveCanonicalizationImpl object. - * - * @param algorithmURI The exclusive canonicalization algorithm URI. + * + * @param algorithmURI The exclusive canonicalization algorithm + * URI. * @param inclusiveNamespacePrefixes The namespace prefixes to be processed - * according to canonical XML. + * according to canonical XML. */ public ExclusiveCanonicalizationImpl( - String algorithmURI, - List inclusiveNamespacePrefixes) { + String algorithmURI, + List inclusiveNamespacePrefixes) { setAlgorithmURI(algorithmURI); setInclusiveNamespacePrefixes(inclusiveNamespacePrefixes); } /** * Sets the namespace prefixes to be processed according to canonical XML. - * + * * @param inclusiveNamespacePrefixes The prefixes of the namespaces to treat - * according to canonical XML. + * according to canonical XML. */ protected void setInclusiveNamespacePrefixes(List inclusiveNamespacePrefixes) { this.inclusiveNamespacePrefixes = inclusiveNamespacePrefixes; @@ -69,29 +69,32 @@ public class ExclusiveCanonicalizationImpl /** * @see iaik.server.modules.xml.ExclusiveCanonicalization#getInclusiveNamespacePrefixes() */ + @Override public List getInclusiveNamespacePrefixes() { return inclusiveNamespacePrefixes; } /** * Compare this object to another CanonicalizationTransform. - * - * @param other The object to compare this - * ExclusiveCanonicalization to. + * + * @param other The object to compare this + * ExclusiveCanonicalization to. * @return true, if other is a - * ExclusiveCanonicalization and the algorithm URIs match, - * otherwise false. + * ExclusiveCanonicalization and the algorithm URIs match, + * otherwise false. * @see java.lang.Object#equals(Object) */ + @Override public boolean equals(Object other) { if (other instanceof ExclusiveCanonicalization) { - ExclusiveCanonicalization eC14n = - (ExclusiveCanonicalization) other; - boolean algURIEquals = getAlgorithmURI().equals(eC14n.getAlgorithmURI()); - boolean inclNSPrefs = - (getInclusiveNamespacePrefixes() == null || getInclusiveNamespacePrefixes().isEmpty()) - ? eC14n.getInclusiveNamespacePrefixes() == null || eC14n.getInclusiveNamespacePrefixes().isEmpty() - : getInclusiveNamespacePrefixes().equals(eC14n.getInclusiveNamespacePrefixes()); + final ExclusiveCanonicalization eC14n = + (ExclusiveCanonicalization) other; + final boolean algURIEquals = getAlgorithmURI().equals(eC14n.getAlgorithmURI()); + final boolean inclNSPrefs = + getInclusiveNamespacePrefixes() == null || getInclusiveNamespacePrefixes().isEmpty() + ? eC14n.getInclusiveNamespacePrefixes() == null || eC14n.getInclusiveNamespacePrefixes() + .isEmpty() + : getInclusiveNamespacePrefixes().equals(eC14n.getInclusiveNamespacePrefixes()); return algURIEquals && inclNSPrefs; } return false; diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/SigningTimeImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/SigningTimeImpl.java index 9026d33..9f4e22d 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/SigningTimeImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/SigningTimeImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.xml; import java.util.Date; @@ -30,18 +29,18 @@ import iaik.server.modules.xml.SigningTime; /** * An implementation of the SigningTime Property. - * + * * @author Patrick Peck * @version $Id$ */ public class SigningTimeImpl implements SigningTime { - + /** The signing time. */ - private Date signingTime; - + private final Date signingTime; + /** * Create a new SigningTimeImpl. - * + * * @param signingTime The signing time. */ public SigningTimeImpl(Date signingTime) { @@ -51,6 +50,7 @@ public class SigningTimeImpl implements SigningTime { /** * @see iaik.server.modules.xml.SigningTime#getSigningTime() */ + @Override public Date getSigningTime() { return signingTime; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/TransformationImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/TransformationImpl.java index 1595446..fa3401e 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/TransformationImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/TransformationImpl.java @@ -21,14 +21,13 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.xml; import iaik.server.modules.xml.Transformation; /** * Base implementation class for Transformation derived classes. - * + * * @author Patrick Peck * @version $Id$ */ @@ -36,32 +35,34 @@ public abstract class TransformationImpl implements Transformation { /** The algorithm URI identifying the transformation algorithm. */ private String algorithmURI; - + /** * @see iaik.server.modules.xml.Transformation#getAlgorithmURI() */ + @Override public String getAlgorithmURI() { return algorithmURI; } /** * Sets the algorithm URI. - * + * * @param algorithmURI The algorithm URI to set. */ protected void setAlgorithmURI(String algorithmURI) { this.algorithmURI = algorithmURI; } - + /** * Returns the hash code of the algorithm URI. Should be overridden if a * transformation distinguishes itself from others by more than just the * algorithm URI. - * + * * @see java.lang.Object#hashCode() */ + @Override public int hashCode() { return getAlgorithmURI().hashCode(); } - + } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XMLDataObjectImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XMLDataObjectImpl.java index e8444b9..0688d0e 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XMLDataObjectImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XMLDataObjectImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.xml; import org.w3c.dom.Element; @@ -30,22 +29,21 @@ import iaik.server.modules.xml.XMLDataObject; /** * A DataObject containing a single DOM element. - * + * * @author Patrick Peck * @version $Id$ */ public class XMLDataObjectImpl - extends DataObjectImpl - implements XMLDataObject { - - /** The XML data contained in this XMLDataObject. */ + extends DataObjectImpl + implements XMLDataObject { + + /** The XML data contained in this XMLDataObject. */ private Element element; - + /** * Create a new XMLDataObjectImpl. - * - * @param element The DOM element contained in this - * XMLDataObject. + * + * @param element The DOM element contained in this XMLDataObject. */ public XMLDataObjectImpl(Element element) { setElement(element); @@ -54,13 +52,14 @@ public class XMLDataObjectImpl /** * @see iaik.server.modules.xml.XMLDataObject#getElement() */ + @Override public Element getElement() { return element; } /** * Set the DOM element contained in this XMLDataObject. - * + * * @param element The DOM element to set. */ public void setElement(Element element) { diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XMLNodeListDataObjectImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XMLNodeListDataObjectImpl.java index 2fb9df9..51f96f0 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XMLNodeListDataObjectImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XMLNodeListDataObjectImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.xml; import org.w3c.dom.NodeList; @@ -30,22 +29,22 @@ import iaik.server.modules.xml.XMLNodeListDataObject; /** * A DataObject containing a list of DOM nodes. - * + * * @author Patrick Peck * @version $Id$ */ public class XMLNodeListDataObjectImpl - extends DataObjectImpl - implements XMLNodeListDataObject { + extends DataObjectImpl + implements XMLNodeListDataObject { /** The nodes contained in this XMLNodeListDataObject. */ private NodeList nodeList; /** * Create a new XMLNodeListDataObjectImpl. - * + * * @param nodeList The list of DOM nodes contained in this - * XMLNodeListDataObject. + * XMLNodeListDataObject. */ public XMLNodeListDataObjectImpl(NodeList nodeList) { setNodeList(nodeList); @@ -54,7 +53,7 @@ public class XMLNodeListDataObjectImpl /** * Set the list of DOM nodes contained in this * XMLNodeListDataObject. - * + * * @param nodeList The list of DOM nodes to set. */ public void setNodeList(NodeList nodeList) { @@ -64,6 +63,7 @@ public class XMLNodeListDataObjectImpl /** * @see iaik.server.modules.xml.XMLNodeListDataObject#getNodeList() */ + @Override public NodeList getNodeList() { return nodeList; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XMLSignatureImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XMLSignatureImpl.java index 0774726..1844780 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XMLSignatureImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XMLSignatureImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.xml; import org.w3c.dom.Element; @@ -29,28 +28,28 @@ import org.w3c.dom.Element; import iaik.server.modules.xml.XMLSignature; /** - * An object containing an XMLDsig signature in the form of a + * An object containing an XMLDsig signature in the form of a * dsig:Signature DOM element. - * + * * @author Patrick Peck * @version $Id$ */ public class XMLSignatureImpl implements XMLSignature { /** The signature DOM element. */ private Element element; - + /** * Create a new XMLSignatureImpl. - * + * * @param element The dsig:Signature DOM element. */ public XMLSignatureImpl(Element element) { setElement(element); } - + /** * Set the dsig:Signature DOM element. - * + * * @param element The dsig:Signature element to set. */ public void setElement(Element element) { @@ -60,6 +59,7 @@ public class XMLSignatureImpl implements XMLSignature { /** * @see iaik.server.modules.xml.XMLSignature#getElement() */ + @Override public Element getElement() { return element; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XPath2FilterImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XPath2FilterImpl.java index d309302..a44196a 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XPath2FilterImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XPath2FilterImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.xml; import java.util.Map; @@ -31,7 +30,7 @@ import iaik.server.modules.xml.XPath2Transformation.XPath2Filter; /** * An object encapsulating an XPath-Filter2 expression. - * + * * @author Patrick Peck * @version $Id$ */ @@ -46,17 +45,18 @@ public class XPath2FilterImpl implements XPath2Filter { /** * Create a new XPath2FilterImpl object. - * - * @param filterType The type of filter. Must be one of the filter type - * constants declared in iaik.server.modules.xml.XPath2Transformation.XPath2Filter - * @param xPathExpression The XPath expression belonging to this filter. + * + * @param filterType The type of filter. Must be one of the filter + * type constants declared in + * iaik.server.modules.xml.XPath2Transformation.XPath2Filter + * @param xPathExpression The XPath expression belonging to this filter. * @param namespaceDeclarations The namespace declarations visible for this - * XPath2Filter. + * XPath2Filter. */ public XPath2FilterImpl( - String filterType, - String xPathExpression, - Map namespaceDeclarations) { + String filterType, + String xPathExpression, + Map namespaceDeclarations) { setFilterType(filterType); setXPathExpression(xPathExpression); @@ -66,13 +66,14 @@ public class XPath2FilterImpl implements XPath2Filter { /** * @see iaik.server.modules.xml.XPath2Transformation.XPath2Filter#getFilterType() */ + @Override public String getFilterType() { return filterType; } /** * Set the filter type. - * + * * @param filterType The filter type to set. */ protected void setFilterType(String filterType) { @@ -82,13 +83,14 @@ public class XPath2FilterImpl implements XPath2Filter { /** * @see iaik.server.modules.xml.XPath2Transformation.XPath2Filter#getXPathExpression() */ + @Override public String getXPathExpression() { return xPathExpression; } /** * Set the XPath expression. - * + * * @param xPathExpression The XPath expression to set. */ protected void setXPathExpression(String xPathExpression) { @@ -98,15 +100,16 @@ public class XPath2FilterImpl implements XPath2Filter { /** * @see iaik.server.modules.xml.XPath2Transformation.XPath2Filter#getNamespaceDeclarations() */ + @Override public Map getNamespaceDeclarations() { return namespaceDeclarations; } /** * Set the namespace declarations. - * - * @param namespaceDeclarations The mapping between namespace prefixes and - * their associated URI. + * + * @param namespaceDeclarations The mapping between namespace prefixes and their + * associated URI. */ protected void setNamespaceDeclarations(Map namespaceDeclarations) { this.namespaceDeclarations = namespaceDeclarations; @@ -114,18 +117,19 @@ public class XPath2FilterImpl implements XPath2Filter { /** * Compare this object to another. - * + * * @param other The object to compare this XPath2Filter to. * @return true, if other is a - * XPath2Filter and the filter types match and the XPath - * expressions match. Otherwise false is returned. + * XPath2Filter and the filter types match and the XPath + * expressions match. Otherwise false is returned. * @see java.lang.Object#equals(java.lang.Object) */ + @Override public boolean equals(Object other) { if (other instanceof XPath2Transformation.XPath2Filter) { - XPath2Filter filter = (XPath2Transformation.XPath2Filter) other; + final XPath2Filter filter = (XPath2Transformation.XPath2Filter) other; return getFilterType().equals(filter.getFilterType()) - && getXPathExpression().equals(filter.getXPathExpression()); + && getXPathExpression().equals(filter.getXPathExpression()); } return false; } @@ -133,6 +137,7 @@ public class XPath2FilterImpl implements XPath2Filter { /** * @see java.lang.Object#hashCode() */ + @Override public int hashCode() { return getXPathExpression().hashCode() * 31 + getFilterType().hashCode(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XPath2TransformationImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XPath2TransformationImpl.java index f483b18..b49bd64 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XPath2TransformationImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XPath2TransformationImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.xml; import java.util.ArrayList; @@ -33,20 +32,20 @@ import iaik.server.modules.xml.XPath2Transformation; /** * An object encapsulating a Transformation containing several * XPath-Filter2 expressions. - * + * * @author Patrick Peck * @version $Id$ */ public class XPath2TransformationImpl - extends TransformationImpl - implements XPath2Transformation { + extends TransformationImpl + implements XPath2Transformation { /** The filters contained in this XPath2Transformation */ - private List xPathFilters = new ArrayList(); + private final List xPathFilters = new ArrayList(); /** * Create a new XPath2TransformationImpl. - * + * * The list of XPath-Filter2 expression is initially empty. */ public XPath2TransformationImpl() { @@ -56,13 +55,14 @@ public class XPath2TransformationImpl /** * @see iaik.server.modules.xml.XPath2Transformation#getXPathFilters() */ + @Override public List getXPathFilters() { return xPathFilters; } /** * Add an XPath-Filter2 expression to the list of filters. - * + * * @param filter The filter to add. */ public void addXPathFilter(XPath2Filter filter) { @@ -71,18 +71,18 @@ public class XPath2TransformationImpl /** * Compare this XPath2Transformation to another. - * - * @param other The object to compare this - * XPath2Transformation to. + * + * @param other The object to compare this XPath2Transformation to. * @return true, if other is an - * XPath2Transformation and getXPathFilters() equals - * other.getXPathFilters(). Otherwise false is - * returned. + * XPath2Transformation and getXPathFilters() + * equals other.getXPathFilters(). Otherwise + * false is returned. * @see java.lang.Object#equals(Object) */ + @Override public boolean equals(Object other) { if (other instanceof XPath2Transformation) { - XPath2Transformation transform = (XPath2Transformation) other; + final XPath2Transformation transform = (XPath2Transformation) other; return getXPathFilters().equals(transform.getXPathFilters()); } @@ -92,8 +92,9 @@ public class XPath2TransformationImpl /** * @see java.lang.Object#hashCode() */ + @Override public int hashCode() { - Iterator iter = getXPathFilters().iterator(); + final Iterator iter = getXPathFilters().iterator(); int hashCode = 0; while (iter.hasNext()) { diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XPathTransformationImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XPathTransformationImpl.java index 06cc319..65b33f4 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XPathTransformationImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XPathTransformationImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.xml; import java.util.Map; @@ -30,13 +29,13 @@ import iaik.server.modules.xml.XPathTransformation; /** * A Transformation containing an XPath expression. - * + * * @author Patrick Peck * @version $Id$ */ public class XPathTransformationImpl - extends TransformationImpl - implements XPathTransformation { + extends TransformationImpl + implements XPathTransformation { /** The XPath expression. */ private String xPathExpression; @@ -45,16 +44,16 @@ public class XPathTransformationImpl /** * Create a new XPathTransformationImpl. - * + * * The namespace declarations are initialized empty. - * - * @param xPathExpression The XPath expression this object will contain. + * + * @param xPathExpression The XPath expression this object will contain. * @param namespaceDeclarations The namespace declarations visible for this - * XPath. + * XPath. */ public XPathTransformationImpl( - String xPathExpression, - Map namespaceDeclarations) { + String xPathExpression, + Map namespaceDeclarations) { setAlgorithmURI(XPathTransformation.XPATH); setXPathExpression(xPathExpression); @@ -63,7 +62,7 @@ public class XPathTransformationImpl /** * Set the XPath expression. - * + * * @param xPathExpression The XPath expression. */ protected void setXPathExpression(String xPathExpression) { @@ -73,6 +72,7 @@ public class XPathTransformationImpl /** * @see iaik.server.modules.xml.XPathTransformation#getXPathExpression() */ + @Override public String getXPathExpression() { return xPathExpression; } @@ -80,15 +80,16 @@ public class XPathTransformationImpl /** * @see iaik.server.modules.xml.XPathTransformation#getNamespaceDeclarations() */ + @Override public Map getNamespaceDeclarations() { return namespaceDeclarations; } /** * Set the namespace declarations. - * - * @param namespaceDeclarations The mapping between namespace prefixes and - * their associated URI. + * + * @param namespaceDeclarations The mapping between namespace prefixes and their + * associated URI. */ protected void setNamespaceDeclarations(Map namespaceDeclarations) { this.namespaceDeclarations = namespaceDeclarations; @@ -96,17 +97,18 @@ public class XPathTransformationImpl /** * Compare this XPathTransformation to another. - * - * @param other The object to compare this - * XPathTransformation to. + * + * @param other The object to compare this XPathTransformation to. * @return true, if other is an - * XPathTransformation and if this object contains the same XPath - * expression as other. Otherwise false is returned. + * XPathTransformation and if this object contains the same + * XPath expression as other. Otherwise false + * is returned. * @see java.lang.Object#equals(Object) */ + @Override public boolean equals(Object other) { if (other instanceof XPathTransformation) { - XPathTransformation transform = (XPathTransformation) other; + final XPathTransformation transform = (XPathTransformation) other; return getXPathExpression().equals(transform.getXPathExpression()); } return false; @@ -115,6 +117,7 @@ public class XPathTransformationImpl /** * @see java.lang.Object#hashCode() */ + @Override public int hashCode() { return getXPathExpression().hashCode(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XSLTTransformationImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XSLTTransformationImpl.java index 9dc45fc..6c71f42 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XSLTTransformationImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xml/XSLTTransformationImpl.java @@ -45,204 +45,194 @@ import at.gv.egovernment.moaspss.util.XPathException; import at.gv.egovernment.moaspss.util.XPathUtils; import iaik.server.modules.xml.MOAXSecProvider; import iaik.server.modules.xml.XSLTTransformation; -import iaik.xml.crypto.dsig.XMLSignatureFactory; -import iaik.xml.filter.impl.dsig.CanonInputStream; -import iaik.xml.filter.impl.dsig.Canonicalizer; -import iaik.xml.filter.impl.dsig.Traverser; /** * A Transformation containing an XSLT transformation. - * + * * @author Patrick Peck * @version $Id$ */ public class XSLTTransformationImpl extends TransformationImpl implements XSLTTransformation { - /** The XSLT stylesheet. */ - private Element styleSheetElement; - /** - * The hash code of the canonicalized stylesheet. If calculated, this value - * should be != 0. - */ - private int hashCode; - - /** - * Create a new XSLTTransformationImpl object. - * - * @param styleSheetElement - * The XSLT stylesheet element. - */ - public XSLTTransformationImpl(Element styleSheetElement) { - setAlgorithmURI(XSLTTransformation.XSLT); - setStyleSheetElement(styleSheetElement); - } - - /** - * Set the XSLT stylesheet element. - * - * @param styleSheetElement - * The XSLT stylesheet element to set. - */ - protected void setStyleSheetElement(Element styleSheetElement) { - this.styleSheetElement = styleSheetElement; - this.hashCode = 0; - } - - /** - * @see iaik.server.modules.xml.XSLTTransformation#getStylesheetElement() - */ - public Element getStylesheetElement() { - return styleSheetElement; - } - - /** - * Compare this XSLTTransformation to another. - * - * @param other - * The object to compare this XSLTTransformation to. - * @return true, if other is an - * XSLTTransformation and if the canonicalized - * representations of the stylesheets contained in this - * and other match. Otherwise, false is - * returned. - * @see java.lang.Object#equals(Object) - */ - public boolean equals(Object other) { - if (other instanceof XSLTTransformation) { - XSLTTransformation xslt = (XSLTTransformation) other; - - return compareElements(getStylesheetElement(), xslt.getStylesheetElement()); - } - return false; - } - - /** - * @see java.lang.Object#hashCode() - */ - public int hashCode() { - if (hashCode == 0) { - hashCode = calculateHashCode(getStylesheetElement()); - } - return hashCode; - } - - /** - * Calculate the hash code for a DOM element by canonicalizing it. - * - * @param element - * The DOM element for which the hash code is to be calculated. - * @return int The hash code, or 0, if it could not be - * calculated. - */ - private static int calculateHashCode(Element element) { - try { - InputStream is = canonicalize(element); - byte[] buf = new byte[256]; - int hashCode = 1; - int length; - int i; - - while ((length = is.read(buf)) > 0) { - for (i = 0; i < length; i++) { - hashCode += buf[i] * 31 + i; - } - } - is.close(); - return hashCode; - } catch (IOException e) { - return 0; - } catch (NoSuchAlgorithmException e) { - return 0; - } catch (InvalidAlgorithmParameterException e) { - return 0; - } catch (TransformException e) { - return 0; - } - } - - /** - * Compare two DOM elements by canonicalizing their contents and comparing - * the resulting byte stream. - * - * @param elem1 - * The 1st element to compare. - * @param elem2 - * The 2nd element to compare. - * @return boolean true, if the elements are considered equal - * after canonicalization. Otherwise false is returned. - */ - private static boolean compareElements(Element elem1, Element elem2) { - try { - InputStream is1 = canonicalize(elem1); - InputStream is2 = canonicalize(elem2); - return StreamUtils.compareStreams(is1, is2); - } catch (IOException e) { - return false; - } catch (NoSuchAlgorithmException e) { - return false; - } catch (InvalidAlgorithmParameterException e) { - return false; - } catch (TransformException e) { - return false; - } - } - - /** - * Canonicalize a DOM element. + /** The XSLT stylesheet. */ + private Element styleSheetElement; + /** + * The hash code of the canonicalized stylesheet. If calculated, this value + * should be != 0. + */ + private int hashCode; + + /** + * Create a new XSLTTransformationImpl object. + * + * @param styleSheetElement The XSLT stylesheet element. + */ + public XSLTTransformationImpl(Element styleSheetElement) { + setAlgorithmURI(XSLTTransformation.XSLT); + setStyleSheetElement(styleSheetElement); + } + + /** + * Set the XSLT stylesheet element. + * + * @param styleSheetElement The XSLT stylesheet element to set. + */ + protected void setStyleSheetElement(Element styleSheetElement) { + this.styleSheetElement = styleSheetElement; + this.hashCode = 0; + } + + /** + * @see iaik.server.modules.xml.XSLTTransformation#getStylesheetElement() + */ + @Override + public Element getStylesheetElement() { + return styleSheetElement; + } + + /** + * Compare this XSLTTransformation to another. + * + * @param other The object to compare this XSLTTransformation to. + * @return true, if other is an + * XSLTTransformation and if the canonicalized + * representations of the stylesheets contained in this and + * other match. Otherwise, false is returned. + * @see java.lang.Object#equals(Object) + */ + @Override + public boolean equals(Object other) { + if (other instanceof XSLTTransformation) { + final XSLTTransformation xslt = (XSLTTransformation) other; + + return compareElements(getStylesheetElement(), xslt.getStylesheetElement()); + } + return false; + } + + /** + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + if (hashCode == 0) { + hashCode = calculateHashCode(getStylesheetElement()); + } + return hashCode; + } + + /** + * Calculate the hash code for a DOM element by canonicalizing it. * + * @param element The DOM element for which the hash code is to be calculated. + * @return int The hash code, or 0, if it could not be calculated. + */ + private static int calculateHashCode(Element element) { + try { + final InputStream is = canonicalize(element); + final byte[] buf = new byte[256]; + int hashCode = 1; + int length; + int i; + + while ((length = is.read(buf)) > 0) { + for (i = 0; i < length; i++) { + hashCode += buf[i] * 31 + i; + } + } + is.close(); + return hashCode; + } catch (final IOException e) { + return 0; + } catch (final NoSuchAlgorithmException e) { + return 0; + } catch (final InvalidAlgorithmParameterException e) { + return 0; + } catch (final TransformException e) { + return 0; + } + } + + /** + * Compare two DOM elements by canonicalizing their contents and comparing the + * resulting byte stream. + * + * @param elem1 The 1st element to compare. + * @param elem2 The 2nd element to compare. + * @return boolean true, if the elements are considered equal after + * canonicalization. Otherwise false is returned. + */ + private static boolean compareElements(Element elem1, Element elem2) { + try { + final InputStream is1 = canonicalize(elem1); + final InputStream is2 = canonicalize(elem2); + return StreamUtils.compareStreams(is1, is2); + } catch (final IOException e) { + return false; + } catch (final NoSuchAlgorithmException e) { + return false; + } catch (final InvalidAlgorithmParameterException e) { + return false; + } catch (final TransformException e) { + return false; + } + } + + /** + * Canonicalize a DOM element. + * * @param element The element to canonicalize. * @return InputStream A stream with the canonicalized data. - * @throws InvalidAlgorithmParameterException - * @throws IOException - * @throws TransformException - * @throws AlgorithmException An error occurred canonicalizing the element. + * @throws InvalidAlgorithmParameterException + * @throws IOException + * @throws TransformException + * @throws AlgorithmException An error occurred canonicalizing + * the element. */ private static InputStream canonicalize(Element element) - throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, IOException, TransformException { - // CanonicalizationMethod canonicalizationMethod = - // MOAXSecProvider.getXMLSignatureFactory().newCanonicalizationMethod( - // CanonicalizationMethod.EXCLUSIVE, new ExcC14NParameterSpec()); - - //CanonicalizationAlgorithm c14n = - // new CanonicalizationAlgorithmImplExclusiveCanonicalXML(); - //Traverser traverser = new Traverser(element, true, true); - //Canonicalizer canonicalizer = new Canonicalizer(traverser, false, true, null); - - //return new CanonInputStream(canonicalizer); - - CanonicalizationMethod canonicalizationMethod = - MOAXSecProvider.getXMLSignatureFactory().newCanonicalizationMethod( - CanonicalizationMethod.EXCLUSIVE, new ExcC14NParameterSpec()); - - //CanonicalizationAlgorithm c14n = - // new CanonicalizationAlgorithmImplExclusiveCanonicalXML(); - NodeList nodeList; - - try { - nodeList = XPathUtils.selectNodeList(element, - XPathUtils.ALL_NODES_XPATH); - } catch (XPathException e) { - nodeList = new NodeListAdapter(Collections.EMPTY_LIST); - } - //c14n.setInput(nodeList); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - canonicalizationMethod.transform(new - NodeListToNodeSetDataAdapter(nodeList), null, baos); - baos.close(); - return new ByteArrayInputStream(baos.toByteArray()); - /* - NodeList nodeList; - + throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, IOException, TransformException { + // CanonicalizationMethod canonicalizationMethod = + // MOAXSecProvider.getXMLSignatureFactory().newCanonicalizationMethod( + // CanonicalizationMethod.EXCLUSIVE, new ExcC14NParameterSpec()); + + // CanonicalizationAlgorithm c14n = + // new CanonicalizationAlgorithmImplExclusiveCanonicalXML(); + // Traverser traverser = new Traverser(element, true, true); + // Canonicalizer canonicalizer = new Canonicalizer(traverser, false, true, + // null); + + // return new CanonInputStream(canonicalizer); + + final CanonicalizationMethod canonicalizationMethod = + MOAXSecProvider.getXMLSignatureFactory().newCanonicalizationMethod( + CanonicalizationMethod.EXCLUSIVE, new ExcC14NParameterSpec()); + + // CanonicalizationAlgorithm c14n = + // new CanonicalizationAlgorithmImplExclusiveCanonicalXML(); + NodeList nodeList; + try { - nodeList = XPathUtils.selectNodeList(element, XPathUtils.ALL_NODES_XPATH); - } catch (XPathException e) { + nodeList = XPathUtils.selectNodeList(element, + XPathUtils.ALL_NODES_XPATH); + } catch (final XPathException e) { nodeList = new NodeListAdapter(Collections.EMPTY_LIST); } - //c14n.setInput(nodeList); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + // c14n.setInput(nodeList); + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); canonicalizationMethod.transform(new NodeListToNodeSetDataAdapter(nodeList), null, baos); baos.close(); - return new ByteArrayInputStream(baos.toByteArray());*/ + return new ByteArrayInputStream(baos.toByteArray()); + /* + * NodeList nodeList; + * + * try { nodeList = XPathUtils.selectNodeList(element, + * XPathUtils.ALL_NODES_XPATH); } catch (XPathException e) { nodeList = new + * NodeListAdapter(Collections.EMPTY_LIST); } //c14n.setInput(nodeList); + * ByteArrayOutputStream baos = new ByteArrayOutputStream(); + * canonicalizationMethod.transform(new NodeListToNodeSetDataAdapter(nodeList), + * null, baos); baos.close(); return new + * ByteArrayInputStream(baos.toByteArray()); + */ } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xmlsign/DataObjectTreatmentImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xmlsign/DataObjectTreatmentImpl.java index 310f2dd..6eb565a 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xmlsign/DataObjectTreatmentImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xmlsign/DataObjectTreatmentImpl.java @@ -21,19 +21,17 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.xmlsign; import java.util.List; -import iaik.server.modules.xmlsign.DataObjectTreatment; - import at.gv.egovernment.moa.spss.server.util.IdGenerator; +import iaik.server.modules.xmlsign.DataObjectTreatment; /** * An object encapsulating how to treat an associated DataObject * when creating a signature. - * + * * @author Patrick Peck * @version $Id$ */ @@ -51,29 +49,30 @@ public class DataObjectTreatmentImpl implements DataObjectTreatment { /** Whether to include the associated data object in the manifest. */ private boolean referenceInManifest; /** The object ID generator. */ - private IdGenerator objIdGen; - + private final IdGenerator objIdGen; + /** * Create a new DataObjectTreatmentImpl. - * + * * @param objIdGen The IdGenerator for unique object IDs. */ public DataObjectTreatmentImpl(IdGenerator objIdGen) { this.objIdGen = objIdGen; } - + /** * @see iaik.server.modules.xmlsign.DataObjectTreatment#getFinalContentType() */ + @Override public String getFinalContentType() { return finalContentType; } /** * Sets the final content type. - * + * * @param finalContentType The final content type to set (a MIME-type type of - * String). + * String). */ public void setFinalContentType(String finalContentType) { this.finalContentType = finalContentType; @@ -82,13 +81,14 @@ public class DataObjectTreatmentImpl implements DataObjectTreatment { /** * @see iaik.server.modules.xmlsign.DataObjectTreatment#getHashAlgorithmName() */ + @Override public String getHashAlgorithmName() { return hashAlgorithmName; } /** * Sets the hash algorithm name. - * + * * @param hashAlgorithmName The hash algorithm name to set. */ public void setHashAlgorithmName(String hashAlgorithmName) { @@ -98,16 +98,18 @@ public class DataObjectTreatmentImpl implements DataObjectTreatment { /** * @see iaik.server.modules.xmlsign.DataObjectTreatment#isIncludedInSignature() */ + @Override public boolean isIncludedInSignature() { return includedInSignature; } /** - * Sets whether the associated DataObject is to be included in - * the signature. - * + * Sets whether the associated DataObject is to be included in the + * signature. + * * @param includedInSignature If true, the associated - * DataObject will be included in the signature, otherwise not. + * DataObject will be included in the + * signature, otherwise not. */ public void setIncludedInSignature(boolean includedInSignature) { this.includedInSignature = includedInSignature; @@ -116,16 +118,18 @@ public class DataObjectTreatmentImpl implements DataObjectTreatment { /** * @see iaik.server.modules.xmlsign.DataObjectTreatment#isReferenceInManifest() */ + @Override public boolean isReferenceInManifest() { return referenceInManifest; } /** - * Sets whether the associated DataObject is - * to be included in the dsig:Manifest. - * + * Sets whether the associated DataObject is to be included in the + * dsig:Manifest. + * * @param referenceInManifest If true, the associated - * DataObject will be included in the manifest, otherwise not. + * DataObject will be included in the + * manifest, otherwise not. */ public void setReferenceInManifest(boolean referenceInManifest) { this.referenceInManifest = referenceInManifest; @@ -134,13 +138,14 @@ public class DataObjectTreatmentImpl implements DataObjectTreatment { /** * @see iaik.server.modules.xmlsign.DataObjectTreatment#getTransformationList() */ + @Override public List getTransformationList() { return transformationList; } /** * Set the list of transformations for the associated DataObject. - * + * * @param transformationList The transformations to set. */ public void setTransformationList(List transformationList) { @@ -150,6 +155,7 @@ public class DataObjectTreatmentImpl implements DataObjectTreatment { /** * @see iaik.server.modules.xmlsign.DataObjectTreatment#getTransformationSupplements() */ + @Override public List getTransformationSupplements() { return transformationSupplements; } @@ -157,16 +163,17 @@ public class DataObjectTreatmentImpl implements DataObjectTreatment { /** * Sets the transformation supplements for the associated * DataObject. - * + * * @param transformationSupplements The transformation supplements to set. */ public void setTransformationSupplements(List transformationSupplements) { this.transformationSupplements = transformationSupplements; } - + /** * @see iaik.server.modules.xmlsign.DataObjectTreatment#getDsigDataObjectID() */ + @Override public String getDsigDataObjectID() { return objIdGen.uniqueId(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xmlsign/XMLSignatureCreationProfileImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xmlsign/XMLSignatureCreationProfileImpl.java index 9d6e3d2..516e3d8 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xmlsign/XMLSignatureCreationProfileImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xmlsign/XMLSignatureCreationProfileImpl.java @@ -21,9 +21,16 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.xmlsign; +import java.util.List; +import java.util.Set; + +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.moa.spss.server.util.IdGenerator; +import at.gv.egovernment.moaspss.logging.Logger; import iaik.server.modules.algorithms.SignatureAlgorithms; import iaik.server.modules.keys.AlgorithmUnavailableException; import iaik.server.modules.keys.KeyEntryID; @@ -34,23 +41,14 @@ import iaik.server.modules.xml.Canonicalization; import iaik.server.modules.xmlsign.XMLSignatureCreationProfile; import iaik.server.modules.xmlsign.XMLSignatureInsertionLocation; -import java.util.List; -import java.util.Set; - -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.moa.spss.server.util.IdGenerator; -import at.gv.egovernment.moaspss.logging.Logger; - /** * An object providing auxiliary information for creating an XML signature. - * + * * @author Patrick Peck * @version $Id$ */ public class XMLSignatureCreationProfileImpl - implements XMLSignatureCreationProfile { + implements XMLSignatureCreationProfile { /** The transformations to apply to a data object. */ private List dataObjectTreatmentList; @@ -58,7 +56,7 @@ public class XMLSignatureCreationProfileImpl private Set keySet; /** The type URI of the signature manifest. */ private String securityLayerManifestTypeURI; - /** Whether the created signature is to be Security Layer conform. */ + /** Whether the created signature is to be Security Layer conform. */ private boolean securityLayerConform; /** Where to insert the signature into the signature environment. */ private XMLSignatureInsertionLocation signatureInsertionLocation; @@ -66,55 +64,55 @@ public class XMLSignatureCreationProfileImpl private String signatureStructureType; /** The type of Canonicalization to use for the signed info. */ private Canonicalization signedInfoCanonicalization; - /** Properties to be signed during signature creation. */ + /** Properties to be signed during signature creation. */ private List signedProperties; /** The ID generator for signature IDs. */ - private IdGenerator signatureIDGenerator; + private final IdGenerator signatureIDGenerator; /** The ID generator for manifst IDs. */ - private IdGenerator manifestIDGenerator; + private final IdGenerator manifestIDGenerator; /** The ID generator for XMLDsig manifest IDs. */ - private IdGenerator dsigManifestIDGenerator; + private final IdGenerator dsigManifestIDGenerator; /** The ID generator for signed property IDs. */ - private IdGenerator propertyIDGenerator; - /** The selected digest method algorithm if XAdES 1.4.2 is used */ - private String digestMethodXAdES142; - - + private final IdGenerator propertyIDGenerator; + /** The selected digest method algorithm if XAdES 1.4.2 is used */ + private final String digestMethodXAdES142; + /** * Create a new XMLSignatureCreationProfileImpl. - * - * @param createProfileCount Provides external information about the - * number of calls to the signature creation module, using the same request. - * @param reservedIDs The set of IDs that must not be used while generating - * new IDs. + * + * @param createProfileCount Provides external information about the number of + * calls to the signature creation module, using the + * same request. + * @param reservedIDs The set of IDs that must not be used while + * generating new IDs. */ public XMLSignatureCreationProfileImpl( - int createProfileCount, - Set reservedIDs, - String digestMethodXAdES142) { + int createProfileCount, + Set reservedIDs, + String digestMethodXAdES142) { signatureIDGenerator = - new IdGenerator("signature-" + createProfileCount, reservedIDs); + new IdGenerator("signature-" + createProfileCount, reservedIDs); manifestIDGenerator = - new IdGenerator("manifest-" + createProfileCount, reservedIDs); + new IdGenerator("manifest-" + createProfileCount, reservedIDs); dsigManifestIDGenerator = - new IdGenerator("dsig-manifest-" + createProfileCount, reservedIDs); + new IdGenerator("dsig-manifest-" + createProfileCount, reservedIDs); propertyIDGenerator = - new IdGenerator("etsi-signed-" + createProfileCount, reservedIDs); + new IdGenerator("etsi-signed-" + createProfileCount, reservedIDs); this.digestMethodXAdES142 = digestMethodXAdES142; } /** * @see iaik.server.modules.xmlsign.XMLSignatureCreationProfile#getDataObjectTreatmentList() */ + @Override public List getDataObjectTreatmentList() { return dataObjectTreatmentList; } /** * Sets the list of DataObjectTreatments. - * - * @param dataObjectTreatmentList The DataObjectTreatments to - * set. + * + * @param dataObjectTreatmentList The DataObjectTreatments to set. */ public void setDataObjectTreatmentList(List dataObjectTreatmentList) { this.dataObjectTreatmentList = dataObjectTreatmentList; @@ -123,6 +121,7 @@ public class XMLSignatureCreationProfileImpl /** * @see iaik.server.modules.xmlsign.XMLSignatureCreationProfile#getKeySet() */ + @Override public Set getKeySet() { return keySet; } @@ -130,7 +129,7 @@ public class XMLSignatureCreationProfileImpl /** * Set the set of KeyEntryIDs which may be used for signature * creation. - * + * * @param keySet The set of KeyEntryIDs to set. */ public void setKeySet(Set keySet) { @@ -140,15 +139,15 @@ public class XMLSignatureCreationProfileImpl /** * @see iaik.server.modules.xmlsign.XMLSignatureCreationProfile#getSecurityLayerManifestTypeURI() */ + @Override public String getSecurityLayerManifestTypeURI() { return securityLayerManifestTypeURI; } /** * Set the SecurityLayerManifestTypeURI. - * - * @param securityLayerManifestTypeURI The SecurityLayerManifestTypeURI to - * set. + * + * @param securityLayerManifestTypeURI The SecurityLayerManifestTypeURI to set. */ public void setSecurityLayerManifestTypeURI(String securityLayerManifestTypeURI) { this.securityLayerManifestTypeURI = securityLayerManifestTypeURI; @@ -157,132 +156,131 @@ public class XMLSignatureCreationProfileImpl /** * @see iaik.server.modules.xmlsign.XMLSignatureCreationProfile#getSignatureAlgorithmName(KeyEntryID) */ + @Override public String getSignatureAlgorithmName(KeyEntryID selectedKeyID) - throws AlgorithmUnavailableException { + throws AlgorithmUnavailableException { - TransactionContext context = - TransactionContextManager.getInstance().getTransactionContext(); - TransactionId tid = new TransactionId(context.getTransactionID()); - KeyModule module = KeyModuleFactory.getInstance(tid); + final TransactionContext context = + TransactionContextManager.getInstance().getTransactionContext(); + final TransactionId tid = new TransactionId(context.getTransactionID()); + final KeyModule module = KeyModuleFactory.getInstance(tid); Set algorithms; try { algorithms = module.getSupportedSignatureAlgorithms(selectedKeyID); - } catch (UnknownKeyException e) { + } catch (final UnknownKeyException e) { throw new AlgorithmUnavailableException( - "Unknown key entry: " + selectedKeyID, - e, - null); + "Unknown key entry: " + selectedKeyID, + e, + null); } - + if (digestMethodXAdES142 == null) { - // XAdES 1.4.2 not enabled - legacy MOA - if (algorithms.contains(SignatureAlgorithms.MD2_WITH_RSA) - || algorithms.contains(SignatureAlgorithms.MD5_WITH_RSA) - || algorithms.contains(SignatureAlgorithms.RIPEMD128_WITH_RSA) - || algorithms.contains(SignatureAlgorithms.RIPEMD160_WITH_RSA) - || algorithms.contains(SignatureAlgorithms.SHA1_WITH_RSA) - || algorithms.contains(SignatureAlgorithms.SHA256_WITH_RSA)) { - - return SignatureAlgorithms.SHA1_WITH_RSA; - } else if ( - algorithms.contains(SignatureAlgorithms.ECDSA)) { - return SignatureAlgorithms.ECDSA; - } else if ( - algorithms.contains(SignatureAlgorithms.DSA)) { - return SignatureAlgorithms.DSA; + // XAdES 1.4.2 not enabled - legacy MOA + if (algorithms.contains(SignatureAlgorithms.MD2_WITH_RSA) + || algorithms.contains(SignatureAlgorithms.MD5_WITH_RSA) + || algorithms.contains(SignatureAlgorithms.RIPEMD128_WITH_RSA) + || algorithms.contains(SignatureAlgorithms.RIPEMD160_WITH_RSA) + || algorithms.contains(SignatureAlgorithms.SHA1_WITH_RSA) + || algorithms.contains(SignatureAlgorithms.SHA256_WITH_RSA)) { + + return SignatureAlgorithms.SHA1_WITH_RSA; + } else if (algorithms.contains(SignatureAlgorithms.ECDSA)) { + return SignatureAlgorithms.ECDSA; + } else if (algorithms.contains(SignatureAlgorithms.DSA)) { + return SignatureAlgorithms.DSA; + } else { + throw new AlgorithmUnavailableException( + "No algorithm for key entry: " + selectedKeyID, + null, + null); + } + } else { + // XAdES 1.4.2 is enabled: select signature algorithm according to selected + // digest method + if (digestMethodXAdES142.compareTo("SHA-1") == 0) { + Logger.warn( + "XAdES version 1.4.2 is enabled, but SHA-1 is configured as digest algorithm. Please revise a use of a more secure digest algorithm out of the SHA-2 family (e.g. SHA-256, SHA-384, SHA-512)"); + + if (algorithms.contains(SignatureAlgorithms.SHA1_WITH_RSA)) { + return SignatureAlgorithms.SHA1_WITH_RSA; + + } else if (algorithms.contains(SignatureAlgorithms.ECDSA)) { + return SignatureAlgorithms.ECDSA; + + } else if (algorithms.contains(SignatureAlgorithms.DSA)) { + return SignatureAlgorithms.DSA; + } else { - throw new AlgorithmUnavailableException( - "No algorithm for key entry: " + selectedKeyID, - null, - null); + throw new AlgorithmUnavailableException( + "No algorithm for key entry: " + selectedKeyID, + null, + null); } + + } else if (digestMethodXAdES142.compareTo("SHA-256") == 0) { + if (algorithms.contains(SignatureAlgorithms.SHA256_WITH_RSA)) { + return SignatureAlgorithms.SHA256_WITH_RSA; + + } else if (algorithms.contains(SignatureAlgorithms.SHA256_WITH_ECDSA)) { + return SignatureAlgorithms.SHA256_WITH_ECDSA; + + } else if (algorithms.contains(SignatureAlgorithms.DSA)) { + return SignatureAlgorithms.DSA; + + } else { + throw new AlgorithmUnavailableException( + "No algorithm for key entry: " + selectedKeyID, + null, + null); + } + } else if (digestMethodXAdES142.compareTo("SHA-384") == 0) { + if (algorithms.contains(SignatureAlgorithms.SHA384_WITH_RSA)) { + return SignatureAlgorithms.SHA384_WITH_RSA; + + } else if (algorithms.contains(SignatureAlgorithms.SHA384_WITH_ECDSA)) { + return SignatureAlgorithms.SHA384_WITH_ECDSA; + + } else if (algorithms.contains(SignatureAlgorithms.DSA)) { + return SignatureAlgorithms.DSA; + + } else { + throw new AlgorithmUnavailableException( + "No algorithm for key entry: " + selectedKeyID, + null, + null); + } + } else if (digestMethodXAdES142.compareTo("SHA-512") == 0) { + if (algorithms.contains(SignatureAlgorithms.SHA512_WITH_RSA)) { + return SignatureAlgorithms.SHA512_WITH_RSA; + + } else if (algorithms.contains(SignatureAlgorithms.SHA512_WITH_ECDSA)) { + return SignatureAlgorithms.SHA512_WITH_ECDSA; + + } else if (algorithms.contains(SignatureAlgorithms.DSA)) { + return SignatureAlgorithms.DSA; + + } else { + throw new AlgorithmUnavailableException( + "No algorithm for key entry: " + selectedKeyID, + null, + null); + } + } else { + throw new AlgorithmUnavailableException( + "No signature algorithm found for digest algorithm '" + digestMethodXAdES142, + null, + null); + } + } - else { - // XAdES 1.4.2 is enabled: select signature algorithm according to selected digest method - if (digestMethodXAdES142.compareTo("SHA-1") == 0) { - Logger.warn("XAdES version 1.4.2 is enabled, but SHA-1 is configured as digest algorithm. Please revise a use of a more secure digest algorithm out of the SHA-2 family (e.g. SHA-256, SHA-384, SHA-512)"); - - if (algorithms.contains(SignatureAlgorithms.SHA1_WITH_RSA)) { - return SignatureAlgorithms.SHA1_WITH_RSA; - - } else if (algorithms.contains(SignatureAlgorithms.ECDSA)) { - return SignatureAlgorithms.ECDSA; - - } else if (algorithms.contains(SignatureAlgorithms.DSA)) { - return SignatureAlgorithms.DSA; - - } else { - throw new AlgorithmUnavailableException( - "No algorithm for key entry: " + selectedKeyID, - null, - null); - } - - } else if (digestMethodXAdES142.compareTo("SHA-256") == 0) { - if (algorithms.contains(SignatureAlgorithms.SHA256_WITH_RSA)) { - return SignatureAlgorithms.SHA256_WITH_RSA; - - } else if (algorithms.contains(SignatureAlgorithms.SHA256_WITH_ECDSA)) { - return SignatureAlgorithms.SHA256_WITH_ECDSA; - - } else if (algorithms.contains(SignatureAlgorithms.DSA)) { - return SignatureAlgorithms.DSA; - - } else { - throw new AlgorithmUnavailableException( - "No algorithm for key entry: " + selectedKeyID, - null, - null); - } - } else if (digestMethodXAdES142.compareTo("SHA-384") == 0) { - if (algorithms.contains(SignatureAlgorithms.SHA384_WITH_RSA)) { - return SignatureAlgorithms.SHA384_WITH_RSA; - - } else if (algorithms.contains(SignatureAlgorithms.SHA384_WITH_ECDSA)) { - return SignatureAlgorithms.SHA384_WITH_ECDSA; - - } else if (algorithms.contains(SignatureAlgorithms.DSA)) { - return SignatureAlgorithms.DSA; - - } else { - throw new AlgorithmUnavailableException( - "No algorithm for key entry: " + selectedKeyID, - null, - null); - } - } else if (digestMethodXAdES142.compareTo("SHA-512") == 0) { - if (algorithms.contains(SignatureAlgorithms.SHA512_WITH_RSA)) { - return SignatureAlgorithms.SHA512_WITH_RSA; - - } else if (algorithms.contains(SignatureAlgorithms.SHA512_WITH_ECDSA)) { - return SignatureAlgorithms.SHA512_WITH_ECDSA; - - } else if (algorithms.contains(SignatureAlgorithms.DSA)) { - return SignatureAlgorithms.DSA; - - } else { - throw new AlgorithmUnavailableException( - "No algorithm for key entry: " + selectedKeyID, - null, - null); - } - } - else { - throw new AlgorithmUnavailableException( - "No signature algorithm found for digest algorithm '" + digestMethodXAdES142, - null, - null); - } - - } - } /** * @see iaik.server.modules.xmlsign.XMLSignatureCreationProfile#getSignatureInsertionLocation() */ + @Override public XMLSignatureInsertionLocation getSignatureInsertionLocation() { return signatureInsertionLocation; } @@ -290,7 +288,7 @@ public class XMLSignatureCreationProfileImpl /** * Set the location where the signature is to be inserted into the signature * parent. - * + * * @param signatureInsertionLocation The location to set. */ public void setSignatureInsertionLocation(XMLSignatureInsertionLocation signatureInsertionLocation) { @@ -300,12 +298,14 @@ public class XMLSignatureCreationProfileImpl /** * @see iaik.server.modules.xmlsign.XMLSignatureCreationProfile#getSignatureStructureType() */ + @Override public String getSignatureStructureType() { return signatureStructureType; } /** * Set the signature structure type. + * * @param signatureStructureType The signature structure type to set. */ public void setSignatureStructureType(String signatureStructureType) { @@ -315,13 +315,14 @@ public class XMLSignatureCreationProfileImpl /** * @see iaik.server.modules.xmlsign.XMLSignatureCreationProfile#getSignedInfoCanonicalization() */ + @Override public Canonicalization getSignedInfoCanonicalization() { return signedInfoCanonicalization; } /** * Sets the canonicalization method to use for the SignedInfo object. - * + * * @param signedInfoCanonicalization The canonicalization method to set. */ public void setSignedInfoCanonicalization(Canonicalization signedInfoCanonicalization) { @@ -331,13 +332,14 @@ public class XMLSignatureCreationProfileImpl /** * @see iaik.server.modules.xmlsign.XMLSignatureCreationProfile#getSignedProperties() */ + @Override public List getSignedProperties() { return signedProperties; } /** * Set the signed properties. - * + * * @param signedProperties The signed properties to set. */ public void setSignedProperties(List signedProperties) { @@ -347,15 +349,16 @@ public class XMLSignatureCreationProfileImpl /** * @see iaik.server.modules.xmlsign.XMLSignatureCreationProfile#isSecurityLayerConform() */ + @Override public boolean isSecurityLayerConform() { return securityLayerConform; } /** * Sets the security layer conformity. - * - * @param securityLayerConform true, if the created signature - * is to be conform to the Security Layer specification. + * + * @param securityLayerConform true, if the created signature is to + * be conform to the Security Layer specification. */ public void setSecurityLayerConform(boolean securityLayerConform) { this.securityLayerConform = securityLayerConform; @@ -364,6 +367,7 @@ public class XMLSignatureCreationProfileImpl /** * @see iaik.server.modules.xmlsign.XMLSignatureCreationProfile#getSignatureID() */ + @Override public String getSignatureID() { return signatureIDGenerator.uniqueId(); } @@ -371,6 +375,7 @@ public class XMLSignatureCreationProfileImpl /** * @see iaik.server.modules.xmlsign.XMLSignatureCreationProfile#getSecurityLayerManifestID() */ + @Override public String getSecurityLayerManifestID() { return manifestIDGenerator.uniqueId(); } @@ -378,6 +383,7 @@ public class XMLSignatureCreationProfileImpl /** * @see iaik.server.modules.xmlsign.XMLSignatureCreationProfile#getDsigManifestID() */ + @Override public String getDsigManifestID() { return dsigManifestIDGenerator.uniqueId(); } @@ -385,13 +391,15 @@ public class XMLSignatureCreationProfileImpl /** * @see iaik.server.modules.xmlsign.XMLSignatureCreationProfile#getSignedPropertiesID() */ + @Override public String getSignedPropertiesID() { return propertyIDGenerator.uniqueId(); } - + /** * @see iaik.server.modules.xmlsign.XMLSignatureCreationProfile#getPermitFileURIs() */ + @Override public boolean getPermitFileURIs() { return false; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xmlsign/XMLSignatureInsertionLocationImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xmlsign/XMLSignatureInsertionLocationImpl.java index 90c1f49..a5290a7 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xmlsign/XMLSignatureInsertionLocationImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xmlsign/XMLSignatureInsertionLocationImpl.java @@ -21,29 +21,28 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.xmlsign; import iaik.server.modules.xmlsign.XMLSignatureInsertionLocation; /** - * An object giving the location of where the signature will be - * inserted into the parent element. - * + * An object giving the location of where the signature will be inserted into + * the parent element. + * * @author Patrick Peck * @version $Id$ */ public class XMLSignatureInsertionLocationImpl - implements XMLSignatureInsertionLocation { + implements XMLSignatureInsertionLocation { /** Where to put the signature into the signature parent element. */ private int signatureChildIndex; - + /** * Create a new XMLSignatureInsertLocationImpl. - * + * * @param signatureChildIndex The position index at which to append the - * signature to the parent element. + * signature to the parent element. */ public XMLSignatureInsertionLocationImpl(int signatureChildIndex) { setSignatureChildIndex(signatureChildIndex); @@ -52,6 +51,7 @@ public class XMLSignatureInsertionLocationImpl /** * @see iaik.server.modules.xmlsign.XMLSignatureInsertionLocation#getSignatureChildIndex() */ + @Override public int getSignatureChildIndex() { return signatureChildIndex; } @@ -59,7 +59,7 @@ public class XMLSignatureInsertionLocationImpl /** * Sets the position index at which to append the signature to the parent * element. - * + * * @param signatureChildIndex The position index to set. */ public void setSignatureChildIndex(int signatureChildIndex) { diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xmlverify/XMLSignatureVerificationProfileImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xmlverify/XMLSignatureVerificationProfileImpl.java index 0ad3d79..6e4883f 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xmlverify/XMLSignatureVerificationProfileImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/iaik/xmlverify/XMLSignatureVerificationProfileImpl.java @@ -21,22 +21,22 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.iaik.xmlverify; import java.util.List; import iaik.pki.PKIProfile; +import iaik.server.modules.SignatureVerificationProfile; import iaik.server.modules.xmlverify.XMLSignatureVerificationProfile; /** * An object providing auxiliary information for verifying an XML signature. - * + * * @author Patrick Peck * @version $Id$ */ public class XMLSignatureVerificationProfileImpl - implements XMLSignatureVerificationProfile { + implements XMLSignatureVerificationProfile { /** Whether to check the Security Layer manifest. */ private boolean checkSecurityLayerManifest; @@ -52,18 +52,20 @@ public class XMLSignatureVerificationProfileImpl private boolean includeReferenceInputData; /** Whether the file URIs are permitted */ private boolean permitFileURIs; + /** * @see iaik.server.modules.xmlverify.XMLSignatureVerificationProfile#checkSecurityLayerManifest() */ + @Override public boolean checkSecurityLayerManifest() { return checkSecurityLayerManifest; } /** * Set whether to check the references in the Security Layer manifest. - * - * @param checkSecurityLayerManifest true, if the references - * in the Security Layer manifest must be checked. + * + * @param checkSecurityLayerManifest true, if the references in the + * Security Layer manifest must be checked. */ public void setCheckSecurityLayerManifest(boolean checkSecurityLayerManifest) { this.checkSecurityLayerManifest = checkSecurityLayerManifest; @@ -72,15 +74,16 @@ public class XMLSignatureVerificationProfileImpl /** * @see iaik.server.modules.xmlverify.XMLSignatureVerificationProfile#checkXMLDsigManifests() */ + @Override public boolean checkXMLDsigManifests() { return checkXMLDsigManifests; } /** * Sets whether to check the references of all XML Dsig manifests. - * - * @param checkXMLDSigManifests true, if the references in the - * XML Dsig manifest must be checked. + * + * @param checkXMLDSigManifests true, if the references in the XML + * Dsig manifest must be checked. */ public void setCheckXMLDsigManifests(boolean checkXMLDSigManifests) { this.checkXMLDsigManifests = checkXMLDSigManifests; @@ -89,15 +92,16 @@ public class XMLSignatureVerificationProfileImpl /** * @see iaik.server.modules.xmlverify.XMLSignatureVerificationProfile#getCertificateValidationProfile() */ + @Override public PKIProfile getCertificateValidationProfile() { return certificateValidationProfile; } /** * Sets the profile for validating the signer certificate. - * + * * @param certificateValidationProfile The certificate validation profile to - * set. + * set. */ public void setCertificateValidationProfile(PKIProfile certificateValidationProfile) { this.certificateValidationProfile = certificateValidationProfile; @@ -106,13 +110,14 @@ public class XMLSignatureVerificationProfileImpl /** * @see iaik.server.modules.xmlverify.XMLSignatureVerificationProfile#getTransformationSupplements() */ + @Override public List getTransformationSupplements() { return transformationSupplements; } /** * Sets the transformation supplements. - * + * * @param transformationSupplements The transformation supplements to set. */ public void setTransformationSupplements(List transformationSupplements) { @@ -122,15 +127,16 @@ public class XMLSignatureVerificationProfileImpl /** * @see iaik.server.modules.xmlverify.XMLSignatureVerificationProfile#includeHashInputData() */ + @Override public boolean includeHashInputData() { return includeHashInputData; } /** * Set whether to include the hash input data in the result. - * - * @param includeHashInputData If true, the hash input data - * will be returned in the result. + * + * @param includeHashInputData If true, the hash input data will be + * returned in the result. */ public void setIncludeHashInputData(boolean includeHashInputData) { this.includeHashInputData = includeHashInputData; @@ -139,39 +145,40 @@ public class XMLSignatureVerificationProfileImpl /** * @see iaik.server.modules.xmlverify.XMLSignatureVerificationProfile#includeReferenceInputData() */ + @Override public boolean includeReferenceInputData() { return includeReferenceInputData; } /** * Set whether to include the reference input data in the result. - * - * @param includeReferenceInputData If true, the reference - * input data will be included in the result. + * + * @param includeReferenceInputData If true, the reference input + * data will be included in the result. */ public void setIncludeReferenceInputData(boolean includeReferenceInputData) { this.includeReferenceInputData = includeReferenceInputData; } - + /** - * @see iaik.server.modules.xmlverify.XMLSignatureVerificationProfile#getPermitFileURIs() + * @see iaik.server.modules.xmlverify.XMLSignatureVerificationProfile#getPermitFileURIs() */ + @Override public boolean getPermitFileURIs() { return permitFileURIs; } - + /** * Set whether the file URIs are permitted or not - * + * * @param permitFileURIs whether the file URIs are permitted or not */ - public void setPermitFileURIs(boolean permitFileURIs) - { + public void setPermitFileURIs(boolean permitFileURIs) { this.permitFileURIs = permitFileURIs; } @Override public String getTargetLevel() { - return XMLSignatureVerificationProfile.LEVEL_LTA; + return SignatureVerificationProfile.LEVEL_LTA; } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/init/ConfiguratorImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/init/ConfiguratorImpl.java index 32654d4..5726220 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/init/ConfiguratorImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/init/ConfiguratorImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.init; import at.gv.egovernment.moa.spss.MOAException; @@ -33,7 +32,7 @@ import iaik.server.ConfigurationData; /** * Default implementation of Configurator. - * + * * @author Patrick Peck * @version $Id$ */ @@ -42,41 +41,44 @@ public class ConfiguratorImpl extends Configurator { private boolean initialized = false; StartupConfigurationHolder result; - + + @Override public StartupConfigurationHolder getCurrentConfiguration() { - return result; - + return result; + } - + + @Override public StartupConfigurationHolder init() throws MOAException { if (!initialized) { result = SystemInitializer.init(); initialized = true; - + } - + return result; - + } + @Override public StartupConfigurationHolder update() throws MOAException { if (!initialized) { return null; } - - try { + + try { // reconfigure the system - ConfigurationProvider config = ConfigurationProvider.reload(); - ConfigurationData iaikConfig = new IaikConfigurator().configure(config); + final ConfigurationProvider config = ConfigurationProvider.reload(); + final ConfigurationData iaikConfig = new IaikConfigurator().configure(config); result = new StartupConfigurationHolder(config, iaikConfig); return result; - - } catch (MOAException e) { + + } catch (final MOAException e) { throw e; - - } catch (Throwable t) { + + } catch (final Throwable t) { throw new ConfigurationException("MOA-SPSS initialization FAILED with a generic error", null, t); - + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/init/ExternalInitializer.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/init/ExternalInitializer.java index 692ee53..73a183f 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/init/ExternalInitializer.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/init/ExternalInitializer.java @@ -3,5 +3,5 @@ package at.gv.egovernment.moa.spss.server.init; import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; public interface ExternalInitializer { - public void initialize(ConfigurationProvider configurationProvider); + void initialize(ConfigurationProvider configurationProvider); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/init/StartupConfigurationHolder.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/init/StartupConfigurationHolder.java index 229a8b2..903b08b 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/init/StartupConfigurationHolder.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/init/StartupConfigurationHolder.java @@ -4,39 +4,37 @@ import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; import iaik.server.ConfigurationData; public class StartupConfigurationHolder { - - private final ConfigurationProvider moaSpssConfig; - private final ConfigurationData iaikConfiguration; - - /** - * Holder for IAIK and MOA-SPSS related configuration object. - * - * @param config MOA-SPSS specific configuration - * @param iaikConfig Internal IAIK module configuration - */ - public StartupConfigurationHolder(ConfigurationProvider config, ConfigurationData iaikConfig) { - this.moaSpssConfig = config; - this.iaikConfiguration = iaikConfig; - } - /** - * Get MOA-SPSS configuration object from start-up process. - * - * @return MOA-SPSS configuration - */ - public ConfigurationProvider getMoaSpssConfig() { - return moaSpssConfig; - } + private final ConfigurationProvider moaSpssConfig; + private final ConfigurationData iaikConfiguration; - /** - * Get configuration object for IAIK modules from start-up process. - * - * @return IAIK module configuration - */ - public ConfigurationData getIaikConfiguration() { - return iaikConfiguration; - } - - + /** + * Holder for IAIK and MOA-SPSS related configuration object. + * + * @param config MOA-SPSS specific configuration + * @param iaikConfig Internal IAIK module configuration + */ + public StartupConfigurationHolder(ConfigurationProvider config, ConfigurationData iaikConfig) { + this.moaSpssConfig = config; + this.iaikConfiguration = iaikConfig; + } + + /** + * Get MOA-SPSS configuration object from start-up process. + * + * @return MOA-SPSS configuration + */ + public ConfigurationProvider getMoaSpssConfig() { + return moaSpssConfig; + } + + /** + * Get configuration object for IAIK modules from start-up process. + * + * @return IAIK module configuration + */ + public ConfigurationData getIaikConfiguration() { + return iaikConfiguration; + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/init/SystemInitializer.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/init/SystemInitializer.java index 25bb6d9..a1bb145 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/init/SystemInitializer.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/init/SystemInitializer.java @@ -21,13 +21,11 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.init; import java.io.IOException; import java.util.Calendar; import java.util.Date; -import java.util.GregorianCalendar; import java.util.Iterator; import java.util.ServiceLoader; import java.util.Timer; @@ -39,7 +37,6 @@ import at.gv.egovernment.moa.spss.MOAException; import at.gv.egovernment.moa.spss.api.common.TSLConfiguration; 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.iaik.config.LoggerConfigImpl; import at.gv.egovernment.moa.spss.server.service.RevocationArchiveCleaner; import at.gv.egovernment.moa.spss.tsl.TSLServiceFactory; import at.gv.egovernment.moa.spss.tsl.timer.TSLUpdaterTimerTask; @@ -56,7 +53,7 @@ import iaik.utils.RFC2253NameParser; /** * MOA SP/SS web service initialization. - * + * * @author Patrick Peck * @version $Id$ */ @@ -67,40 +64,40 @@ public class SystemInitializer { private static final String LOGGING_HIERARCHY = "moa.spss.server"; /** Whether XML schema grammars have been initialized. */ private static boolean grammarsInitialized = false; - + private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SystemInitializer.class); - private static ServiceLoader initializerServices = - ServiceLoader.load(ExternalInitializer.class); + private static ServiceLoader initializerServices = + ServiceLoader.load(ExternalInitializer.class); private static ConfigurationData iaikConfiguration; private static ConfigurationProvider config; - - + private static void runInitializer(ConfigurationProvider configurationProvider) { - Iterator initializerIterator = initializerServices.iterator(); - logger.info("Running external initializers"); - while(initializerIterator.hasNext()) { - ExternalInitializer externalInitializer = initializerIterator.next(); - externalInitializer.initialize(configurationProvider); - } + final Iterator initializerIterator = initializerServices.iterator(); + logger.info("Running external initializers"); + while (initializerIterator.hasNext()) { + final ExternalInitializer externalInitializer = initializerIterator.next(); + externalInitializer.initialize(configurationProvider); + } } - + /** * Initialize the MOA SP/SS webservice. - * @return + * + * @return */ public static StartupConfigurationHolder init() { - - logger.info("##############################################################################"); - logger.info("##############################################################################"); - logger.info("### ###"); - logger.info("### LOADING MOA-SPSS ###"); - logger.info("### ================ ###"); - logger.info("### ###"); - logger.info("##############################################################################"); - logger.info("##############################################################################"); - - MessageProvider msg = MessageProvider.getInstance(); + + logger.info("##############################################################################"); + logger.info("##############################################################################"); + logger.info("### ###"); + logger.info("### LOADING MOA-SPSS ###"); + logger.info("### ================ ###"); + logger.info("### ###"); + logger.info("##############################################################################"); + logger.info("##############################################################################"); + + final MessageProvider msg = MessageProvider.getInstance(); Thread archiveCleaner; @@ -109,96 +106,93 @@ public class SystemInitializer { // set up a logging context for logging the startup LoggingContextManager.getInstance().setLoggingContext( - new LoggingContext("startup")); - + new LoggingContext("startup")); + // AxisProperties.setProperty("enableNamespacePrefixOptimization","false"); // AxisProperties.setProperty("disablePrettyXML", "true"); // AxisProperties.setProperty("axis.doAutoTypes", "true"); - - // initialize preparsed Xerces grammar pool for faster XML + + // initialize preparsed Xerces grammar pool for faster XML // parsing/validating try { if (!grammarsInitialized) { - Class clazz = SystemInitializer.class; + final Class clazz = SystemInitializer.class; // preparse XML schema DOMUtils.addSchemaToPool( - clazz.getResourceAsStream(Constants.XML_SCHEMA_LOCATION), - Constants.XML_NS_URI); + clazz.getResourceAsStream(Constants.XML_SCHEMA_LOCATION), + Constants.XML_NS_URI); // preparse XMLDsig Filter2 schema DOMUtils.addSchemaToPool( - clazz.getResourceAsStream(Constants.DSIG_FILTER2_SCHEMA_LOCATION), - Constants.DSIG_FILTER2_NS_URI); + clazz.getResourceAsStream(Constants.DSIG_FILTER2_SCHEMA_LOCATION), + Constants.DSIG_FILTER2_NS_URI); // preparse XMLDsig schema DOMUtils.addSchemaToPool( - clazz.getResourceAsStream(Constants.DSIG_SCHEMA_LOCATION), - Constants.DSIG_NS_URI); + clazz.getResourceAsStream(Constants.DSIG_SCHEMA_LOCATION), + Constants.DSIG_NS_URI); // preparse MOA schema DOMUtils.addSchemaToPool( - clazz.getResourceAsStream(Constants.MOA_SCHEMA_LOCATION), - Constants.MOA_NS_URI); + clazz.getResourceAsStream(Constants.MOA_SCHEMA_LOCATION), + Constants.MOA_NS_URI); grammarsInitialized = true; } - } catch (IOException e) { + } catch (final IOException e) { Logger.warn(new LogMsg(msg.getMessage("init.04", null)), e); } - + // initialize configuration try { - Logger.info("Initialize MOA-SP/SS configuration ... "); - config = ConfigurationProvider.getInstance(); - - //initialize TSL module - TSLConfiguration moaSPTslConfig = config.getTSLConfiguration(); - if (moaSPTslConfig != null) { - Logger.debug("Starting TSL-Service initialization ... "); - TslConfigurationImpl tslConfig = new TslConfigurationImpl(); - tslConfig.setEuTslURL(moaSPTslConfig.getEuTSLUrl()); - tslConfig.setTslWorkingDirectory(moaSPTslConfig.getWorkingDirectory()); - tslConfig.setNetworkReadTimeout(config.getReadTimeout() / 1000); - - Logger.info(new LogMsg(msg.getMessage("config.41", null))); - TSLServiceFactory.initialize(tslConfig); - Logger.info("TSL-Service client initialization finished"); - - //initialize TSL Update Task - initTSLUpdateTask(moaSPTslConfig); - - } - - Logger.info("Register additional RFC2253 Object identifier"); - RFC2253NameParser.register( - "organizationIdentifier", - new ObjectID("2.5.4.97", "organizationIdentifier", (String) null, false)); - - - Logger.info("Building IAIK-MOA configuration ... "); - iaikConfiguration = new IaikConfigurator().configure(config); - - - runInitializer(config); - Logger.info(new LogMsg(msg.getMessage("init.01", null))); - - - } catch (MOAException e) { - Logger.fatal(new LogMsg(msg.getMessage("init.00", null)), e); - throw new RuntimeException(e); - - } catch (Throwable e) { - Logger.fatal(new LogMsg(msg.getMessage("init.00", null)), e); - throw new RuntimeException(e); - - } - + Logger.info("Initialize MOA-SP/SS configuration ... "); + config = ConfigurationProvider.getInstance(); + + // initialize TSL module + final TSLConfiguration moaSPTslConfig = config.getTSLConfiguration(); + if (moaSPTslConfig != null) { + Logger.debug("Starting TSL-Service initialization ... "); + final TslConfigurationImpl tslConfig = new TslConfigurationImpl(); + tslConfig.setEuTslURL(moaSPTslConfig.getEuTSLUrl()); + tslConfig.setTslWorkingDirectory(moaSPTslConfig.getWorkingDirectory()); + tslConfig.setNetworkReadTimeout(config.getReadTimeout() / 1000); + + Logger.info(new LogMsg(msg.getMessage("config.41", null))); + TSLServiceFactory.initialize(tslConfig); + Logger.info("TSL-Service client initialization finished"); + + // initialize TSL Update Task + initTSLUpdateTask(moaSPTslConfig); + + } + + Logger.info("Register additional RFC2253 Object identifier"); + RFC2253NameParser.register( + "organizationIdentifier", + new ObjectID("2.5.4.97", "organizationIdentifier", (String) null, false)); + + Logger.info("Building IAIK-MOA configuration ... "); + iaikConfiguration = new IaikConfigurator().configure(config); + + runInitializer(config); + Logger.info(new LogMsg(msg.getMessage("init.01", null))); + + } catch (final MOAException e) { + Logger.fatal(new LogMsg(msg.getMessage("init.00", null)), e); + throw new RuntimeException(e); + + } catch (final Throwable e) { + Logger.fatal(new LogMsg(msg.getMessage("init.00", null)), e); + throw new RuntimeException(e); + + } + // CHANGE IXSIL to XSECT // set IXSIL debug output - //IXSILInit.setPrintDebugLog( - // Logger.isDebugEnabled(IaikLog.IAIK_LOG_HIERARCHY)); - //Logger.info("Registering XSECT"); - //XSecProvider.addAsProvider(true); - + // IXSILInit.setPrintDebugLog( + // Logger.isDebugEnabled(IaikLog.IAIK_LOG_HIERARCHY)); + // Logger.info("Registering XSECT"); + // XSecProvider.addAsProvider(true); + // start the archive cleanup thread archiveCleaner = - new Thread(new RevocationArchiveCleaner(ARCHIVE_CLEANUP_INTERVAL)); + new Thread(new RevocationArchiveCleaner(ARCHIVE_CLEANUP_INTERVAL)); archiveCleaner.setName("RevocationArchiveCleaner"); archiveCleaner.setDaemon(true); archiveCleaner.setPriority(Thread.MIN_PRIORITY); @@ -209,56 +203,57 @@ public class SystemInitializer { logger.info("=============================================================================="); logger.info("=== CONFIGURATION DONE ==="); logger.info("=============================================================================="); - - + return new StartupConfigurationHolder(config, iaikConfiguration); - + } - + /** * Get configuration object from IAIK modules. - * + * * @return Configuration or null of it was not configurated yet */ public static ConfigurationData getIaikConfiguration() { - return iaikConfiguration; - + return iaikConfiguration; + } - + private static void initTSLUpdateTask(TSLConfiguration tslconfig) { - MessageProvider msg = MessageProvider.getInstance(); - if (tslconfig != null) { - // get start time and period from config - long period = tslconfig.getUpdateSchedulePeriod(); - Date startConfig = tslconfig.getUpdateScheduleStartTime(); - - // get hh:mm:ss from config date - Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance - calendar.setTime(startConfig); // assigns calendar to given date - int hour = calendar.get(Calendar.HOUR_OF_DAY); - int min = calendar.get(Calendar.MINUTE); - int sec = calendar.get(Calendar.SECOND); - - // create date with today and time from config - Calendar cal = Calendar.getInstance(); - Date now = cal.getTime(); - cal.set(Calendar.HOUR_OF_DAY, hour); - cal.set(Calendar.MINUTE, min); - cal.set(Calendar.SECOND, sec); - - // proposed start time - Date start = cal.getTime(); - - // if start time has already passed today - add one day (86400000 milliseconds = 1 day) - if (start.before(now)) - start = new Date(start.getTime() + 86400000); - - Logger.debug(new LogMsg(msg.getMessage("config.46", new String[]{start.toString(), "" + period}))); - - // start TSL updater task - Timer timer = new Timer("TSL_DB_Updater"); - timer.schedule(new TSLUpdaterTimerTask(), start, period); + final MessageProvider msg = MessageProvider.getInstance(); + if (tslconfig != null) { + // get start time and period from config + final long period = tslconfig.getUpdateSchedulePeriod(); + final Date startConfig = tslconfig.getUpdateScheduleStartTime(); + + // get hh:mm:ss from config date + final Calendar calendar = Calendar.getInstance(); // creates a new calendar instance + calendar.setTime(startConfig); // assigns calendar to given date + final int hour = calendar.get(Calendar.HOUR_OF_DAY); + final int min = calendar.get(Calendar.MINUTE); + final int sec = calendar.get(Calendar.SECOND); + + // create date with today and time from config + final Calendar cal = Calendar.getInstance(); + final Date now = cal.getTime(); + cal.set(Calendar.HOUR_OF_DAY, hour); + cal.set(Calendar.MINUTE, min); + cal.set(Calendar.SECOND, sec); + + // proposed start time + Date start = cal.getTime(); + + // if start time has already passed today - add one day (86400000 milliseconds = + // 1 day) + if (start.before(now)) { + start = new Date(start.getTime() + 86400000); } + + Logger.debug(new LogMsg(msg.getMessage("config.46", new String[] { start.toString(), "" + period }))); + + // start TSL updater task + final Timer timer = new Timer("TSL_DB_Updater"); + timer.schedule(new TSLUpdaterTimerTask(), start, period); + } } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/CMSSignatureCreationInvoker.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/CMSSignatureCreationInvoker.java index 4050ebc..2e7445e 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/CMSSignatureCreationInvoker.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/CMSSignatureCreationInvoker.java @@ -21,19 +21,8 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.invoke; -import iaik.server.modules.algorithms.HashAlgorithms; -import iaik.server.modules.cmssign.CMSSignature; -import iaik.server.modules.cmssign.CMSSignatureCreationException; -import iaik.server.modules.cmssign.CMSSignatureCreationModule; -import iaik.server.modules.cmssign.CMSSignatureCreationModuleFactory; -import iaik.server.modules.cmssign.CMSSignatureCreationProfile; -import iaik.server.modules.keys.KeyEntryID; -import iaik.server.modules.keys.KeyModule; -import iaik.server.modules.keys.KeyModuleFactory; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; @@ -76,38 +65,46 @@ import at.gv.egovernment.moa.spss.util.MessageProvider; import at.gv.egovernment.moaspss.logging.LogMsg; import at.gv.egovernment.moaspss.logging.Logger; import at.gv.egovernment.moaspss.util.Constants; +import iaik.server.modules.algorithms.HashAlgorithms; +import iaik.server.modules.cmssign.CMSSignature; +import iaik.server.modules.cmssign.CMSSignatureCreationException; +import iaik.server.modules.cmssign.CMSSignatureCreationModule; +import iaik.server.modules.cmssign.CMSSignatureCreationModuleFactory; +import iaik.server.modules.cmssign.CMSSignatureCreationProfile; +import iaik.server.modules.keys.KeyEntryID; +import iaik.server.modules.keys.KeyModule; +import iaik.server.modules.keys.KeyModuleFactory; /** * A class providing an API based interface to the * CMSSignatureCreationModule. - * - * This class performs the invocation of the + * + * This class performs the invocation of the * iaik.server.modules.cmssign.CMSSignatureCreationModule from a * CreateCMSSignatureRequest given as an API object. The result of * the invocation is integrated into a CreateCMSSignatureResponse * and returned. - * + * * @version $Id$ */ public class CMSSignatureCreationInvoker { - - private static Map HASH_ALGORITHM_MAPPING; - - static { - HASH_ALGORITHM_MAPPING = new HashMap(); - HASH_ALGORITHM_MAPPING.put(Constants.SHA1_URI, HashAlgorithms.SHA1); - HASH_ALGORITHM_MAPPING.put(Constants.SHA256_URI, HashAlgorithms.SHA256); - HASH_ALGORITHM_MAPPING.put(Constants.SHA384_URI, HashAlgorithms.SHA384); - HASH_ALGORITHM_MAPPING.put(Constants.SHA512_URI, HashAlgorithms.SHA512); - } - + + private static Map HASH_ALGORITHM_MAPPING; + + static { + HASH_ALGORITHM_MAPPING = new HashMap(); + HASH_ALGORITHM_MAPPING.put(Constants.SHA1_URI, HashAlgorithms.SHA1); + HASH_ALGORITHM_MAPPING.put(Constants.SHA256_URI, HashAlgorithms.SHA256); + HASH_ALGORITHM_MAPPING.put(Constants.SHA384_URI, HashAlgorithms.SHA384); + HASH_ALGORITHM_MAPPING.put(Constants.SHA512_URI, HashAlgorithms.SHA512); + } /** The single instance of this class. */ private static CMSSignatureCreationInvoker instance = null; /** * Get the only instance of this class. - * + * * @return The only instance of this class. */ public static synchronized CMSSignatureCreationInvoker getInstance() { @@ -119,273 +116,271 @@ public class CMSSignatureCreationInvoker { /** * Create a new CMSSignatureCreationInvoker. - * + * * Protected to disallow multiple instances. */ protected CMSSignatureCreationInvoker() { } - - /** * Process the CreateCMSSignatureRequest message and invoke the * XMLSignatureCreationModule for every * SingleSignatureInfo contained in the request. - * + * * @param request A CreateCMSSignatureRequest API object * containing the information for creating the signature(s). - * @param reserved A Set of reserved object IDs. - * - * @return A CreateCMSSignatureResponse API object containing - * the created signature(s). The response contains either a - * SignatureEnvironment or a ErrorResponse - * for each SingleSignatureInfo in the request. - * @throws MOAException An error occurred during signature creation. + * @param reserved A Set of reserved object IDs. + * + * @return A CreateCMSSignatureResponse API object containing the + * created signature(s). The response contains either a + * SignatureEnvironment or a ErrorResponse for + * each SingleSignatureInfo in the request. + * @throws MOAException An error occurred during signature creation. */ public CreateCMSSignatureResponse createCMSSignature( - CreateCMSSignatureRequest request, - Set reserved) - throws MOAException { + CreateCMSSignatureRequest request, + Set reserved) + throws MOAException { + + final TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); + // LoggingContext loggingCtx = + // LoggingContextManager.getInstance().getLoggingContext(); - TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); - //LoggingContext loggingCtx = LoggingContextManager.getInstance().getLoggingContext(); + final CreateCMSSignatureResponseBuilder responseBuilder = new CreateCMSSignatureResponseBuilder(); + final CreateCMSSignatureResponse response = new CreateCMSSignatureResponseImpl(); - CreateCMSSignatureResponseBuilder responseBuilder = new CreateCMSSignatureResponseBuilder(); - CreateCMSSignatureResponse response = new CreateCMSSignatureResponseImpl(); + boolean isSecurityLayerConform = false; + boolean isPAdESConformRequired = false; + String structure = null; + String mimetype = null; - boolean isSecurityLayerConform = false; - boolean isPAdESConformRequired = false; - String structure = null; - String mimetype = null; - - // select the SingleSignatureInfo elements - Iterator singleSignatureInfoIter = request.getSingleSignatureInfos().iterator(); + // select the SingleSignatureInfo elements + final Iterator singleSignatureInfoIter = request.getSingleSignatureInfos().iterator(); // iterate over all the SingleSignatureInfo elements in the request - while (singleSignatureInfoIter.hasNext()) { - SingleSignatureInfo singleSignatureInfo = (SingleSignatureInfo) singleSignatureInfoIter.next(); - isSecurityLayerConform = singleSignatureInfo.isSecurityLayerConform(); - isPAdESConformRequired = singleSignatureInfo.isPAdESConform(); - - //PAdES conformity always requires SecurityLayer conformity, because certificates must be included - if (isPAdESConformRequired && !isSecurityLayerConform) { - isSecurityLayerConform = isPAdESConformRequired; - Logger.debug("Set SecurityLayerConformity to 'true' because PAdES conformity is requested"); - - } - - - DataObjectInfo dataObjectInfo = singleSignatureInfo.getDataObjectInfo(); - structure = dataObjectInfo.getStructure(); - - CMSDataObject dataobject = dataObjectInfo.getDataObject(); - MetaInfo metainfo = dataobject.getMetaInfo(); - - /*TODO: do not set SigningTime in IAIK-MOA request or any other - * API method/parameter when IAIK-MOA API is updated. - * Maybe also update mimetype solution below - */ - //does not set mimetype if PAdES conformity is requested - if (!isPAdESConformRequired) { - mimetype = metainfo.getMimeType(); - - } else - Logger.debug("PAdES conformity requested. Does not set mimetype into CAdES signature"); - - CMSContent content = dataobject.getContent(); - InputStream contentIs = null; - // build the content data - switch (content.getContentType()) { - case CMSContent.EXPLICIT_CONTENT : - contentIs = ((CMSContentExcplicit) content).getBinaryContent(); - break; - case CMSContent.REFERENCE_CONTENT : - String reference = ((CMSContentReference) content).getReference(); - if (!"".equals(reference)) { - ExternalURIResolver resolver = new ExternalURIResolver(); - contentIs = resolver.resolve(reference); - } else { - throw new MOAApplicationException("2301", null); - } - break; - default : { - throw new MOAApplicationException("2301", null); - } - } - - // create CMSSignatureCreationModuleFactory - CMSSignatureCreationModule module = CMSSignatureCreationModuleFactory.getInstance(); - - List signedProperties = null; - boolean includeData = true; - if (structure.compareTo("enveloping") == 0) - includeData = true; - if (structure.compareTo("detached") == 0) - includeData = false; - - ConfigurationProvider config = context.getConfiguration(); - - // get the key group id - String keyGroupID = request.getKeyIdentifier(); - // set the key set - Set keySet = buildKeySet(keyGroupID); - if (keySet == null) { - throw new MOAApplicationException("2231", null); - } else if (keySet.size() == 0) { - throw new MOAApplicationException("2232", null); - } - - // get digest algorithm - String digestAlgorithm = getDigestAlgorithm(config, keyGroupID); - - // create CMSSignatureCreation profile: - CMSSignatureCreationProfile profile = new CMSSignatureCreationProfileImpl( - keySet, - digestAlgorithm, - signedProperties, - isSecurityLayerConform, - includeData, - mimetype, - isPAdESConformRequired); - - // create CMSSignature from the CMSSignatureCreationModule - // build the additionalSignedProperties - List additionalSignedProperties = buildAdditionalSignedProperties(); - TransactionId tid = new TransactionId(context.getTransactionID()); - try { - CMSSignature signature = module.createSignature(profile, additionalSignedProperties, tid); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - // get CMS SignedData output stream from the CMSSignature and wrap it around out - boolean base64 = true; - OutputStream signedDataStream = signature.getSignature(out, base64); - - // now write the data to be signed to the signedDataStream - // Stream based, this should have a better performance - FilteredOutputStream filteredOuputStream = new FilteredOutputStream( - signedDataStream, 4096, dataobject.getExcludeByteRangeFrom(), - dataobject.getExcludeByteRangeTo()); - - IOUtils.copyLarge(contentIs, filteredOuputStream); - filteredOuputStream.flush(); - - // finish SignedData processing by closing signedDataStream - signedDataStream.close(); - String base64value = out.toString(); - - responseBuilder.addCMSSignature(base64value); - - - } catch (CMSSignatureCreationException e) { - MOAException moaException = IaikExceptionMapper.getInstance().map(e); - - responseBuilder.addError( - moaException.getMessageId(), - moaException.getMessage()); - Logger.warn(moaException.getMessage(), e); - - } - catch (IOException e) { - throw new MOAApplicationException("2301", null, e); - } - - } - + while (singleSignatureInfoIter.hasNext()) { + final SingleSignatureInfo singleSignatureInfo = (SingleSignatureInfo) singleSignatureInfoIter.next(); + isSecurityLayerConform = singleSignatureInfo.isSecurityLayerConform(); + isPAdESConformRequired = singleSignatureInfo.isPAdESConform(); + + // PAdES conformity always requires SecurityLayer conformity, because + // certificates must be included + if (isPAdESConformRequired && !isSecurityLayerConform) { + isSecurityLayerConform = isPAdESConformRequired; + Logger.debug("Set SecurityLayerConformity to 'true' because PAdES conformity is requested"); + + } + + final DataObjectInfo dataObjectInfo = singleSignatureInfo.getDataObjectInfo(); + structure = dataObjectInfo.getStructure(); + + final CMSDataObject dataobject = dataObjectInfo.getDataObject(); + final MetaInfo metainfo = dataobject.getMetaInfo(); + + /* + * TODO: do not set SigningTime in IAIK-MOA request or any other API + * method/parameter when IAIK-MOA API is updated. Maybe also update mimetype + * solution below + */ + // does not set mimetype if PAdES conformity is requested + if (!isPAdESConformRequired) { + mimetype = metainfo.getMimeType(); + + } else { + Logger.debug("PAdES conformity requested. Does not set mimetype into CAdES signature"); + } + + final CMSContent content = dataobject.getContent(); + InputStream contentIs = null; + // build the content data + switch (content.getContentType()) { + case CMSContent.EXPLICIT_CONTENT: + contentIs = ((CMSContentExcplicit) content).getBinaryContent(); + break; + case CMSContent.REFERENCE_CONTENT: + final String reference = ((CMSContentReference) content).getReference(); + if (!"".equals(reference)) { + final ExternalURIResolver resolver = new ExternalURIResolver(); + contentIs = resolver.resolve(reference); + } else { + throw new MOAApplicationException("2301", null); + } + break; + default: { + throw new MOAApplicationException("2301", null); + } + } + + // create CMSSignatureCreationModuleFactory + final CMSSignatureCreationModule module = CMSSignatureCreationModuleFactory.getInstance(); + + final List signedProperties = null; + boolean includeData = true; + if (structure.compareTo("enveloping") == 0) { + includeData = true; + } + if (structure.compareTo("detached") == 0) { + includeData = false; + } + + final ConfigurationProvider config = context.getConfiguration(); + + // get the key group id + final String keyGroupID = request.getKeyIdentifier(); + // set the key set + final Set keySet = buildKeySet(keyGroupID); + if (keySet == null) { + throw new MOAApplicationException("2231", null); + } else if (keySet.size() == 0) { + throw new MOAApplicationException("2232", null); + } + + // get digest algorithm + final String digestAlgorithm = getDigestAlgorithm(config, keyGroupID); + + // create CMSSignatureCreation profile: + final CMSSignatureCreationProfile profile = new CMSSignatureCreationProfileImpl( + keySet, + digestAlgorithm, + signedProperties, + isSecurityLayerConform, + includeData, + mimetype, + isPAdESConformRequired); + + // create CMSSignature from the CMSSignatureCreationModule + // build the additionalSignedProperties + final List additionalSignedProperties = buildAdditionalSignedProperties(); + final TransactionId tid = new TransactionId(context.getTransactionID()); + try { + final CMSSignature signature = module.createSignature(profile, additionalSignedProperties, tid); + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + // get CMS SignedData output stream from the CMSSignature and wrap it around out + final boolean base64 = true; + final OutputStream signedDataStream = signature.getSignature(out, base64); + + // now write the data to be signed to the signedDataStream + // Stream based, this should have a better performance + final FilteredOutputStream filteredOuputStream = new FilteredOutputStream( + signedDataStream, 4096, dataobject.getExcludeByteRangeFrom(), + dataobject.getExcludeByteRangeTo()); + + IOUtils.copyLarge(contentIs, filteredOuputStream); + filteredOuputStream.flush(); + + // finish SignedData processing by closing signedDataStream + signedDataStream.close(); + final String base64value = out.toString(); + + responseBuilder.addCMSSignature(base64value); + + } catch (final CMSSignatureCreationException e) { + final MOAException moaException = IaikExceptionMapper.getInstance().map(e); + + responseBuilder.addError( + moaException.getMessageId(), + moaException.getMessage()); + Logger.warn(moaException.getMessage(), e); + + } catch (final IOException e) { + throw new MOAApplicationException("2301", null, e); + } + + } return responseBuilder.getResponse(); } - + private boolean inRange(BigDecimal counter, CMSDataObject dataobject) { - BigDecimal from = dataobject.getExcludeByteRangeFrom(); - BigDecimal to = dataobject.getExcludeByteRangeTo(); - - if ( (from == null) || (to == null)) - return false; - - int compare = counter.compareTo(from); - if (compare == -1) - return false; - else { - compare = counter.compareTo(to); - if (compare == 1) - return false; - else - return true; - } - - - + final BigDecimal from = dataobject.getExcludeByteRangeFrom(); + final BigDecimal to = dataobject.getExcludeByteRangeTo(); + + if (from == null || to == null) { + return false; + } + + int compare = counter.compareTo(from); + if (compare == -1) { + return false; + } else { + compare = counter.compareTo(to); + if (compare == 1) { + return false; + } else { + return true; + } + } + } - - private String getDigestAlgorithm(ConfigurationProvider config, String keyGroupID) throws MOASystemException { - // get digest method on key group level (if configured) - String configDigestMethodKG = config.getKeyGroup(keyGroupID).getDigestMethodAlgorithm(); - // get default digest method (if configured) - String configDigestMethod = config.getDigestMethodAlgorithmName(); - - - String digestMethod = null; - if (configDigestMethodKG != null) { - // if KG specific digest method is configured - digestMethod = (String) HASH_ALGORITHM_MAPPING.get(configDigestMethodKG); - if (digestMethod == null) { - error( - "config.17", - new Object[] { configDigestMethodKG}); - throw new MOASystemException("2900", null); - } - Logger.debug("Digest algorithm: " + digestMethod + "(configured in KeyGroup)"); - } - else { - // else get default configured digest method - digestMethod = (String) HASH_ALGORITHM_MAPPING.get(configDigestMethod); - if (digestMethod == null) { - error( - "config.17", - new Object[] { configDigestMethod}); - throw new MOASystemException("2900", null); - } - Logger.debug("Digest algorithm: " + digestMethod + "(default)"); - - } - return digestMethod; + private String getDigestAlgorithm(ConfigurationProvider config, String keyGroupID) + throws MOASystemException { + // get digest method on key group level (if configured) + final String configDigestMethodKG = config.getKeyGroup(keyGroupID).getDigestMethodAlgorithm(); + // get default digest method (if configured) + final String configDigestMethod = config.getDigestMethodAlgorithmName(); + + String digestMethod = null; + if (configDigestMethodKG != null) { + // if KG specific digest method is configured + digestMethod = (String) HASH_ALGORITHM_MAPPING.get(configDigestMethodKG); + if (digestMethod == null) { + error( + "config.17", + new Object[] { configDigestMethodKG }); + throw new MOASystemException("2900", null); + } + Logger.debug("Digest algorithm: " + digestMethod + "(configured in KeyGroup)"); + } else { + // else get default configured digest method + digestMethod = (String) HASH_ALGORITHM_MAPPING.get(configDigestMethod); + if (digestMethod == null) { + error( + "config.17", + new Object[] { configDigestMethod }); + throw new MOASystemException("2900", null); + } + Logger.debug("Digest algorithm: " + digestMethod + "(default)"); + + } + return digestMethod; } - + /** * Utility function to issue an error message to the log. - * - * @param messageId The ID of the message to log. + * + * @param messageId The ID of the message to log. * @param parameters Additional message parameters. */ private static void error(String messageId, Object[] parameters) { - MessageProvider msg = MessageProvider.getInstance(); + final MessageProvider msg = MessageProvider.getInstance(); Logger.error(new LogMsg(msg.getMessage(messageId, parameters))); } - + /** * Build the set of KeyEntryIDs available to the given * keyGroupID. - * + * * @param keyGroupID The keygroup ID for which the available keys should be - * returned. - * @return The Set of KeyEntryIDs - * identifying the available keys. + * returned. + * @return The Set of KeyEntryIDs identifying the + * available keys. */ private Set buildKeySet(String keyGroupID) { - TransactionContext context = - TransactionContextManager.getInstance().getTransactionContext(); - ConfigurationProvider config = context.getConfiguration(); + final TransactionContext context = + TransactionContextManager.getInstance().getTransactionContext(); + final ConfigurationProvider config = context.getConfiguration(); Set keyGroupEntries; // get the KeyGroup entries from the configuration if (context.getClientCertificate() != null) { - X509Certificate cert = context.getClientCertificate()[0]; - Principal issuer = cert.getIssuerDN(); - BigInteger serialNumber = cert.getSerialNumber(); + final X509Certificate cert = context.getClientCertificate()[0]; + final Principal issuer = cert.getIssuerDN(); + final BigInteger serialNumber = cert.getSerialNumber(); keyGroupEntries = - config.getKeyGroupEntries(issuer, serialNumber, keyGroupID); + config.getKeyGroupEntries(issuer, serialNumber, keyGroupID); } else { keyGroupEntries = config.getKeyGroupEntries(null, null, keyGroupID); } @@ -396,23 +391,23 @@ public class CMSSignatureCreationInvoker { } else if (keyGroupEntries.size() == 0) { return Collections.EMPTY_SET; } else { - KeyModule module = - KeyModuleFactory.getInstance( - new TransactionId(context.getTransactionID())); - Set keyEntryIDs = module.getPrivateKeyEntryIDs(); - Set keySet = new HashSet(); + final KeyModule module = + KeyModuleFactory.getInstance( + new TransactionId(context.getTransactionID())); + final Set keyEntryIDs = module.getPrivateKeyEntryIDs(); + final Set keySet = new HashSet(); Iterator iter; // filter out the keys that do not exist in the IAIK configuration // by walking through the key entries and checking if the exist in the // keyGroupEntries for (iter = keyEntryIDs.iterator(); iter.hasNext();) { - KeyEntryID entryID = (KeyEntryID) iter.next(); - KeyGroupEntry entry = - new KeyGroupEntry( - entryID.getModuleID(), - entryID.getCertificateIssuer(), - entryID.getCertificateSerialNumber()); + final KeyEntryID entryID = (KeyEntryID) iter.next(); + final KeyGroupEntry entry = + new KeyGroupEntry( + entryID.getModuleID(), + entryID.getCertificateIssuer(), + entryID.getCertificateSerialNumber()); if (keyGroupEntries.contains(entry)) { keySet.add(entryID); } @@ -423,18 +418,18 @@ public class CMSSignatureCreationInvoker { /** * Build the list of additional signed properties. - * + * * Based on the generic configuration setting - * ConfigurationProvider.TEST_SIGNING_TIME_PROPERTY, a - * constant SigningTime will be added to the properties. - * + * ConfigurationProvider.TEST_SIGNING_TIME_PROPERTY, a constant + * SigningTime will be added to the properties. + * * @return The List of additional signed properties. */ private List buildAdditionalSignedProperties() { - TransactionContext context = - TransactionContextManager.getInstance().getTransactionContext(); - ConfigurationProvider config = context.getConfiguration(); - List additionalSignedProperties = Collections.EMPTY_LIST; + final TransactionContext context = + TransactionContextManager.getInstance().getTransactionContext(); + final ConfigurationProvider config = context.getConfiguration(); + final List additionalSignedProperties = Collections.EMPTY_LIST; return additionalSignedProperties; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/CMSSignatureVerificationInvoker.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/CMSSignatureVerificationInvoker.java index 74fa9ab..e18f957 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/CMSSignatureVerificationInvoker.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/CMSSignatureVerificationInvoker.java @@ -28,7 +28,6 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; -import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; @@ -55,12 +54,8 @@ import at.gv.egovernment.moa.spss.util.QCSSCDResult; import at.gv.egovernment.moaspss.logging.Logger; import at.gv.egovernment.moaspss.logging.LoggingContext; import at.gv.egovernment.moaspss.logging.LoggingContextManager; -import iaik.server.ConfigurationException; -import iaik.server.modules.AdESConstants; -import iaik.server.modules.AdESFormVerificationResult; import iaik.server.modules.IAIKException; import iaik.server.modules.IAIKRuntimeException; -import iaik.server.modules.SignatureVerificationProfile; import iaik.server.modules.cmsverify.CMSSignatureVerificationModule; import iaik.server.modules.cmsverify.CMSSignatureVerificationModuleFactory; import iaik.server.modules.cmsverify.CMSSignatureVerificationProfile; @@ -75,449 +70,459 @@ import iaik.x509.X509Certificate; /** * A class providing an interface to the * CMSSignatureVerificationModule. - * + * * This class performs the invocation of the * iaik.server.modules.cmsverify.CMSSignatureVerificationModule * from a VerifyCMSSignatureRequest. The result of the invocation * is integrated into a VerifyCMSSignatureResponse returned. - * + * * @author Patrick Peck * @version $Id$ */ public class CMSSignatureVerificationInvoker { - /** The single instance of this class. */ - private static CMSSignatureVerificationInvoker instance = null; - - /** - * Return the only instance of this class. - * - * @return The only instance of this class. - */ - public static synchronized CMSSignatureVerificationInvoker getInstance() { - if (instance == null) { - instance = new CMSSignatureVerificationInvoker(); - } - return instance; - } - - /** - * Create a new CMSSignatureVerificationInvoker. - * - * Protected to disallow multiple instances. - */ - protected CMSSignatureVerificationInvoker() { - } - - /** - * Verify a CMS signature. - * - * @param request - * The VerifyCMSSignatureRequest containing the CMS - * signature, as well as additional data needed for verification. - * @return Element A VerifyCMSSignatureResponse containing the - * answer to the VerifyCMSSignatureRequest. - * @throws MOAException - * An error occurred while processing the request. - */ - public VerifyCMSSignatureResponse verifyCMSSignature(VerifyCMSSignatureRequest request) throws MOAException { - - CMSSignatureVerificationProfileFactory profileFactory = new CMSSignatureVerificationProfileFactory(request); - VerifyCMSSignatureResponseBuilder responseBuilder = new VerifyCMSSignatureResponseBuilder(); - TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); - LoggingContext loggingCtx = LoggingContextManager.getInstance().getLoggingContext(); - InputStream signature; - InputStream signedContent = null; - Date signingTime; - List results; - int[] signatories; - InputStream input; - byte[] buf = new byte[2048]; - - // get the signature - signature = request.getCMSSignature(); - - // get the actual trustprofile - TrustProfile trustProfile = context.getConfiguration().getTrustProfile(request.getTrustProfileId()); - - try { - // get the signing time - signingTime = request.getDateTime(); - - // build the profile - if (request.isPDF()) { - PDFSignatureVerificationProfile profile = profileFactory.createPDFProfile(); - Logger.debug("Sending PDFSignatureVerificationProfile to IAIK-MOA"); - - PDFSignatureVerificationModule module = iaik.server.modules.pdfverify.PDFSignatureVerificationModuleFactory - .getInstance(); - - module.setLog(new IaikLog(loggingCtx.getNodeID())); - //Logger.info(" Available: " + signature.available()); - module.init(signature, profile, new TransactionId(context.getTransactionID())); - - // input = module.getInputStream(); - - // while (input.read(buf) > 0); - if(request.isExtended()) { - Logger.info("Running extended validation"); - results = module.verifyPAdESSignature(signingTime); - } else { - Logger.info("Running not extended validation"); - results = module.verifySignature(signingTime); - } - - //PAdES module had to be closed manually - module.closeModule(); - - } else { - // get the signed content - signedContent = getSignedContent(request); - CMSSignatureVerificationProfile profile = profileFactory.createProfile(); - Logger.debug("Sending CMSSignatureVerificationProfile to IAIK-MOA"); - - // verify the signature - CMSSignatureVerificationModule module = CMSSignatureVerificationModuleFactory.getInstance(); - - module.setLog(new IaikLog(loggingCtx.getNodeID())); - - module.init(signature, signedContent, profile, new TransactionId(context.getTransactionID())); - input = module.getInputStream(); - - while (input.read(buf) > 0) - ; - - if(request.isExtended()) { - Logger.info("Running extended validation"); - results = module.verifyCAdESSignature(signingTime); - } else { - Logger.info("Running not extended validation"); - results = module.verifySignature(signingTime); - } - // results = module.verifySignature(signingTime); - } - - } catch (IAIKException e) { - MOAException moaException = IaikExceptionMapper.getInstance().map(e); - throw moaException; - } catch (IAIKRuntimeException e) { - MOAException moaException = IaikExceptionMapper.getInstance().map(e); - throw moaException; - } catch (IOException e) { - throw new MOAApplicationException("2244", null, e); - } catch (MOAException e) { - throw e; - } finally { - try { - if (signedContent != null) - signedContent.close(); - - if (signature != null) - signature.close(); - - } catch (Throwable t) { - // Intentionally do nothing here - } - } - - QCSSCDResult qcsscdresult = new QCSSCDResult(); - - // build the response: for each signatory add the result to the response - signatories = request.getSignatories(); - if (signatories == VerifyCMSSignatureRequest.ALL_SIGNATORIES) { - Iterator resultIter; - - for (resultIter = results.iterator(); resultIter.hasNext();) { - Object resultObject = resultIter.next(); - if (!request.isPDF()) { - handleCMSResult(resultObject, responseBuilder, trustProfile); - } else { - handlePDFResult(resultObject, responseBuilder, trustProfile); - } - } - } else { - int i; - - for (i = 0; i < signatories.length; i++) { - int sigIndex = signatories[i] - 1; - - try { - Object resultObject = results.get(signatories[i] - 1); - if (!request.isPDF()) { - handleCMSResult(resultObject, responseBuilder, trustProfile); - } else { - handlePDFResult(resultObject, responseBuilder, trustProfile); - } - } catch (IndexOutOfBoundsException e) { - throw new MOAApplicationException("2249", new Object[] { new Integer(sigIndex) }); - } - } - } - - return responseBuilder.getResponse(); - } - - private void handleCMSResult(Object resultObject, VerifyCMSSignatureResponseBuilder responseBuilder, - TrustProfile trustProfile) throws MOAException { - QCSSCDResult qcsscdresult = new QCSSCDResult(); - - if(resultObject == null) { - Logger.warn("Result Object is null!"); - return; - } - - CMSSignatureVerificationResult cmsResult = null; - List adesResults = null; - boolean extendedVerification = false; - - ExtendedCertificateCheckResult extCheckResult = null; - if (resultObject instanceof ExtendedCMSSignatureVerificationResult) { - Logger.info("Got ExtendedCMSSignatureVerificationResult"); - extendedVerification = true; - ExtendedCMSSignatureVerificationResult result = (ExtendedCMSSignatureVerificationResult) resultObject; - cmsResult = result.getCMSSignatureVerificationResult(); - adesResults = AdESResultUtils.getAdESResult(result.getFormVerificationResult()); - - - if (Logger.isDebugEnabled() && adesResults != null) { - Iterator adesIterator = adesResults.iterator(); - while (adesIterator.hasNext()) - Logger.debug("ADES Formresults: " + adesIterator.next().toString()); - - } - - try { - //Logger.info("Extended Validation Report: " + result.getName()); - Logger.debug("Extended Validation Code: " + result.getResultCode().toString()); - Logger.debug("Extended Validation Info: " + result.getInfo()); - - extCheckResult = AdESResultUtils.getExtendedResult(result.getResultCode()); - - } catch (NullPointerException e) { - Logger.info("No extendend validation result available."); - - } - } else { - Logger.debug("Got CMSSignatureVerificationResult"); - cmsResult = (CMSSignatureVerificationResult) resultObject; - - } - - String issuerCountryCode = null; - // QC/SSCD check - - if(cmsResult.getCertificateValidationResult() != null) { - List list = cmsResult.getCertificateValidationResult().getCertificateChain(); - if (list != null) { - X509Certificate[] chain = new X509Certificate[list.size()]; - - Iterator it = list.iterator(); - int i = 0; - while (it.hasNext()) { - chain[i] = (X509Certificate) it.next(); - i++; - } - - qcsscdresult = CertificateUtils.checkQCSSCD(chain, cmsResult.getSigningTime(), trustProfile.isTSLEnabled(), ConfigurationProvider.getInstance()); - - // get signer certificate issuer country code - issuerCountryCode = CertificateUtils.getIssuerCountry((X509Certificate) list.get(0)); - } - } - - responseBuilder.addResult(cmsResult, trustProfile, qcsscdresult.isQC(), qcsscdresult.isQCSourceTSL(), - qcsscdresult.isSSCD(), qcsscdresult.isSSCDSourceTSL(), issuerCountryCode, adesResults, extCheckResult, - qcsscdresult.getTslInfos(), extendedVerification); - } - - private void handlePDFResult(Object resultObject, VerifyCMSSignatureResponseBuilder responseBuilder, - TrustProfile trustProfile) throws MOAException { - QCSSCDResult qcsscdresult = new QCSSCDResult(); - - if(resultObject == null) { - Logger.warn("Result Object is null!"); - return; - } - - PDFSignatureVerificationResult cmsResult = null; - List adesResults = null; - boolean extendedVerification = false; - Boolean coversFullDoc = null; - int[] sigByteRange = null; - - ExtendedCertificateCheckResult extCheckResult = null; - if (resultObject instanceof ExtendedPDFSignatureVerificationResult) { - Logger.info("Got ExtendedPDFSignatureVerificationResult"); - extendedVerification = true; - ExtendedPDFSignatureVerificationResult result = (ExtendedPDFSignatureVerificationResult) resultObject; - cmsResult = result.getPDFSignatureVerificationResult(); - adesResults = AdESResultUtils.getAdESResult(result.getFormVerificationResult()); - - if (Logger.isDebugEnabled() && adesResults != null) { - Iterator adesIterator = adesResults.iterator(); - while (adesIterator.hasNext()) - Logger.debug("ADES Formresults: " + adesIterator.next().toString()); - - } - - - try { - Logger.debug("Extended Validation Code: " + result.getResultCode().toString()); - - if (result.getDetailedExtendedReport() != null) - Logger.debug("Extended Validation Info: " + result.getDetailedExtendedReport().getMessage()); - else - Logger.debug("Extended Validation Info: " + result.getInfo()); - - - Logger.debug("Full extended Validation Infos: " + result.getInfo()); - extCheckResult = AdESResultUtils.getExtendedResult(result.getResultCode()); - - } catch (NullPointerException e) { - Logger.info("No extendend validation result available."); - - } - - } else { - Logger.debug("Got PDFSignatureVerificationResult"); - cmsResult = (PDFSignatureVerificationResult) resultObject; - } - - if (MiscUtil.isNotEmpty(cmsResult.getError())) - Logger.info("Signature validation stopped with an error: " + cmsResult.getError()); - - String issuerCountryCode = null; - // QC/SSCD check - - if (cmsResult.getCertificateValidationResult() != null) { - List list = cmsResult.getCertificateValidationResult().getCertificateChain(); - if (list != null) { - X509Certificate[] chain = new X509Certificate[list.size()]; - - Iterator it = list.iterator(); - int i = 0; - while (it.hasNext()) { - chain[i] = (X509Certificate) it.next(); - i++; - } - - qcsscdresult = CertificateUtils.checkQCSSCD(chain, cmsResult.getSigningTime(), trustProfile.isTSLEnabled(), ConfigurationProvider.getInstance()); - - // get signer certificate issuer country code - issuerCountryCode = CertificateUtils.getIssuerCountry((X509Certificate) list.get(0)); - - } - } - - responseBuilder.addResult(cmsResult, trustProfile, qcsscdresult.isQC(), qcsscdresult.isQCSourceTSL(), - qcsscdresult.isSSCD(), qcsscdresult.isSSCDSourceTSL(), issuerCountryCode, adesResults, - extCheckResult, qcsscdresult.getTslInfos(), extendedVerification); - } - - /** - * Get the signed content contained either in the request itself or given as - * a reference to external data. - * - * @param request - * The VerifyCMSSignatureRequest containing the - * signed content (or the reference to the signed content). - * @return InputStream A stream providing the signed content data, or - * null if no signed content was provided with the - * request. - * @throws MOAApplicationException - * An error occurred building the stream. - */ - private InputStream getSignedContent(VerifyCMSSignatureRequest request) throws MOAApplicationException { - - InputStream is = null; - CMSDataObject dataObj; - CMSContent content; - - // select the Content element - dataObj = request.getDataObject(); - if (dataObj == null) { - return null; - } - content = dataObj.getContent(); - - // build the content data - switch (content.getContentType()) { - case CMSContent.EXPLICIT_CONTENT: - is = ((CMSContentExcplicit) content).getBinaryContent(); - is = excludeByteRange(is, request); - return is; - case CMSContent.REFERENCE_CONTENT: - String reference = ((CMSContentReference) content).getReference(); - if (!"".equals(reference)) { - ExternalURIResolver resolver = new ExternalURIResolver(); - is = resolver.resolve(reference); - is = excludeByteRange(is, request); - return is; - } else { - return null; - } - default: - return null; - } - - } - - private InputStream excludeByteRange(InputStream contentIs, VerifyCMSSignatureRequest request) - throws MOAApplicationException { - - int byteRead; - - ByteArrayOutputStream contentOs = new ByteArrayOutputStream(); - - CMSDataObject dataobject = request.getDataObject(); - BigDecimal from = dataobject.getExcludeByteRangeFrom(); - BigDecimal to = dataobject.getExcludeByteRangeTo(); - - if ((from == null) || (to == null)) - return contentIs; - - BigDecimal counter = new BigDecimal("0"); - BigDecimal one = new BigDecimal("1"); - - try { - while ((byteRead = contentIs.read()) >= 0) { - - if (inRange(counter, dataobject)) { - // if byte is in byte range, set byte to 0x00 - contentOs.write(0); - } else - contentOs.write(byteRead); - - counter = counter.add(one); - } - - InputStream is = new ByteArrayInputStream(contentOs.toByteArray()); - - return is; - - } catch (IOException e) { - throw new MOAApplicationException("2301", null, e); - } - - } - - private boolean inRange(BigDecimal counter, CMSDataObject dataobject) { - BigDecimal from = dataobject.getExcludeByteRangeFrom(); - BigDecimal to = dataobject.getExcludeByteRangeTo(); - - if ((from == null) || (to == null)) - return false; - - int compare = counter.compareTo(from); - if (compare == -1) - return false; - else { - compare = counter.compareTo(to); - if (compare == 1) - return false; - else - return true; - } - - } + /** The single instance of this class. */ + private static CMSSignatureVerificationInvoker instance = null; + + /** + * Return the only instance of this class. + * + * @return The only instance of this class. + */ + public static synchronized CMSSignatureVerificationInvoker getInstance() { + if (instance == null) { + instance = new CMSSignatureVerificationInvoker(); + } + return instance; + } + + /** + * Create a new CMSSignatureVerificationInvoker. + * + * Protected to disallow multiple instances. + */ + protected CMSSignatureVerificationInvoker() { + } + + /** + * Verify a CMS signature. + * + * @param request The VerifyCMSSignatureRequest containing the CMS + * signature, as well as additional data needed for verification. + * @return Element A VerifyCMSSignatureResponse containing the + * answer to the VerifyCMSSignatureRequest. + * @throws MOAException An error occurred while processing the request. + */ + public VerifyCMSSignatureResponse verifyCMSSignature(VerifyCMSSignatureRequest request) + throws MOAException { + + final CMSSignatureVerificationProfileFactory profileFactory = new CMSSignatureVerificationProfileFactory( + request); + final VerifyCMSSignatureResponseBuilder responseBuilder = new VerifyCMSSignatureResponseBuilder(); + final TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); + final LoggingContext loggingCtx = LoggingContextManager.getInstance().getLoggingContext(); + InputStream signature; + InputStream signedContent = null; + Date signingTime; + List results; + int[] signatories; + InputStream input; + final byte[] buf = new byte[2048]; + + // get the signature + signature = request.getCMSSignature(); + + // get the actual trustprofile + final TrustProfile trustProfile = context.getConfiguration().getTrustProfile(request.getTrustProfileId()); + + try { + // get the signing time + signingTime = request.getDateTime(); + + // build the profile + if (request.isPDF()) { + final PDFSignatureVerificationProfile profile = profileFactory.createPDFProfile(); + Logger.debug("Sending PDFSignatureVerificationProfile to IAIK-MOA"); + + final PDFSignatureVerificationModule module = + iaik.server.modules.pdfverify.PDFSignatureVerificationModuleFactory + .getInstance(); + + module.setLog(new IaikLog(loggingCtx.getNodeID())); + // Logger.info(" Available: " + signature.available()); + module.init(signature, profile, new TransactionId(context.getTransactionID())); + + // input = module.getInputStream(); + + // while (input.read(buf) > 0); + if (request.isExtended()) { + Logger.info("Running extended validation"); + results = module.verifyPAdESSignature(signingTime); + } else { + Logger.info("Running not extended validation"); + results = module.verifySignature(signingTime); + } + + // PAdES module had to be closed manually + module.closeModule(); + + } else { + // get the signed content + signedContent = getSignedContent(request); + final CMSSignatureVerificationProfile profile = profileFactory.createProfile(); + Logger.debug("Sending CMSSignatureVerificationProfile to IAIK-MOA"); + + // verify the signature + final CMSSignatureVerificationModule module = CMSSignatureVerificationModuleFactory.getInstance(); + + module.setLog(new IaikLog(loggingCtx.getNodeID())); + + module.init(signature, signedContent, profile, new TransactionId(context.getTransactionID())); + input = module.getInputStream(); + + while (input.read(buf) > 0) { + ; + } + + if (request.isExtended()) { + Logger.info("Running extended validation"); + results = module.verifyCAdESSignature(signingTime); + } else { + Logger.info("Running not extended validation"); + results = module.verifySignature(signingTime); + } + // results = module.verifySignature(signingTime); + } + + } catch (final IAIKException e) { + final MOAException moaException = IaikExceptionMapper.getInstance().map(e); + throw moaException; + } catch (final IAIKRuntimeException e) { + final MOAException moaException = IaikExceptionMapper.getInstance().map(e); + throw moaException; + } catch (final IOException e) { + throw new MOAApplicationException("2244", null, e); + } catch (final MOAException e) { + throw e; + } finally { + try { + if (signedContent != null) { + signedContent.close(); + } + + if (signature != null) { + signature.close(); + } + + } catch (final Throwable t) { + // Intentionally do nothing here + } + } + + final QCSSCDResult qcsscdresult = new QCSSCDResult(); + + // build the response: for each signatory add the result to the response + signatories = request.getSignatories(); + if (signatories == VerifyCMSSignatureRequest.ALL_SIGNATORIES) { + Iterator resultIter; + + for (resultIter = results.iterator(); resultIter.hasNext();) { + final Object resultObject = resultIter.next(); + if (!request.isPDF()) { + handleCMSResult(resultObject, responseBuilder, trustProfile); + } else { + handlePDFResult(resultObject, responseBuilder, trustProfile); + } + } + } else { + int i; + + for (i = 0; i < signatories.length; i++) { + final int sigIndex = signatories[i] - 1; + + try { + final Object resultObject = results.get(signatories[i] - 1); + if (!request.isPDF()) { + handleCMSResult(resultObject, responseBuilder, trustProfile); + } else { + handlePDFResult(resultObject, responseBuilder, trustProfile); + } + } catch (final IndexOutOfBoundsException e) { + throw new MOAApplicationException("2249", new Object[] { new Integer(sigIndex) }); + } + } + } + + return responseBuilder.getResponse(); + } + + private void handleCMSResult(Object resultObject, VerifyCMSSignatureResponseBuilder responseBuilder, + TrustProfile trustProfile) throws MOAException { + QCSSCDResult qcsscdresult = new QCSSCDResult(); + + if (resultObject == null) { + Logger.warn("Result Object is null!"); + return; + } + + CMSSignatureVerificationResult cmsResult = null; + List adesResults = null; + boolean extendedVerification = false; + + ExtendedCertificateCheckResult extCheckResult = null; + if (resultObject instanceof ExtendedCMSSignatureVerificationResult) { + Logger.info("Got ExtendedCMSSignatureVerificationResult"); + extendedVerification = true; + final ExtendedCMSSignatureVerificationResult result = + (ExtendedCMSSignatureVerificationResult) resultObject; + cmsResult = result.getCMSSignatureVerificationResult(); + adesResults = AdESResultUtils.getAdESResult(result.getFormVerificationResult()); + + if (Logger.isDebugEnabled() && adesResults != null) { + final Iterator adesIterator = adesResults.iterator(); + while (adesIterator.hasNext()) { + Logger.debug("ADES Formresults: " + adesIterator.next().toString()); + } + + } + + try { + // Logger.info("Extended Validation Report: " + result.getName()); + Logger.debug("Extended Validation Code: " + result.getResultCode().toString()); + Logger.debug("Extended Validation Info: " + result.getInfo()); + + extCheckResult = AdESResultUtils.getExtendedResult(result.getResultCode()); + + } catch (final NullPointerException e) { + Logger.info("No extendend validation result available."); + + } + } else { + Logger.debug("Got CMSSignatureVerificationResult"); + cmsResult = (CMSSignatureVerificationResult) resultObject; + + } + + String issuerCountryCode = null; + // QC/SSCD check + + if (cmsResult.getCertificateValidationResult() != null) { + final List list = cmsResult.getCertificateValidationResult().getCertificateChain(); + if (list != null) { + final X509Certificate[] chain = new X509Certificate[list.size()]; + + final Iterator it = list.iterator(); + int i = 0; + while (it.hasNext()) { + chain[i] = (X509Certificate) it.next(); + i++; + } + + qcsscdresult = CertificateUtils.checkQCSSCD(chain, cmsResult.getSigningTime(), trustProfile + .isTSLEnabled(), ConfigurationProvider.getInstance()); + + // get signer certificate issuer country code + issuerCountryCode = CertificateUtils.getIssuerCountry((X509Certificate) list.get(0)); + } + } + + responseBuilder.addResult(cmsResult, trustProfile, qcsscdresult.isQC(), qcsscdresult.isQCSourceTSL(), + qcsscdresult.isSSCD(), qcsscdresult.isSSCDSourceTSL(), issuerCountryCode, adesResults, extCheckResult, + qcsscdresult.getTslInfos(), extendedVerification); + } + + private void handlePDFResult(Object resultObject, VerifyCMSSignatureResponseBuilder responseBuilder, + TrustProfile trustProfile) throws MOAException { + QCSSCDResult qcsscdresult = new QCSSCDResult(); + + if (resultObject == null) { + Logger.warn("Result Object is null!"); + return; + } + + PDFSignatureVerificationResult cmsResult = null; + List adesResults = null; + boolean extendedVerification = false; + final Boolean coversFullDoc = null; + final int[] sigByteRange = null; + + ExtendedCertificateCheckResult extCheckResult = null; + if (resultObject instanceof ExtendedPDFSignatureVerificationResult) { + Logger.info("Got ExtendedPDFSignatureVerificationResult"); + extendedVerification = true; + final ExtendedPDFSignatureVerificationResult result = + (ExtendedPDFSignatureVerificationResult) resultObject; + cmsResult = result.getPDFSignatureVerificationResult(); + adesResults = AdESResultUtils.getAdESResult(result.getFormVerificationResult()); + + if (Logger.isDebugEnabled() && adesResults != null) { + final Iterator adesIterator = adesResults.iterator(); + while (adesIterator.hasNext()) { + Logger.debug("ADES Formresults: " + adesIterator.next().toString()); + } + + } + + try { + Logger.debug("Extended Validation Code: " + result.getResultCode().toString()); + + if (result.getDetailedExtendedReport() != null) { + Logger.debug("Extended Validation Info: " + result.getDetailedExtendedReport().getMessage()); + } else { + Logger.debug("Extended Validation Info: " + result.getInfo()); + } + + Logger.debug("Full extended Validation Infos: " + result.getInfo()); + extCheckResult = AdESResultUtils.getExtendedResult(result.getResultCode()); + + } catch (final NullPointerException e) { + Logger.info("No extendend validation result available."); + + } + + } else { + Logger.debug("Got PDFSignatureVerificationResult"); + cmsResult = (PDFSignatureVerificationResult) resultObject; + } + + if (MiscUtil.isNotEmpty(cmsResult.getError())) { + Logger.info("Signature validation stopped with an error: " + cmsResult.getError()); + } + + String issuerCountryCode = null; + // QC/SSCD check + + if (cmsResult.getCertificateValidationResult() != null) { + final List list = cmsResult.getCertificateValidationResult().getCertificateChain(); + if (list != null) { + final X509Certificate[] chain = new X509Certificate[list.size()]; + + final Iterator it = list.iterator(); + int i = 0; + while (it.hasNext()) { + chain[i] = (X509Certificate) it.next(); + i++; + } + + qcsscdresult = CertificateUtils.checkQCSSCD(chain, cmsResult.getSigningTime(), trustProfile + .isTSLEnabled(), ConfigurationProvider.getInstance()); + + // get signer certificate issuer country code + issuerCountryCode = CertificateUtils.getIssuerCountry((X509Certificate) list.get(0)); + + } + } + + responseBuilder.addResult(cmsResult, trustProfile, qcsscdresult.isQC(), qcsscdresult.isQCSourceTSL(), + qcsscdresult.isSSCD(), qcsscdresult.isSSCDSourceTSL(), issuerCountryCode, adesResults, + extCheckResult, qcsscdresult.getTslInfos(), extendedVerification); + } + + /** + * Get the signed content contained either in the request itself or given as a + * reference to external data. + * + * @param request The VerifyCMSSignatureRequest containing the + * signed content (or the reference to the signed content). + * @return InputStream A stream providing the signed content data, or + * null if no signed content was provided with the request. + * @throws MOAApplicationException An error occurred building the stream. + */ + private InputStream getSignedContent(VerifyCMSSignatureRequest request) throws MOAApplicationException { + + InputStream is = null; + CMSDataObject dataObj; + CMSContent content; + + // select the Content element + dataObj = request.getDataObject(); + if (dataObj == null) { + return null; + } + content = dataObj.getContent(); + + // build the content data + switch (content.getContentType()) { + case CMSContent.EXPLICIT_CONTENT: + is = ((CMSContentExcplicit) content).getBinaryContent(); + is = excludeByteRange(is, request); + return is; + case CMSContent.REFERENCE_CONTENT: + final String reference = ((CMSContentReference) content).getReference(); + if (!"".equals(reference)) { + final ExternalURIResolver resolver = new ExternalURIResolver(); + is = resolver.resolve(reference); + is = excludeByteRange(is, request); + return is; + } else { + return null; + } + default: + return null; + } + + } + + private InputStream excludeByteRange(InputStream contentIs, VerifyCMSSignatureRequest request) + throws MOAApplicationException { + + int byteRead; + + final ByteArrayOutputStream contentOs = new ByteArrayOutputStream(); + + final CMSDataObject dataobject = request.getDataObject(); + final BigDecimal from = dataobject.getExcludeByteRangeFrom(); + final BigDecimal to = dataobject.getExcludeByteRangeTo(); + + if (from == null || to == null) { + return contentIs; + } + + BigDecimal counter = new BigDecimal("0"); + final BigDecimal one = new BigDecimal("1"); + + try { + while ((byteRead = contentIs.read()) >= 0) { + + if (inRange(counter, dataobject)) { + // if byte is in byte range, set byte to 0x00 + contentOs.write(0); + } else { + contentOs.write(byteRead); + } + + counter = counter.add(one); + } + + final InputStream is = new ByteArrayInputStream(contentOs.toByteArray()); + + return is; + + } catch (final IOException e) { + throw new MOAApplicationException("2301", null, e); + } + + } + + private boolean inRange(BigDecimal counter, CMSDataObject dataobject) { + final BigDecimal from = dataobject.getExcludeByteRangeFrom(); + final BigDecimal to = dataobject.getExcludeByteRangeTo(); + + if (from == null || to == null) { + return false; + } + + int compare = counter.compareTo(from); + if (compare == -1) { + return false; + } else { + compare = counter.compareTo(to); + if (compare == 1) { + return false; + } else { + return true; + } + } + + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/CMSSignatureVerificationProfileFactory.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/CMSSignatureVerificationProfileFactory.java index bd5db6d..5e343c4 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/CMSSignatureVerificationProfileFactory.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/CMSSignatureVerificationProfileFactory.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.invoke; import at.gv.egovernment.moa.spss.MOAException; @@ -39,71 +38,71 @@ import iaik.server.modules.pdfverify.PDFSignatureVerificationProfile; * A factory to create a CMSSignatureVerificationProfile from a * VerifyCMSSignatureRequest and the current MOA configuration * data. - * + * * @author Patrick Peck * @version $Id$ */ public class CMSSignatureVerificationProfileFactory { - /** The VerifyCMSSignatureRequest to draw profile data from. */ - private VerifyCMSSignatureRequest request; + /** The VerifyCMSSignatureRequest to draw profile data from. */ + private final VerifyCMSSignatureRequest request; /** * Create a new CMSSignatureVerificationProfileFactory. * - * @param request The VerifyCMSSignatureRequest to draw profile - * data from. + * @param request The VerifyCMSSignatureRequest to draw profile + * data from. */ public CMSSignatureVerificationProfileFactory(VerifyCMSSignatureRequest request) { this.request = request; } /** - * Create a CMSSignatureVerificationProfile from the given - * request and the current MOA configuration. - * + * Create a CMSSignatureVerificationProfile from the given request + * and the current MOA configuration. + * * @return The CMSSignatureVerificationProfile for the - * request, based on the current configuration. + * request, based on the current configuration. * @throws MOAException An error occurred creating the profile. */ public PDFSignatureVerificationProfile createPDFProfile() - throws MOAException { - TransactionContext context = - TransactionContextManager.getInstance().getTransactionContext(); - ConfigurationProvider config = context.getConfiguration(); - PDFSignatureVerificationProfileImpl profile = - new PDFSignatureVerificationProfileImpl(); + throws MOAException { + final TransactionContext context = + TransactionContextManager.getInstance().getTransactionContext(); + final ConfigurationProvider config = context.getConfiguration(); + final PDFSignatureVerificationProfileImpl profile = + new PDFSignatureVerificationProfileImpl(); String trustProfileID; // set the certificate validation profile trustProfileID = request.getTrustProfileId(); profile.setCertificateValidationProfile( - new PKIProfileImpl(config, trustProfileID)); + new PKIProfileImpl(config, trustProfileID)); return profile; } - + /** - * Create a CMSSignatureVerificationProfile from the given - * request and the current MOA configuration. - * + * Create a CMSSignatureVerificationProfile from the given request + * and the current MOA configuration. + * * @return The CMSSignatureVerificationProfile for the - * request, based on the current configuration. + * request, based on the current configuration. * @throws MOAException An error occurred creating the profile. */ public CMSSignatureVerificationProfile createProfile() - throws MOAException { - TransactionContext context = - TransactionContextManager.getInstance().getTransactionContext(); - ConfigurationProvider config = context.getConfiguration(); - CMSSignatureVerificationProfileImpl profile = - new CMSSignatureVerificationProfileImpl(); + throws MOAException { + final TransactionContext context = + TransactionContextManager.getInstance().getTransactionContext(); + final ConfigurationProvider config = context.getConfiguration(); + final CMSSignatureVerificationProfileImpl profile = + new CMSSignatureVerificationProfileImpl(); String trustProfileID; // set the certificate validation profile trustProfileID = request.getTrustProfileId(); profile.setCertificateValidationProfile( - new PKIProfileImpl(config, trustProfileID)); + new PKIProfileImpl(config, trustProfileID)); return profile; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/CreateCMSSignatureResponseBuilder.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/CreateCMSSignatureResponseBuilder.java index aa52fe0..bc5d884 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/CreateCMSSignatureResponseBuilder.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/CreateCMSSignatureResponseBuilder.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.invoke; import java.util.ArrayList; @@ -34,29 +33,33 @@ import at.gv.egovernment.moa.spss.api.xmlsign.ErrorResponse; /** * A class to build a CreateCMSSignatureResponse. - * - *

The methods addSignature() and addError() may be + * + *

+ * The methods addSignature() and addError() may be * called in any combination to add CMSignature and * ErrorResponse elements to the response. One of these functions - * must be called at least once to produce a - * CreateCMSSignatureResponse.

- * - *

The getResponseElement() method then returns the - * CreateXMLSignatureResponse built so far.

- * + * must be called at least once to produce a + * CreateCMSSignatureResponse. + *

+ * + *

+ * The getResponseElement() method then returns the + * CreateXMLSignatureResponse built so far. + *

+ * * @author Patrick Peck * @version $Id$ */ public class CreateCMSSignatureResponseBuilder { /** The SPSSFactory for creating API objects. */ - private SPSSFactory factory = SPSSFactory.getInstance(); + private final SPSSFactory factory = SPSSFactory.getInstance(); /** The elements to add to the response. */ - private List responseElements = new ArrayList(); + private final List responseElements = new ArrayList(); /** * Get the CreateCMSSignatureResponse built so far. - * + * * @return The CreateCMSSignatureResponse built so far. */ public CreateCMSSignatureResponse getResponse() { @@ -65,28 +68,29 @@ public class CreateCMSSignatureResponseBuilder { /** * Add a SignatureEnvironment element to the response. - * + * * @param signatureEnvironment The content to put under the - * SignatureEnvironment element. This should either be a - * dsig:Signature element (in case of a detached signature) or - * the signature environment containing the signature (in case of - * an enveloping signature). + * SignatureEnvironment element. This + * should either be a dsig:Signature + * element (in case of a detached signature) or the + * signature environment containing the signature + * (in case of an enveloping signature). */ public void addCMSSignature(String base64value) { - CMSSignatureResponse responseElement = - factory.createCMSSignatureResponse(base64value); + final CMSSignatureResponse responseElement = + factory.createCMSSignatureResponse(base64value); responseElements.add(responseElement); } /** * Add a ErrorResponse element to the response. - * + * * @param errorCode The error code. - * @param info Additional information about the error. + * @param info Additional information about the error. */ public void addError(String errorCode, String info) { - ErrorResponse errorResponse = - factory.createErrorResponse(Integer.parseInt(errorCode), info); + final ErrorResponse errorResponse = + factory.createErrorResponse(Integer.parseInt(errorCode), info); responseElements.add(errorResponse); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/CreateXMLSignatureResponseBuilder.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/CreateXMLSignatureResponseBuilder.java index 7a7161d..0a7e70d 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/CreateXMLSignatureResponseBuilder.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/CreateXMLSignatureResponseBuilder.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.invoke; import java.util.ArrayList; @@ -36,29 +35,33 @@ import at.gv.egovernment.moa.spss.api.xmlsign.SignatureEnvironmentResponse; /** * A class to build a CreateXMLSignatureResponse. - * - *

The methods addSignature() and addError() may be + * + *

+ * The methods addSignature() and addError() may be * called in any combination to add SignatureEnvironment and * ErrorResponse elements to the response. One of these functions - * must be called at least once to produce a - * CreateXMLSignatureResponse.

- * - *

The getResponseElement() method then returns the - * CreateXMLSignatureResponse built so far.

- * + * must be called at least once to produce a + * CreateXMLSignatureResponse. + *

+ * + *

+ * The getResponseElement() method then returns the + * CreateXMLSignatureResponse built so far. + *

+ * * @author Patrick Peck * @version $Id$ */ public class CreateXMLSignatureResponseBuilder { /** The SPSSFactory for creating API objects. */ - private SPSSFactory factory = SPSSFactory.getInstance(); + private final SPSSFactory factory = SPSSFactory.getInstance(); /** The elements to add to the response. */ - private List responseElements = new ArrayList(); + private final List responseElements = new ArrayList(); /** * Get the CreateXMLSignatureResponse built so far. - * + * * @return The CreateXMLSignatureResponse built so far. */ public CreateXMLSignatureResponse getResponse() { @@ -67,28 +70,29 @@ public class CreateXMLSignatureResponseBuilder { /** * Add a SignatureEnvironment element to the response. - * + * * @param signatureEnvironment The content to put under the - * SignatureEnvironment element. This should either be a - * dsig:Signature element (in case of a detached signature) or - * the signature environment containing the signature (in case of - * an enveloping signature). + * SignatureEnvironment element. This + * should either be a dsig:Signature + * element (in case of a detached signature) or the + * signature environment containing the signature + * (in case of an enveloping signature). */ public void addSignatureEnvironment(Element signatureEnvironment) { - SignatureEnvironmentResponse responseElement = - factory.createSignatureEnvironmentResponse(signatureEnvironment); + final SignatureEnvironmentResponse responseElement = + factory.createSignatureEnvironmentResponse(signatureEnvironment); responseElements.add(responseElement); } /** * Add a ErrorResponse element to the response. - * + * * @param errorCode The error code. - * @param info Additional information about the error. + * @param info Additional information about the error. */ public void addError(String errorCode, String info) { - ErrorResponse errorResponse = - factory.createErrorResponse(Integer.parseInt(errorCode), info); + final ErrorResponse errorResponse = + factory.createErrorResponse(Integer.parseInt(errorCode), info); responseElements.add(errorResponse); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/DataObjectFactory.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/DataObjectFactory.java index 0740a73..b8d4df5 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/DataObjectFactory.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/DataObjectFactory.java @@ -21,10 +21,8 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.invoke; - import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -84,8 +82,8 @@ import iaik.server.modules.xml.XMLDataObject; import iaik.xml.crypto.utils.URIDereferencerImpl; /** - * A class to create DataObjects contained in different - * locations of the MOA XML request format. + * A class to create DataObjects contained in different locations + * of the MOA XML request format. * * @author Patrick Peck * @author Gregor Karlinger @@ -94,15 +92,15 @@ import iaik.xml.crypto.utils.URIDereferencerImpl; public class DataObjectFactory { /** - * XPATH for registering ID attributes of known schemas if - * validating parsing fails. + * XPATH for registering ID attributes of known schemas if validating parsing + * fails. */ private static final String XPATH = - "descendant-or-self::node()[" + - "namespace-uri()='http://www.w3.org/2000/09/xmldsig#' " + - "or namespace-uri()='http://reference.e-government.gv.at/namespace/persondata/20020228#' " + - "or starts-with(namespace-uri(), 'http://uri.etsi.org/01903/')" + - "]/attribute::Id"; + "descendant-or-self::node()[" + + "namespace-uri()='http://www.w3.org/2000/09/xmldsig#' " + + "or namespace-uri()='http://reference.e-government.gv.at/namespace/persondata/20020228#' " + + "or starts-with(namespace-uri(), 'http://uri.etsi.org/01903/')" + + "]/attribute::Id"; /** The single instance of this class. */ private static DataObjectFactory instance = null; @@ -128,26 +126,27 @@ public class DataObjectFactory { } /** - * Return the signature environment, i.e., the root element of the - * document, into which the signature will be inserted (if created) or which - * contains the signature (if verified). + * Return the signature environment, i.e., the root element of the document, + * into which the signature will be inserted (if created) or which contains the + * signature (if verified). * - * @param content The Content object containing the signature - * environment. + * @param content The Content object containing the signature + * environment. * @param supplements Additional schema or DTD information. - * @return The signature environment or null, if no - * signature environment exists. - * @throws MOASystemException A system error occurred building the signature - * environment (see message for details). + * @return The signature environment or null, if no signature + * environment exists. + * @throws MOASystemException A system error occurred building the + * signature environment (see message for + * details). * @throws MOAApplicationException An error occurred building the signature - * environment (see message for details). + * environment (see message for details). */ public XMLDataObject createSignatureEnvironment( - Content content, - List supplements) - throws MOASystemException, MOAApplicationException { + Content content, + List supplements) + throws MOASystemException, MOAApplicationException { - String reference = content.getReference(); + final String reference = content.getReference(); EntityResolver entityResolver; byte[] contentBytes; @@ -155,10 +154,10 @@ public class DataObjectFactory { checkAllowContentAndReference(content, false); // build the EntityResolver for validating parsing - if ((supplements == null) || supplements.isEmpty()) { + if (supplements == null || supplements.isEmpty()) { entityResolver = new MOASPSSEntityResolver(); } else { - EntityResolverChain chain = new EntityResolverChain(); + final EntityResolverChain chain = new EntityResolverChain(); chain.addEntityResolver(buildSupplementEntityResolver(supplements)); chain.addEntityResolver(new MOASPSSEntityResolver()); @@ -168,83 +167,70 @@ public class DataObjectFactory { // convert the content into a byte array try { switch (content.getContentType()) { - case Content.BINARY_CONTENT : - { - InputStream is = ((ContentBinary) content).getBinaryContent(); - contentBytes = StreamUtils.readStream(is); - break; - } - case Content.LOCREF_CONTENT: - { - String locRefURI = ((ContentLocRef) content).getLocationReferenceURI(); - InputStream is = null; - try - { - TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); - is = context.ResolveURI(locRefURI); - if (is == null) { - ExternalURIResolver uriResolver = new ExternalURIResolver(); - is = uriResolver.resolve(locRefURI); - } - contentBytes = StreamUtils.readStream(is); - } - catch (MOAApplicationException e) - { - throw new MOAApplicationException("3203", new Object[]{reference, locRefURI}, e); - } - finally - { - closeInputStream(is); + case Content.BINARY_CONTENT: { + final InputStream is = ((ContentBinary) content).getBinaryContent(); + contentBytes = StreamUtils.readStream(is); + break; + } + case Content.LOCREF_CONTENT: { + final String locRefURI = ((ContentLocRef) content).getLocationReferenceURI(); + InputStream is = null; + try { + final TransactionContext context = TransactionContextManager.getInstance() + .getTransactionContext(); + is = context.ResolveURI(locRefURI); + if (is == null) { + final ExternalURIResolver uriResolver = new ExternalURIResolver(); + is = uriResolver.resolve(locRefURI); } - break; + contentBytes = StreamUtils.readStream(is); + } catch (final MOAApplicationException e) { + throw new MOAApplicationException("3203", new Object[] { reference, locRefURI }, e); + } finally { + closeInputStream(is); } - case Content.REFERENCE_CONTENT : - { - ExternalURIResolver uriResolver = new ExternalURIResolver(); - InputStream is = null; - try - { - is = uriResolver.resolve(reference); - contentBytes = StreamUtils.readStream(is); - } - catch (Exception e) - { - throw e; - } - finally - { - closeInputStream(is); - } - break; + break; + } + case Content.REFERENCE_CONTENT: { + final ExternalURIResolver uriResolver = new ExternalURIResolver(); + InputStream is = null; + try { + is = uriResolver.resolve(reference); + contentBytes = StreamUtils.readStream(is); + } catch (final Exception e) { + throw e; + } finally { + closeInputStream(is); } - case Content.XML_CONTENT : - { - Element element = + break; + } + case Content.XML_CONTENT: { + final Element element = checkForSingleElement(((ContentXML) content).getXMLContent()); - contentBytes = DOMUtils.serializeNode(element, "UTF-8"); + contentBytes = DOMUtils.serializeNode(element, "UTF-8"); - break; - } - default : { + break; + } + default: { contentBytes = null; // this will not happen } } - } catch (MOAApplicationException e) { + } catch (final MOAApplicationException e) { throw e; - } catch (Exception e) { + } catch (final Exception e) { throw new MOAApplicationException("2219", null); } if (Logger.isTraceEnabled()) { // For logging in Debug-Mode: Mask baseid with xxx - String logString = new String(contentBytes); + final String logString = new String(contentBytes); // TODO use RegExp - String startS = ""; - String endS = "urn:publicid:gv.at:baseid"; + final String startS = ""; + final String endS = "urn:publicid:gv.at:baseid"; String logWithMaskedBaseid = logString; - int start = logString.indexOf(startS); + final int start = logString.indexOf(startS); if (start > -1) { - int end = logString.indexOf(endS); + final int end = logString.indexOf(endS); if (end > -1) { logWithMaskedBaseid = logString.substring(0, start); logWithMaskedBaseid += startS; @@ -257,37 +243,37 @@ public class DataObjectFactory { Logger.trace(">>> parsing the following content: \n" + logWithMaskedBaseid); } try { - ByteArrayInputStream is = new ByteArrayInputStream(contentBytes); - Document doc = - DOMUtils.parseDocument( - is, - true, - Constants.ALL_SCHEMA_LOCATIONS, - null, - entityResolver, - new MOAErrorHandler()); + final ByteArrayInputStream is = new ByteArrayInputStream(contentBytes); + final Document doc = + DOMUtils.parseDocument( + is, + true, + Constants.ALL_SCHEMA_LOCATIONS, + null, + entityResolver, + new MOAErrorHandler()); Logger.trace("<<< parsed"); return new XMLDataObjectImpl(doc.getDocumentElement()); - } catch (Exception e) { + } catch (final Exception e) { // never mind, we'll try non-validating - MessageProvider msg = MessageProvider.getInstance(); + final MessageProvider msg = MessageProvider.getInstance(); Logger.info(new LogMsg(msg.getMessage("invoker.00", null))); Logger.info(new LogMsg(e.getMessage())); } // try to parse non-validating try { - ByteArrayInputStream is = new ByteArrayInputStream(contentBytes); - Document doc = DOMUtils.parseDocument(is, false, null, null); + final ByteArrayInputStream is = new ByteArrayInputStream(contentBytes); + final Document doc = DOMUtils.parseDocument(is, false, null, null); // Since the parse tree will not contain any post schema validation information, // we need to register any attributes known to be of type xsd:Id manually. - NodeList idAttributes = XPathUtils.selectNodeList(doc.getDocumentElement(), XPATH); + final NodeList idAttributes = XPathUtils.selectNodeList(doc.getDocumentElement(), XPATH); for (int i = 0; i < idAttributes.getLength(); i++) { - Node item = idAttributes.item(i); + final Node item = idAttributes.item(i); if (item instanceof Attr) { - Attr attr = (Attr) item; - Element owner = attr.getOwnerElement(); + final Attr attr = (Attr) item; + final Element owner = attr.getOwnerElement(); // Only available in DOM-Level 3 (Java 1.5): // owner.setIdAttributeNode(attr, true); if (doc instanceof CoreDocumentImpl) { @@ -296,7 +282,7 @@ public class DataObjectFactory { } } return new XMLDataObjectImpl(doc.getDocumentElement()); - } catch (Exception e) { + } catch (final Exception e) { throw new MOAApplicationException("2218", null); } } @@ -305,68 +291,69 @@ public class DataObjectFactory { * Create an XMLDataObject from the given signature environment. * * @param signatureEnvironment The signature environment contained in the - * result. - * @param uri The URI identifying the data. This must be either the empty - * URI, an URI starting with "#xpointer", "#xmlns" - * or "#element"; or an URI starting with "#" and - * followed by an element ID. - * @param referenceID The reference ID to set for the data object. + * result. + * @param uri The URI identifying the data. This must be either + * the empty URI, an URI starting with + * "#xpointer", "#xmlns" + * or "#element"; or an URI starting + * with "#" and followed by an element + * ID. + * @param referenceID The reference ID to set for the data object. * @return A data object containing the signature environment. */ public DataObject createFromSignatureEnvironment( - Element signatureEnvironment, - String uri, - String referenceID) - throws MOAApplicationException { + Element signatureEnvironment, + String uri, + String referenceID) + throws MOAApplicationException { DataObjectImpl dataObject = null; if ("".equals(uri)) { dataObject = new XMLDataObjectImpl(signatureEnvironment); - } else if ( - uri.startsWith("#xpointer") + } else if (uri.startsWith("#xpointer") || uri.startsWith("#xmlns") || uri.startsWith("#element")) { try { - // CHANGE IXSIL to XSECT - // maybe use URIDereferencerImpl or XPath ...?? - //XPointerReferenceResolver resolver = new XPointerReferenceResolver(); - URIDereferencerImpl uriDereferencer = new URIDereferencerImpl(); - URIReference uriReference = new URIReferenceImpl(uri, null, signatureEnvironment); - Data returnedData = uriDereferencer.dereference(uriReference, null); - - if(returnedData instanceof NodeSetData) { - NodeSetData nodeSetData = (NodeSetData)returnedData; - Iterator nodesIterator = nodeSetData.iterator(); - List nodeList = new ArrayList(); - - while(nodesIterator.hasNext()) { - nodeList.add(nodesIterator.next()); - } - - NodeList nodes = new NodeListImplementation(nodeList); - dataObject = new XMLNodeListDataObjectImpl(nodes); - } else if(returnedData instanceof OctetStreamData) { - OctetStreamData streamData = (OctetStreamData)returnedData; - dataObject = new ByteStreamDataObjectImpl(streamData.getOctetStream()); + // CHANGE IXSIL to XSECT + // maybe use URIDereferencerImpl or XPath ...?? + // XPointerReferenceResolver resolver = new XPointerReferenceResolver(); + final URIDereferencerImpl uriDereferencer = new URIDereferencerImpl(); + final URIReference uriReference = new URIReferenceImpl(uri, null, signatureEnvironment); + final Data returnedData = uriDereferencer.dereference(uriReference, null); + + if (returnedData instanceof NodeSetData) { + final NodeSetData nodeSetData = (NodeSetData) returnedData; + final Iterator nodesIterator = nodeSetData.iterator(); + final List nodeList = new ArrayList(); + + while (nodesIterator.hasNext()) { + nodeList.add(nodesIterator.next()); + } + + final NodeList nodes = new NodeListImplementation(nodeList); + dataObject = new XMLNodeListDataObjectImpl(nodes); + } else if (returnedData instanceof OctetStreamData) { + final OctetStreamData streamData = (OctetStreamData) returnedData; + dataObject = new ByteStreamDataObjectImpl(streamData.getOctetStream()); } else { - throw new MOAApplicationException("2237", new Object[] { uri }); + throw new MOAApplicationException("2237", new Object[] { uri }); } - - //URI uriObj = new URI(uri); - //NodeList nodes = - // resolver.resolveForest( - // uriObj, - // signatureEnvironment.getOwnerDocument(), - // null); - - } catch (Exception e) { + + // URI uriObj = new URI(uri); + // NodeList nodes = + // resolver.resolveForest( + // uriObj, + // signatureEnvironment.getOwnerDocument(), + // null); + + } catch (final Exception e) { throw new MOAApplicationException("2237", new Object[] { uri }); } } else if (uri.startsWith("#")) { - String id = uri.substring(1); - Element refElem = - signatureEnvironment.getOwnerDocument().getElementById(id); + final String id = uri.substring(1); + final Element refElem = + signatureEnvironment.getOwnerDocument().getElementById(id); if (refElem == null) { throw new MOAApplicationException("2237", new Object[] { id }); @@ -385,87 +372,75 @@ public class DataObjectFactory { * supplements. * * @param supplements The supplements, given as - * XMLDataObjectAssociations. - * @return A StreamEntityResolver mapping the supplements by - * their reference URI to an InputStream of their respective - * content. + * XMLDataObjectAssociations. + * @return A StreamEntityResolver mapping the supplements by their + * reference URI to an InputStream of their respective + * content. */ private static StreamEntityResolver buildSupplementEntityResolver(List supplements) - throws MOAApplicationException - { - Map entities = new HashMap(); + throws MOAApplicationException { + final Map entities = new HashMap(); Iterator iter; for (iter = supplements.iterator(); iter.hasNext();) { - XMLDataObjectAssociation supplement = - (XMLDataObjectAssociation) iter.next(); - Content content = supplement.getContent(); - String reference = content.getReference(); + final XMLDataObjectAssociation supplement = + (XMLDataObjectAssociation) iter.next(); + final Content content = supplement.getContent(); + final String reference = content.getReference(); switch (content.getContentType()) { - case Content.BINARY_CONTENT : - { - entities.put(reference, ((ContentBinary) content).getBinaryContent()); - break; + case Content.BINARY_CONTENT: { + entities.put(reference, ((ContentBinary) content).getBinaryContent()); + break; + } + case Content.LOCREF_CONTENT: { + final String locRefURI = ((ContentLocRef) content).getLocationReferenceURI(); + + final TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); + if (context.FindResolvedEntity(locRefURI) == null) { + + final ExternalURIResolver uriResolver = new ExternalURIResolver(); + InputStream uriStream = null; + byte[] contentBytes; + String contentType = null; + try { + uriStream = uriResolver.resolve(locRefURI); + contentBytes = StreamUtils.readStream(uriStream); + contentType = uriResolver.getContentType(); + } catch (final Exception e) { + throw new MOAApplicationException("3202", new Object[] { reference, locRefURI }, e); + } finally { + closeInputStream(uriStream); + } + context.PutResolvedEntity(locRefURI, contentBytes, contentType); } - case Content.LOCREF_CONTENT: - { - String locRefURI = ((ContentLocRef) content).getLocationReferenceURI(); - - TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); - if (context.FindResolvedEntity(locRefURI)==null) { - - ExternalURIResolver uriResolver = new ExternalURIResolver(); - InputStream uriStream = null; - byte[] contentBytes; - String contentType = null; - try - { - uriStream = uriResolver.resolve(locRefURI); - contentBytes = StreamUtils.readStream(uriStream); - contentType = uriResolver.getContentType(); - } - catch (Exception e) - { - throw new MOAApplicationException("3202", new Object[]{reference, locRefURI}, e); - } - finally - { - closeInputStream(uriStream); - } - context.PutResolvedEntity(locRefURI, contentBytes, contentType); - } - InputStream contentIS = context.ResolveURI(locRefURI); - entities.put(reference, contentIS); - break; + final InputStream contentIS = context.ResolveURI(locRefURI); + entities.put(reference, contentIS); + break; + } + case Content.XML_CONTENT: { + // serialize the first element node that is found in the supplement + // and make it available as a stream + final NodeList nodes = ((ContentXML) content).getXMLContent(); + int i = 0; + + // find the first element node + while (i < nodes.getLength() + && nodes.item(i).getNodeType() != Node.ELEMENT_NODE) { + i++; } - case Content.XML_CONTENT : - { - // serialize the first element node that is found in the supplement - // and make it available as a stream - NodeList nodes = ((ContentXML) content).getXMLContent(); - int i = 0; - - // find the first element node - while ((i < nodes.getLength()) - && (nodes.item(i).getNodeType() != Node.ELEMENT_NODE)) { - i++; - } - // serialize the node - if (i < nodes.getLength()) { - try - { - byte[] serialized = DOMUtils.serializeNode(nodes.item(i), "UTF-8"); - entities.put(reference, new ByteArrayInputStream(serialized)); - } - catch (Exception e) - { - throw new MOAApplicationException("2281", new Object[]{reference}, e); - } + // serialize the node + if (i < nodes.getLength()) { + try { + final byte[] serialized = DOMUtils.serializeNode(nodes.item(i), "UTF-8"); + entities.put(reference, new ByteArrayInputStream(serialized)); + } catch (final Exception e) { + throw new MOAApplicationException("2281", new Object[] { reference }, e); } - break; } + break; + } } } @@ -475,82 +450,87 @@ public class DataObjectFactory { /** * Create a DataObject from a Content object. * - * @param content The Content object containing the data. - * @param finalDataMetaInfo The meta information corresponding with content. - * @param referenceID The reference ID to set in the resulting - * DataObject. May be null. + * @param content The Content object containing + * the data. + * @param finalDataMetaInfo The meta information corresponding with + * content. + * @param referenceID The reference ID to set in the resulting + * DataObject. May be + * null. * @param allowContentAndReference If true, then - * content is allowed to contain both a Reference - * attribute and content. Otherwise, either a Reference - * attribute or content must be set. - * @param binaryAsXml If true, a content child given as - * Base64Content must contain XML data. - * @param xmlAsNodeList If true, the children of a - * XMLContent child element are returned as a - * XMLNodeListDataObject. Otherwise, XMLContent may - * only contain a single child node, which must be an element and which is - * returned as an XMLDataObject. - * @param referenceAsXml If true, then content loaded from the - * URI given as the Reference attribute must be XML data. - * If false, an attempt is made to parse the data as XML and - * return an XMLDataObject but if this fails, a - * BinaryDataObject is returned containing a byte stream to the - * data. + * content is allowed to contain + * both a Reference attribute and + * content. Otherwise, either a + * Reference attribute or content + * must be set. + * @param binaryAsXml If true, a content child given + * as Base64Content must contain + * XML data. + * @param xmlAsNodeList If true, the children of a + * XMLContent child element are + * returned as a + * XMLNodeListDataObject. + * Otherwise, XMLContent may only + * contain a single child node, which must be an + * element and which is returned as an + * XMLDataObject. + * @param referenceAsXml If true, then content loaded + * from the URI given as the + * Reference attribute must be XML + * data. If false, an attempt is + * made to parse the data as XML and return an + * XMLDataObject but if this fails, + * a BinaryDataObject is returned + * containing a byte stream to the data. * @return A DataObject representing the data in - * content. If base64AsXml==true and - * xmlAsNodeList==false and referenceAsXml==true, - * then the result can safely be cast to an XMLDataObject. - * @throws MOASystemException An error indicating an internal problem. See the - * wrapped exception for details. + * content. If base64AsXml==true and + * xmlAsNodeList==false and + * referenceAsXml==true, then the result can safely be cast + * to an XMLDataObject. + * @throws MOASystemException An error indicating an internal problem. See + * the wrapped exception for details. * @throws MOAApplicationException An error occurred handling the content - * (probably while opening a reference or parsing the data). See the wrapped - * exception for details. + * (probably while opening a reference or + * parsing the data). See the wrapped exception + * for details. */ public DataObject createFromContentOptionalRefType( - Content content, - MetaInfo finalDataMetaInfo, - String referenceID, - boolean allowContentAndReference, - boolean binaryAsXml, - boolean xmlAsNodeList, - boolean referenceAsXml) - throws MOASystemException, MOAApplicationException { - - String reference = content.getReference(); + Content content, + MetaInfo finalDataMetaInfo, + String referenceID, + boolean allowContentAndReference, + boolean binaryAsXml, + boolean xmlAsNodeList, + boolean referenceAsXml) + throws MOASystemException, MOAApplicationException { + + final String reference = content.getReference(); DataObjectImpl dataObject = null; checkAllowContentAndReference(content, allowContentAndReference); // ok, build the data object; use content first, if available - switch (content.getContentType()) - { - case Content.XML_CONTENT : - { - ContentXML contentXml = (ContentXML) content; + switch (content.getContentType()) { + case Content.XML_CONTENT: { + final ContentXML contentXml = (ContentXML) content; dataObject = createFromXmlContent(contentXml, xmlAsNodeList); break; } - case Content.BINARY_CONTENT : - { - ContentBinary contentBinary = (ContentBinary) content; + case Content.BINARY_CONTENT: { + final ContentBinary contentBinary = (ContentBinary) content; dataObject = createFromBinaryContent(contentBinary, binaryAsXml, false); break; } - case Content.LOCREF_CONTENT : - { - String locRefURI = ((ContentLocRef) content).getLocationReferenceURI(); - try - { + case Content.LOCREF_CONTENT: { + final String locRefURI = ((ContentLocRef) content).getLocationReferenceURI(); + try { dataObject = createFromURIImpl(locRefURI, referenceAsXml); - } - catch (MOAApplicationException e) - { - throw new MOAApplicationException("3201", new Object[]{reference, locRefURI}, e); + } catch (final MOAApplicationException e) { + throw new MOAApplicationException("3201", new Object[] { reference, locRefURI }, e); } break; } - case Content.REFERENCE_CONTENT : - { + case Content.REFERENCE_CONTENT: { dataObject = createFromURIImpl(reference, referenceAsXml); break; } @@ -567,97 +547,91 @@ public class DataObjectFactory { } /** - * Check, if content and reference URIs are allowed in the content an throw - * an exception if an illegal combination of the two occurs. + * Check, if content and reference URIs are allowed in the content an throw an + * exception if an illegal combination of the two occurs. * - * @param content The Content to check. - * @param allowContentAndReference Whether explicit content and a reference - * are allowed at the same time. - * @throws MOAApplicationException If allowContentAndRefernece - * is false and both explicit content and reference are set, - * an exception is thrown. + * @param content The Content to check. + * @param allowContentAndReference Whether explicit content and a reference are + * allowed at the same time. + * @throws MOAApplicationException If allowContentAndRefernece is + * false and both explicit content + * and reference are set, an exception is + * thrown. */ private static void checkAllowContentAndReference( - Content content, - boolean allowContentAndReference) - throws MOAApplicationException { - String reference = content.getReference(); + Content content, + boolean allowContentAndReference) + throws MOAApplicationException { + final String reference = content.getReference(); // check for content and reference not being set - if ((content.getContentType() == Content.REFERENCE_CONTENT) - && (reference == null)) { - String errorCode = allowContentAndReference ? "1111" : "1110"; + if (content.getContentType() == Content.REFERENCE_CONTENT + && reference == null) { + final String errorCode = allowContentAndReference ? "1111" : "1110"; throw new MOAApplicationException(errorCode, null); } // if we only allow either content or reference being set at once, check if (!allowContentAndReference - && (content.getContentType() != Content.REFERENCE_CONTENT) - && (reference != null)) { + && content.getContentType() != Content.REFERENCE_CONTENT + && reference != null) { throw new MOAApplicationException("1110", null); } } /** - * Create a DataObject from a - * XMLDataObjectAssociation object. + * Create a DataObject from a XMLDataObjectAssociation + * object. * - * @param xmlDataObjAssoc The XMLDataObjectAssociation object. - * @param xmlContentAllowed Whether the content contained in the - * xmlDataObjAssoc is allowed to be of type - * XML_CONTENT. + * @param xmlDataObjAssoc The XMLDataObjectAssociation + * object. + * @param xmlContentAllowed Whether the content contained in the + * xmlDataObjAssoc is allowed to be + * of type XML_CONTENT. * @param binaryContentRepeatable If binary content must be provided as a - * DataObject that can be read multiple times. + * DataObject that can be read + * multiple times. * @return A DataObject representing the data in - * xmlDataObjAssoc. - * @throws MOASystemException An error indicating an internal problem. See the - * wrapped exception for details. + * xmlDataObjAssoc. + * @throws MOASystemException An error indicating an internal problem. See + * the wrapped exception for details. * @throws MOAApplicationException An error occurred handling the content - * (probably while parsing the data). See the wrapped exception for details. + * (probably while parsing the data). See the + * wrapped exception for details. */ public DataObject createFromXmlDataObjectAssociation( - XMLDataObjectAssociation xmlDataObjAssoc, - boolean xmlContentAllowed, - boolean binaryContentRepeatable) - throws MOASystemException, MOAApplicationException { - - Content content = xmlDataObjAssoc.getContent(); - MetaInfo metaInfo = xmlDataObjAssoc.getMetaInfo(); - String mimeType = metaInfo != null ? metaInfo.getMimeType() : null; + XMLDataObjectAssociation xmlDataObjAssoc, + boolean xmlContentAllowed, + boolean binaryContentRepeatable) + throws MOASystemException, MOAApplicationException { + + final Content content = xmlDataObjAssoc.getContent(); + final MetaInfo metaInfo = xmlDataObjAssoc.getMetaInfo(); + final String mimeType = metaInfo != null ? metaInfo.getMimeType() : null; DataObjectImpl dataObject = null; - switch (content.getContentType()) - { - case Content.XML_CONTENT : - { - if (xmlContentAllowed) - { + switch (content.getContentType()) { + case Content.XML_CONTENT: { + if (xmlContentAllowed) { dataObject = createFromXmlContent((ContentXML) content, true); - } - else - { + } else { throw new MOAApplicationException("2280", null); } break; } - case Content.BINARY_CONTENT : - { + case Content.BINARY_CONTENT: { dataObject = createFromBinaryContent( - (ContentBinary) content, - false, - binaryContentRepeatable); + (ContentBinary) content, + false, + binaryContentRepeatable); break; } - case Content.LOCREF_CONTENT : - { - String locRefURI = ((ContentLocRef) content).getLocationReferenceURI(); - try - { + case Content.LOCREF_CONTENT: { + final String locRefURI = ((ContentLocRef) content).getLocationReferenceURI(); + try { dataObject = createFromURIImpl(locRefURI, false); - } - catch (MOAApplicationException e) - { - throw new MOAApplicationException("3201", new Object[]{content.getReference(), locRefURI}, e); + } catch (final MOAApplicationException e) { + throw new MOAApplicationException("3201", new Object[] { content.getReference(), locRefURI }, e); } break; } @@ -673,53 +647,49 @@ public class DataObjectFactory { * object. * * @param transformParameter The TransformParameter object - * containing the data. - * @return A DataObject representing the data in - * root. - * @throws MOASystemException An error indicating an internal problem. See the - * wrapped exception for details. + * containing the data. + * @return A DataObject representing the data in root. + * @throws MOASystemException An error indicating an internal problem. See + * the wrapped exception for details. * @throws MOAApplicationException An error occurred handling the content - * (probably while opening a reference or parsing the data). See the wrapped - * exception for details. + * (probably while opening a reference or + * parsing the data). See the wrapped exception + * for details. */ public DataObject createFromTransformParameter(TransformParameter transformParameter) - throws MOASystemException, MOAApplicationException { + throws MOASystemException, MOAApplicationException { DataObjectImpl dataObject; switch (transformParameter.getTransformParameterType()) { - case TransformParameter.BINARY_TRANSFORMPARAMETER : - TransformParameterBinary tpBinary = - (TransformParameterBinary) transformParameter; + case TransformParameter.BINARY_TRANSFORMPARAMETER: + final TransformParameterBinary tpBinary = + (TransformParameterBinary) transformParameter; try { - //dataObject = new ByteArrayDataObjectImpl(Base64Utils.encode(tpBinary.getBinaryContent())); + // dataObject = new + // ByteArrayDataObjectImpl(Base64Utils.encode(tpBinary.getBinaryContent())); dataObject = - new ByteArrayDataObjectImpl( - StreamUtils.readStream(tpBinary.getBinaryContent())); - } catch (Exception e) { + new ByteArrayDataObjectImpl( + StreamUtils.readStream(tpBinary.getBinaryContent())); + } catch (final Exception e) { return null; } - //dataObject = new ByteStreamDataObjectImpl(tpBinary.getBinaryContent()); + // dataObject = new ByteStreamDataObjectImpl(tpBinary.getBinaryContent()); break; - default : + default: // resolve uri and build the content - ExternalURIResolver resolver = new ExternalURIResolver(); - InputStream is = resolver.resolve(transformParameter.getURI()); + final ExternalURIResolver resolver = new ExternalURIResolver(); + final InputStream is = resolver.resolve(transformParameter.getURI()); ByteArrayInputStream bis; - try - { + try { bis = new ByteArrayInputStream(StreamUtils.readStream(is)); - } - catch (IOException e) - { - throw new MOAApplicationException("2238", new Object[] {transformParameter.getURI()}, e); - } - finally - { + } catch (final IOException e) { + throw new MOAApplicationException("2238", new Object[] { transformParameter.getURI() }, e); + } finally { closeInputStream(is); } - String contentType = resolver.getContentType(); + final String contentType = resolver.getContentType(); dataObject = new ByteStreamDataObjectImpl(bis); dataObject.setMimeType(contentType); break; @@ -733,62 +703,65 @@ public class DataObjectFactory { /** * Create a DataObject from data located at the given URI. * - * @param uri The URI where the data is located. This method uses - * an ExternalURIResolver to resolve URIs. + * @param uri The URI where the data is located. This method uses + * an ExternalURIResolver to resolve URIs. * @param asXml If true, a DataObject is only - * returned, if the content consists of XML data. If it does not consist of - * XML data, an MOAApplicationException will be thrown. If this - * parameter is false and the content consists of XML data, this - * method will still attempt to parse it. + * returned, if the content consists of XML data. If it does not + * consist of XML data, an MOAApplicationException + * will be thrown. If this parameter is false and the + * content consists of XML data, this method will still attempt to + * parse it. * @return The DataObject contained at the URI. - * @throws MOASystemException A system error parsing the XML content. + * @throws MOASystemException A system error parsing the XML content. * @throws MOAApplicationException An error occurred on opening, reading or - * parsing the data behind the URI. + * parsing the data behind the URI. */ public DataObject createFromURI(String uri, boolean asXml) - throws MOASystemException, MOAApplicationException { + throws MOASystemException, MOAApplicationException { return createFromURIImpl(uri, asXml); } /** * Create a DataObject from data located at the given URI. * - * @param uri The URI where the data is located. This method uses - * an ExternalURIResolver to resolve URIs. + * @param uri The URI where the data is located. This method uses + * an ExternalURIResolver to resolve URIs. * @param asXml If true, a DataObject is only - * returned, if the content consists of XML data. If it does not consist of - * XML data, an MOAApplicationException will be thrown. If this - * parameter is false and the content type is detected as being - * XML data, this method will still attemt to parse it. + * returned, if the content consists of XML data. If it does not + * consist of XML data, an MOAApplicationException + * will be thrown. If this parameter is false and the + * content type is detected as being XML data, this method will + * still attemt to parse it. * @return The DataObject contained at the URI. - * @throws MOASystemException A system error parsing the XML content. + * @throws MOASystemException A system error parsing the XML content. * @throws MOAApplicationException An error occurred on opening, reading or - * parsing the data behind the URI. + * parsing the data behind the URI. */ private DataObjectImpl createFromURIImpl(String uri, boolean asXml) - throws MOASystemException, MOAApplicationException { + throws MOASystemException, MOAApplicationException { Logger.trace(">>> resolving uri \"" + uri + "\""); - ExternalURIResolver resolver = new ExternalURIResolver(); + final ExternalURIResolver resolver = new ExternalURIResolver(); - TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); + final TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); InputStream is = context.ResolveURI(uri); String contentType = null; boolean foundURI = false; if (is == null) { - is = resolver.resolve(uri); - contentType = resolver.getContentType(); + is = resolver.resolve(uri); + contentType = resolver.getContentType(); } else { - foundURI = true; - contentType = (String) context.FindResolvedEntity(uri).get(1); - Logger.trace("found \"" + uri + "\" InputStream in preread Supplements!, do not read any more. Content=" + contentType); + foundURI = true; + contentType = (String) context.FindResolvedEntity(uri).get(1); + Logger.trace("found \"" + uri + "\" InputStream in preread Supplements!, do not read any more. Content=" + + contentType); } DataObjectImpl dataObject; // read the content - if ((contentType != null) && contentTypeIsXml(contentType)) { + if (contentType != null && contentTypeIsXml(contentType)) { Document doc; if (asXml) { @@ -798,15 +771,13 @@ public class DataObjectFactory { is = resolver.resolve(uri); doc = DOMUtils.parseDocument(is, false, null, null); dataObject = new XMLDataObjectImpl(doc.getDocumentElement()); - } catch (ParserConfigurationException e) { + } catch (final ParserConfigurationException e) { throw new MOASystemException("1106", null, e); - } catch (SAXException e) { + } catch (final SAXException e) { throw new MOAApplicationException("2209", null, e); - } catch (IOException e) { + } catch (final IOException e) { throw new MOAApplicationException("2210", null, e); - } - finally - { + } finally { closeInputStream(is); } } else { @@ -816,22 +787,17 @@ public class DataObjectFactory { doc = DOMUtils.parseDocument(is, false, null, null); closeInputStream(is); dataObject = new XMLDataObjectImpl(doc.getDocumentElement()); - } catch (Exception e) { + } catch (final Exception e) { // this is the last chance: return the data as a byte stream Logger.trace(">>> reading stream for \"" + uri + "\""); is = resolver.resolve(uri); ByteArrayInputStream bis; - try - { + try { bis = new ByteArrayInputStream(StreamUtils.readStream(is)); dataObject = new ByteStreamDataObjectImpl(bis); - } - catch (IOException e1) - { + } catch (final IOException e1) { throw new MOAApplicationException("2210", new Object[] { uri }, e1); - } - finally - { + } finally { closeInputStream(is); } Logger.trace(">>> read stream for \"" + uri + "\""); @@ -839,34 +805,26 @@ public class DataObjectFactory { } } - else if (asXml) - { + else if (asXml) { // if we need XML data, we're in the wrong place here closeInputStream(is); throw new MOAApplicationException("2211", new Object[] { uri }); - } - else - { + } else { // content is binary: make it available as a binary input stream Logger.trace(">>> getting binary input for \"" + uri + "\""); byte[] contentBytes; ByteArrayInputStream bis; - try - { - contentBytes = StreamUtils.readStream(is); - bis = new ByteArrayInputStream(contentBytes); - } - catch (IOException e) - { + try { + contentBytes = StreamUtils.readStream(is); + bis = new ByteArrayInputStream(contentBytes); + } catch (final IOException e) { throw new MOAApplicationException("2210", null, e); - } - finally - { + } finally { closeInputStream(is); } - if (!foundURI) { - context.PutResolvedEntity(uri, contentBytes, contentType); - } + if (!foundURI) { + context.PutResolvedEntity(uri, contentBytes, contentType); + } dataObject = new ByteStreamDataObjectImpl(bis); Logger.trace("<<< got binary input for \"" + uri + "\""); } @@ -884,16 +842,12 @@ public class DataObjectFactory { * * @param is The input stream to be closed. */ - private static void closeInputStream(InputStream is) - { - try - { + private static void closeInputStream(InputStream is) { + try { if (is != null) { is.close(); } - } - catch (Throwable t) - { + } catch (final Throwable t) { // Intentionally do nothing here } } @@ -905,42 +859,43 @@ public class DataObjectFactory { * application/xml. * * @param contentType The content MIME type. - * @return boolean If true, the content type is XML, otherwise - * not. + * @return boolean If true, the content type is XML, otherwise not. */ private static boolean contentTypeIsXml(String contentType) { return contentType.startsWith("text/xml") - || (contentType.startsWith("application/xml")); + || contentType.startsWith("application/xml"); } /** * Create a DataObject from a ContentXML object. * - * @param xmlContent The ContentXML object from - * which the DataObject is to be built. + * @param xmlContent The ContentXML object from which the + * DataObject is to be built. * @param xmlAsNodeList If true, the children of - * xmlContent are returned as a - * XMLNodeListDataObject. Otherwise, - * xmlContent may only contain a single child node, which must be - * an element and which is returned as an XMLDataObject. + * xmlContent are returned as a + * XMLNodeListDataObject. Otherwise, + * xmlContent may only contain a single child + * node, which must be an element and which is returned as + * an XMLDataObject. * @return A DataObject representing the XML content in - * xmlContent. + * xmlContent. * @throws MOAApplicationException If xmlAsNodeList is - * false and xmlContent does not have a single child - * element. + * false and + * xmlContent does not have a + * single child element. */ private DataObjectImpl createFromXmlContent( - ContentXML xmlContent, - boolean xmlAsNodeList) - throws MOAApplicationException { + ContentXML xmlContent, + boolean xmlAsNodeList) + throws MOAApplicationException { DataObjectImpl dataObject; if (xmlAsNodeList) { dataObject = new XMLNodeListDataObjectImpl(xmlContent.getXMLContent()); } else { - NodeList nodes = xmlContent.getXMLContent(); - Element element = checkForSingleElement(nodes); + final NodeList nodes = xmlContent.getXMLContent(); + final Element element = checkForSingleElement(nodes); // build the XMLDataObject dataObject = new XMLDataObjectImpl(element); @@ -955,10 +910,10 @@ public class DataObjectFactory { * @param nodes The NodeList to check for a single element. * @return The single element contained in nodes. * @throws MOAApplicationException Thrown, if nodes does not - * contain exactly 1 element node. + * contain exactly 1 element node. */ private Element checkForSingleElement(NodeList nodes) - throws MOAApplicationException { + throws MOAApplicationException { Element element = null; int i; @@ -986,26 +941,28 @@ public class DataObjectFactory { * Create a DataObject from a ContentBinary object. * * @param binaryContent The ContentBinary object containing the - * data. - * @param asXml If true, binaryContent must - * contain XML data. Otherwise, a BinaryDataObject will be - * returned containing a byte stream to the decoded Base64 data. - * @param repeatable If multiple calls to getInputStream() must - * repeatedly return the content of the data object. + * data. + * @param asXml If true, binaryContent must + * contain XML data. Otherwise, a + * BinaryDataObject will be returned + * containing a byte stream to the decoded Base64 data. + * @param repeatable If multiple calls to getInputStream() must + * repeatedly return the content of the data object. * @return A DataObject representing the content contained in - * binaryContent. - * @throws MOASystemException An error indicating an internal problem. See the - * wrapped exception for details. + * binaryContent. + * @throws MOASystemException An error indicating an internal problem. See + * the wrapped exception for details. * @throws MOAApplicationException An error occurred handling the content - * (probably while parsing the data). See the wrapped exception for details. + * (probably while parsing the data). See the + * wrapped exception for details. */ private DataObjectImpl createFromBinaryContent( - ContentBinary binaryContent, - boolean asXml, - boolean repeatable) - throws MOASystemException, MOAApplicationException { + ContentBinary binaryContent, + boolean asXml, + boolean repeatable) + throws MOASystemException, MOAApplicationException { - InputStream byteStream = binaryContent.getBinaryContent(); + final InputStream byteStream = binaryContent.getBinaryContent(); DataObjectImpl dataObject; if (asXml) { @@ -1014,19 +971,19 @@ public class DataObjectFactory { try { doc = DOMUtils.parseDocument(byteStream, false, null, null); dataObject = new XMLDataObjectImpl(doc.getDocumentElement()); - } catch (ParserConfigurationException e) { + } catch (final ParserConfigurationException e) { throw new MOASystemException("1106", null, e); - } catch (SAXException e) { + } catch (final SAXException e) { throw new MOAApplicationException("2209", null, e); - } catch (IOException e) { + } catch (final IOException e) { throw new MOAApplicationException("2210", null, e); } } else { if (repeatable) { try { dataObject = - new ByteArrayDataObjectImpl(StreamUtils.readStream(byteStream)); - } catch (IOException e) { + new ByteArrayDataObjectImpl(StreamUtils.readStream(byteStream)); + } catch (final IOException e) { throw new MOAApplicationException("2210", null); } } else { diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/ExternalURIResolver.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/ExternalURIResolver.java index 933d058..5668a36 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/ExternalURIResolver.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/ExternalURIResolver.java @@ -21,12 +21,8 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.invoke; -import iaik.xml.crypto.utils.URI; -import iaik.xml.crypto.utils.URIException; - import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; @@ -38,10 +34,12 @@ import at.gv.egovernment.moa.spss.MOAApplicationException; import at.gv.egovernment.moa.spss.server.transaction.TransactionContext; import at.gv.egovernment.moa.spss.server.transaction.TransactionContextManager; import at.gv.egovernment.moa.spss.util.ExternalURIVerifier; +import iaik.xml.crypto.utils.URI; +import iaik.xml.crypto.utils.URIException; /** * Resolve external URIs and provide them as a stream. - * + * * @author Patrick Peck * @version $Id$ */ @@ -52,14 +50,15 @@ public class ExternalURIResolver { /** * Return a stream to data at the given URI. - * - * This method will try to open an URLConnection to the given - * URI. Access to the file system is disallowed. - * + * + * This method will try to open an URLConnection to the given URI. + * Access to the file system is disallowed. + * * @param uriStr The URI to resolve. * @return InputStream The data contained at the URI. * @throws MOAApplicationException An error occurred resolving the URI (e.g., - * the URI is syntactically incorrect or the stream could not be opened). + * the URI is syntactically incorrect or the + * stream could not be opened). */ public InputStream resolve(String uriStr) throws MOAApplicationException { URI uri; @@ -70,7 +69,7 @@ public class ExternalURIResolver { // build the URI try { uri = new URI(uriStr); - } catch (URIException e) { + } catch (final URIException e) { throw new MOAApplicationException("2207", new Object[] { uriStr }); } @@ -81,30 +80,30 @@ public class ExternalURIResolver { // if we have local content (SOAP with attachments) if ("formdata".equals(uri.getScheme())) { - TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); - if (context==null) { - //no transaction + final TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); + if (context == null) { + // no transaction throw new MOAApplicationException("2282", new Object[] { uri }); } else { - InputStream attachmentIs = context.getAttachmentInputStream(uri); + final InputStream attachmentIs = context.getAttachmentInputStream(uri); if (attachmentIs != null) { setContentType(context.getAttachmentContentType(uri.getPath())); return attachmentIs; } else { - //maybe attachments provided but no suiting attachment found + // maybe attachments provided but no suiting attachment found throw new MOAApplicationException("2282", new Object[] { uri }); } - } - } - + } + } + // convert URI to URL try { // create the URL url = new URL(uriStr); - //System.out.println("ExternalURIResolver: " + url); + // System.out.println("ExternalURIResolver: " + url); ExternalURIVerifier.verify(url.getHost(), url.getPort()); - - } catch (MalformedURLException e) { + + } catch (final MalformedURLException e) { throw new MOAApplicationException("2214", new Object[] { uriStr }); } @@ -112,7 +111,7 @@ public class ExternalURIResolver { try { connection = url.openConnection(); if ("http".equals(url.getProtocol())) { - HttpURLConnection httpConnection = (HttpURLConnection) connection; + final HttpURLConnection httpConnection = (HttpURLConnection) connection; // disallow redirects httpConnection.setInstanceFollowRedirects(false); @@ -121,33 +120,31 @@ public class ExternalURIResolver { throw new MOAApplicationException("2208", new Object[] { uri }); } } else if ("https".equals(url.getProtocol())) { - /* - * this doesn't work because of some interaction between the IAIK - * JCE and Sun JSSE that results in an "Invalid AVA format" exception + /* + * this doesn't work because of some interaction between the IAIK JCE and Sun + * JSSE that results in an "Invalid AVA format" exception */ /* - HttpsURLConnection httpsConnection = (HttpsURLConnection) connection; - InputStream trustStore = - getClass().getResourceAsStream(DEFAULT_TRUST_STORE); - SSLSocketFactory factory = - SSLUtils.getSSLSocketFactory("jks", trustStore, "changeit"); - httpsConnection.setSSLSocketFactory(factory); - httpsConnection.connect(); - if (httpConnection.getResponseCode() != HttpURLConnection.HTTP_OK) { - throw new MOAApplicationException("2208", new Object[] { uri }); - } - */ + * HttpsURLConnection httpsConnection = (HttpsURLConnection) connection; + * InputStream trustStore = getClass().getResourceAsStream(DEFAULT_TRUST_STORE); + * SSLSocketFactory factory = SSLUtils.getSSLSocketFactory("jks", trustStore, + * "changeit"); httpsConnection.setSSLSocketFactory(factory); + * httpsConnection.connect(); if (httpConnection.getResponseCode() != + * HttpURLConnection.HTTP_OK) { throw new MOAApplicationException("2208", new + * Object[] { uri }); } + */ connection.connect(); } else { connection.connect(); } is = connection.getInputStream(); - } catch (IOException e) { + } catch (final IOException e) { throw new MOAApplicationException("2208", new Object[] { uri }, e); - } /*catch (GeneralSecurityException e) { - throw new MOAApplicationException("2208", new Object[] { uri }, e); - }*/ + } /* + * catch (GeneralSecurityException e) { throw new + * MOAApplicationException("2208", new Object[] { uri }, e); } + */ // set the content type setContentType(connection.getContentType()); @@ -157,7 +154,7 @@ public class ExternalURIResolver { /** * Set the content type of the data at the URI. - * + * * @param contentType The content type to set. */ protected void setContentType(String contentType) { @@ -167,7 +164,7 @@ public class ExternalURIResolver { /** * Return the content type of the data detected at the URI from the previous * call of resolve(). - * + * * @return String The content type. */ public String getContentType() { diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/IaikExceptionMapper.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/IaikExceptionMapper.java index 6e8448b..8817937 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/IaikExceptionMapper.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/IaikExceptionMapper.java @@ -21,12 +21,8 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.invoke; -import iaik.server.modules.IAIKException; -import iaik.server.modules.IAIKRuntimeException; - import java.lang.reflect.Constructor; import java.util.HashMap; import java.util.Map; @@ -34,12 +30,13 @@ import java.util.Map; import at.gv.egovernment.moa.spss.MOAApplicationException; import at.gv.egovernment.moa.spss.MOAException; import at.gv.egovernment.moa.spss.MOASystemException; - +import iaik.server.modules.IAIKException; +import iaik.server.modules.IAIKRuntimeException; /** * Map an exception from the iaik namespace to a * MOAException. - * + * * @author Patrick Peck * @version $Id$ */ @@ -47,57 +44,80 @@ public class IaikExceptionMapper { /** The argument classes for MOAExceptions. */ private static final Class[] CONSTRUCTOR_ARGS = - new Class[] { String.class, Object[].class, Throwable.class }; + new Class[] { String.class, Object[].class, Throwable.class }; /** The exception mapping, as an array. */ private static final Object[][] MESSAGES = - { - { iaik.server.modules.IAIKException.class, "9900", MOASystemException.class }, - { iaik.server.modules.IAIKRuntimeException.class, "9901", MOASystemException.class }, - { iaik.server.modules.xmlsign.XMLSignatureCreationException.class, "2220", MOAApplicationException.class }, - { iaik.server.modules.xmlsign.XMLSignatureCreationRuntimeException.class, "2220", MOAApplicationException.class }, - { iaik.server.modules.xmlsign.InvalidKeyException.class, "2221", MOAApplicationException.class }, - { iaik.server.modules.xmlsign.ManifestException.class, "2222", MOAApplicationException.class }, - { iaik.server.modules.xmlsign.ReferenceException.class, "2223", MOAApplicationException.class }, - { iaik.server.modules.xmlsign.HashUnavailableException.class, "2224", MOAApplicationException.class }, - { iaik.server.modules.xmlsign.SignatureAlgorithmException.class, "2225", MOAApplicationException.class }, - { iaik.server.modules.xmlsign.SignatureEmbeddingException.class, "2226", MOAApplicationException.class }, - { iaik.server.modules.xmlsign.SignatureValueException.class, "2227", MOAApplicationException.class }, - { iaik.server.modules.xmlsign.SignedPropertyException.class, "2228", MOAApplicationException.class }, - { iaik.server.modules.xmlsign.SignerCertificateUnavailableException.class, "2229", MOAApplicationException.class }, - { iaik.server.modules.xmlsign.SupplementException.class, "2230", MOAApplicationException.class }, - { iaik.server.modules.xmlsign.TransformationException.class, "2233", MOAApplicationException.class }, - { iaik.server.modules.cmsverify.CMSSignatureVerificationException.class, "2240", MOAApplicationException.class }, - { iaik.server.modules.cmsverify.CMSSignatureVerificationRuntimeException.class, "2240", MOAApplicationException.class }, - { iaik.server.modules.cmsverify.AlgorithmNotSupportedException.class, "2241", MOAApplicationException.class }, - { iaik.server.modules.cmsverify.CMSSignatureParsingException.class, "2242", MOAApplicationException.class }, - { iaik.server.modules.cmsverify.SignerCertificateUnavailableException.class, "2243", MOAApplicationException.class }, - { iaik.server.modules.cmsverify.CMSSignatureVerificationRuntimeException.class, "2247", MOAApplicationException.class }, - { iaik.server.modules.cmsverify.InitException.class, "2248", MOAApplicationException.class }, - { iaik.server.modules.xmlverify.XMLSignatureVerificationException.class, "2240", MOAApplicationException.class }, - { iaik.server.modules.xmlverify.XMLSignatureVerificationRuntimeException.class, "2240", MOAApplicationException.class }, - { iaik.server.modules.xmlverify.AlgorithmNotSupportedException.class, "2241", MOAApplicationException.class }, - { iaik.server.modules.xmlverify.ManifestException.class, "2262", MOAApplicationException.class }, - { iaik.server.modules.xmlverify.PropertiesException.class, "2263", MOAApplicationException.class }, - { iaik.server.modules.xmlverify.ReferenceException.class, "2264", MOAApplicationException.class }, - { iaik.server.modules.xmlverify.HashUnavailableException.class, "2224", MOAApplicationException.class }, - { iaik.server.modules.xmlverify.SignerCertificateUnavailableException.class, "2243", MOAApplicationException.class }, - { iaik.server.modules.xmlverify.SupplementException.class, "2230", MOAApplicationException.class }, - { iaik.server.modules.xmlverify.TransformationException.class, "2265", MOAApplicationException.class }, - { iaik.server.modules.xmlverify.TransformationParsingException.class, "2269", MOAApplicationException.class }, - { at.gv.egovernment.moa.sig.tsl.exception.TslException.class, "2290", MOAApplicationException.class }, - { iaik.server.modules.cmssign.CMSSignatureCreationException.class, "2300", MOAApplicationException.class } , - - - }; - + { + { iaik.server.modules.IAIKException.class, "9900", MOASystemException.class }, + { iaik.server.modules.IAIKRuntimeException.class, "9901", MOASystemException.class }, + { iaik.server.modules.xmlsign.XMLSignatureCreationException.class, "2220", + MOAApplicationException.class }, + { iaik.server.modules.xmlsign.XMLSignatureCreationRuntimeException.class, "2220", + MOAApplicationException.class }, + { iaik.server.modules.xmlsign.InvalidKeyException.class, "2221", MOAApplicationException.class }, + { iaik.server.modules.xmlsign.ManifestException.class, "2222", MOAApplicationException.class }, + { iaik.server.modules.xmlsign.ReferenceException.class, "2223", MOAApplicationException.class }, + { iaik.server.modules.xmlsign.HashUnavailableException.class, "2224", + MOAApplicationException.class }, + { iaik.server.modules.xmlsign.SignatureAlgorithmException.class, "2225", + MOAApplicationException.class }, + { iaik.server.modules.xmlsign.SignatureEmbeddingException.class, "2226", + MOAApplicationException.class }, + { iaik.server.modules.xmlsign.SignatureValueException.class, "2227", + MOAApplicationException.class }, + { iaik.server.modules.xmlsign.SignedPropertyException.class, "2228", + MOAApplicationException.class }, + { iaik.server.modules.xmlsign.SignerCertificateUnavailableException.class, "2229", + MOAApplicationException.class }, + { iaik.server.modules.xmlsign.SupplementException.class, "2230", MOAApplicationException.class }, + { iaik.server.modules.xmlsign.TransformationException.class, "2233", + MOAApplicationException.class }, + { iaik.server.modules.cmsverify.CMSSignatureVerificationException.class, "2240", + MOAApplicationException.class }, + { iaik.server.modules.cmsverify.CMSSignatureVerificationRuntimeException.class, "2240", + MOAApplicationException.class }, + { iaik.server.modules.cmsverify.AlgorithmNotSupportedException.class, "2241", + MOAApplicationException.class }, + { iaik.server.modules.cmsverify.CMSSignatureParsingException.class, "2242", + MOAApplicationException.class }, + { iaik.server.modules.cmsverify.SignerCertificateUnavailableException.class, "2243", + MOAApplicationException.class }, + { iaik.server.modules.cmsverify.CMSSignatureVerificationRuntimeException.class, "2247", + MOAApplicationException.class }, + { iaik.server.modules.cmsverify.InitException.class, "2248", MOAApplicationException.class }, + { iaik.server.modules.xmlverify.XMLSignatureVerificationException.class, "2240", + MOAApplicationException.class }, + { iaik.server.modules.xmlverify.XMLSignatureVerificationRuntimeException.class, "2240", + MOAApplicationException.class }, + { iaik.server.modules.xmlverify.AlgorithmNotSupportedException.class, "2241", + MOAApplicationException.class }, + { iaik.server.modules.xmlverify.ManifestException.class, "2262", MOAApplicationException.class }, + { iaik.server.modules.xmlverify.PropertiesException.class, "2263", MOAApplicationException.class }, + { iaik.server.modules.xmlverify.ReferenceException.class, "2264", MOAApplicationException.class }, + { iaik.server.modules.xmlverify.HashUnavailableException.class, "2224", + MOAApplicationException.class }, + { iaik.server.modules.xmlverify.SignerCertificateUnavailableException.class, "2243", + MOAApplicationException.class }, + { iaik.server.modules.xmlverify.SupplementException.class, "2230", MOAApplicationException.class }, + { iaik.server.modules.xmlverify.TransformationException.class, "2265", + MOAApplicationException.class }, + { iaik.server.modules.xmlverify.TransformationParsingException.class, "2269", + MOAApplicationException.class }, + { at.gv.egovernment.moa.sig.tsl.exception.TslException.class, "2290", + MOAApplicationException.class }, + { iaik.server.modules.cmssign.CMSSignatureCreationException.class, "2300", + MOAApplicationException.class }, + + }; + /** The single instance of this class. */ private static IaikExceptionMapper instance; /** The exception mapping, as a Map for fast lookup. */ - private Map messages = new HashMap(); + private final Map messages = new HashMap(); /** * Get the single instance of this class. - * + * * @return The single instance of this class. */ public static synchronized IaikExceptionMapper getInstance() { @@ -109,7 +129,7 @@ public class IaikExceptionMapper { /** * Create a new IaikExceptionMapper. - * + * * Protected to disallow multple instances. */ protected IaikExceptionMapper() { @@ -124,59 +144,63 @@ public class IaikExceptionMapper { for (i = 0; i < MESSAGES.length; i++) { registerMessage( - (Class) MESSAGES[i][0], - (String) MESSAGES[i][1], - (Class) MESSAGES[i][2]); + (Class) MESSAGES[i][0], + (String) MESSAGES[i][1], + (Class) MESSAGES[i][2]); } } /** * Register a single IAIKException to message mapping. - * - * @param iaikExceptionClass An exception from the iaik package. - * @param messageId The corresponding error message id. - * @param moaExceptionClass The type of MOAException that the - * IAIKException is mapped to (usually - * MOAApplicationException or MOASystemException). + * + * @param iaikExceptionClass An exception from the iaik package. + * @param messageId The corresponding error message id. + * @param moaExceptionClass The type of MOAException that the + * IAIKException is mapped to (usually + * MOAApplicationException or + * MOASystemException). */ protected void registerMessage( - Class iaikExceptionClass, - String messageId, - Class moaExceptionClass) { + Class iaikExceptionClass, + String messageId, + Class moaExceptionClass) { messages.put( - iaikExceptionClass, - new ExceptionMappingInfo(messageId, moaExceptionClass)); + iaikExceptionClass, + new ExceptionMappingInfo(messageId, moaExceptionClass)); } /** - * Map an iaik.xml.crypto.tsl.ex.TSLSearchException to a MOAException. - * - * @param tslSearchException The iaik.xml.crypto.tsl.ex.TSLSearchException to map. - * @return A MOAException containing the message for the - * given IAIKException. + * Map an iaik.xml.crypto.tsl.ex.TSLSearchException to a + * MOAException. + * + * @param tslSearchException The + * iaik.xml.crypto.tsl.ex.TSLSearchException + * to map. + * @return A MOAException containing the message for the given + * IAIKException. */ public MOAException map(at.gv.egovernment.moa.sig.tsl.exception.TslException tslSearchException) { return mapImpl(tslSearchException); } - + /** * Map an IAIKException to a MOAException. - * - * @param iaikException The IAIKException to map. - * @return A MOAException containing the message for the - * given IAIKException. + * + * @param iaikException The IAIKException to map. + * @return A MOAException containing the message for the given + * IAIKException. */ public MOAException map(IAIKException iaikException) { return mapImpl(iaikException); } - + /** * Map an IAIKRuntimeException to a MOAException. - * - * @param iaikException The IAIKException to map. - * @return A MOAException containing the message for the - * given IAIKRuntimeException. + * + * @param iaikException The IAIKException to map. + * @return A MOAException containing the message for the given + * IAIKRuntimeException. */ public MOAException map(IAIKRuntimeException iaikException) { return mapImpl(iaikException); @@ -185,14 +209,14 @@ public class IaikExceptionMapper { /** * Map an IAIKException or IAIKRuntimeException to a * MOAException. - * + * * @param iaikException The IAIKException or - * IAIKRuntimeException to map. - * @return A MOAException containing the message for the - * given IAIKRuntimeException. + * IAIKRuntimeException to map. + * @return A MOAException containing the message for the given + * IAIKRuntimeException. */ private MOAException mapImpl(Exception iaikException) { - MOAException moaException = createMoaException(iaikException); + final MOAException moaException = createMoaException(iaikException); if (moaException == null) { return new MOASystemException("9999", null, iaikException); @@ -201,16 +225,16 @@ public class IaikExceptionMapper { } /** - * Create a MOAException from a given IAIKException - * by looking it up in the mapping. - * + * Create a MOAException from a given IAIKException by + * looking it up in the mapping. + * * @param iaikException The IAIKException to map. - * @return A MOAException with an error code corresponding to - * the given IAIKException. Returns null, if no - * mapping could be found. + * @return A MOAException with an error code corresponding to the + * given IAIKException. Returns null, if no + * mapping could be found. */ protected MOAException createMoaException(Exception iaikException) { - ExceptionMappingInfo info = lookupMessage(iaikException.getClass()); + final ExceptionMappingInfo info = lookupMessage(iaikException.getClass()); Constructor constructor; if (info == null) { @@ -220,13 +244,13 @@ public class IaikExceptionMapper { // instantiate the proper MOAException and return it try { constructor = - info.getMoaExceptionClass().getConstructor(CONSTRUCTOR_ARGS); + info.getMoaExceptionClass().getConstructor(CONSTRUCTOR_ARGS); return (MOAException) constructor.newInstance( - new Object[] { - info.getMessageId(), - new Object[] { iaikException.getMessage()}, - iaikException }); - } catch (Exception e) { + new Object[] { + info.getMessageId(), + new Object[] { iaikException.getMessage() }, + iaikException }); + } catch (final Exception e) { return null; } } @@ -234,19 +258,19 @@ public class IaikExceptionMapper { /** * Recursively look up the message associated with an * IAIKException. - * + * * This method walks up the exception inheritance hierarchy until it finds a * mapping. - * + * * @param iaikExceptionClass The IAIKException to look up. - * @return Information about the message id and - * MOAException class that the iaikExceptionClass - * maps to. If no mapping could be found, null is returned. + * @return Information about the message id and MOAException class + * that the iaikExceptionClass maps to. If no mapping could + * be found, null is returned. */ protected ExceptionMappingInfo lookupMessage(Class iaikExceptionClass) { ExceptionMappingInfo info; - // break if + // break if if (iaikExceptionClass.equals(Exception.class)) { return null; } @@ -264,21 +288,21 @@ public class IaikExceptionMapper { /** * A class containing a mapping from an error message ID to a * MOAException class. - * + * * @author Patrick Peck * @version $Id$ */ class ExceptionMappingInfo { /** The message ID. */ - private String messageId; + private final String messageId; /** The MOAException class. */ - private Class moaExceptionClass; + private final Class moaExceptionClass; /** * Create a new ExceptionMappingInfo. - * - * @param messageId The message ID. - * @param moaExceptionClass The MOAException class. + * + * @param messageId The message ID. + * @param moaExceptionClass The MOAException class. */ public ExceptionMappingInfo(String messageId, Class moaExceptionClass) { this.messageId = messageId; @@ -287,7 +311,7 @@ class ExceptionMappingInfo { /** * Return the message ID. - * + * * @return The message ID. */ public String getMessageId() { @@ -296,7 +320,7 @@ class ExceptionMappingInfo { /** * Returns the MOAException class that the message ID maps to. - * + * * @return The MOAException class. */ public Class getMoaExceptionClass() { diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/InvokerUtils.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/InvokerUtils.java index 0128e6a..43c993b 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/InvokerUtils.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/InvokerUtils.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.invoke; import org.w3c.dom.Element; @@ -35,7 +34,7 @@ import at.gv.egovernment.moaspss.util.XPathUtils; /** * Utility methods for invoking the IAIK MOA modules. - * + * * @author Patrick Peck * @version $Id$ */ @@ -43,44 +42,44 @@ public class InvokerUtils { /** * Select the signature parent element. - * - * @param root The root DOM element which contains the signature parent - * element somewhere in its subtree. - * @param location The ElementSelector containing the XPath - * expression to select the signature parent element from the document. - * It is also contains the namespace prefix to URI mapping. + * + * @param root The root DOM element which contains the signature parent + * element somewhere in its subtree. + * @param location The ElementSelector containing the XPath + * expression to select the signature parent element from the + * document. It is also contains the namespace prefix to URI + * mapping. * @return Element The signature parent element. * @throws MOAApplicationException An error occurred evaluating the - * location. + * location. */ public static Element evaluateSignatureLocation( - Element root, - ElementSelector location) - throws MOAApplicationException { + Element root, + ElementSelector location) + throws MOAApplicationException { NodeList nodes; try { nodes = - XPathUtils.selectNodeList( - root, - location.getNamespaceDeclarations(), - location.getXPathExpression()); - } catch (XPathException e) { + XPathUtils.selectNodeList( + root, + location.getNamespaceDeclarations(), + location.getXPathExpression()); + } catch (final XPathException e) { throw new MOAApplicationException( - "2212", - new Object[] { location.getXPathExpression()}, - e); + "2212", + new Object[] { location.getXPathExpression() }, + e); } if (nodes.getLength() != 1 - || !(nodes.item(0).getNodeType() == Node.ELEMENT_NODE)) { + || !(nodes.item(0).getNodeType() == Node.ELEMENT_NODE)) { throw new MOAApplicationException( - "2212", - new Object[] { location.getXPathExpression()}); + "2212", + new Object[] { location.getXPathExpression() }); } return (Element) nodes.item(0); } - } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/ProfileMapper.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/ProfileMapper.java index c6eaa4f..474e74b 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/ProfileMapper.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/ProfileMapper.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.invoke; import java.util.ArrayList; @@ -48,7 +47,7 @@ import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; /** * Map ProfileID objects to their explicit represantation. - * + * * @author Patrick Peck * @version $Id$ */ @@ -58,83 +57,79 @@ public class ProfileMapper { private static ProfileParser profileParser = new ProfileParser(); /** - * Map a CreateTransformsInfoProfile to a + * Map a CreateTransformsInfoProfile to a * CreateTransformsInfoProfileExplicit. - * + * * @param profile The profile object to map. - * @param config The MOA configuration to use for looking up the profile. + * @param config The MOA configuration to use for looking up the profile. * @return profile, if the given profile is of type - * EXPLICIT_CREATETRANSFORMSINFOPROFILE, otherwise the profile - * that is looked up and parsed from the configuration. + * EXPLICIT_CREATETRANSFORMSINFOPROFILE, otherwise the + * profile that is looked up and parsed from the configuration. * @throws MOAApplicationException An error occurred parsing the profile. */ public static CreateTransformsInfoProfileExplicit mapCreateTransformsInfoProfile( - CreateTransformsInfoProfile profile, - ConfigurationProvider config) - throws MOAApplicationException { + CreateTransformsInfoProfile profile, + ConfigurationProvider config) + throws MOAApplicationException { switch (profile.getCreateTransformsInfoProfileType()) { - case CreateTransformsInfoProfile.EXPLICIT_CREATETRANSFORMSINFOPROFILE : + case CreateTransformsInfoProfile.EXPLICIT_CREATETRANSFORMSINFOPROFILE: return (CreateTransformsInfoProfileExplicit) profile; - case CreateTransformsInfoProfile.ID_CREATETRANSFORMSINFOPROFILE : - CreateTransformsInfoProfileID profileIdObj = - (CreateTransformsInfoProfileID) profile; - String profileID = profileIdObj.getCreateTransformsInfoProfileID(); - Element profileElem = config.getCreateTransformsInfoProfile(profileID); + case CreateTransformsInfoProfile.ID_CREATETRANSFORMSINFOPROFILE: + final CreateTransformsInfoProfileID profileIdObj = + (CreateTransformsInfoProfileID) profile; + final String profileID = profileIdObj.getCreateTransformsInfoProfileID(); + final Element profileElem = config.getCreateTransformsInfoProfile(profileID); if (profileElem == null) { throw new MOAApplicationException("2234", new Object[] { profileID }); } - return ( - CreateTransformsInfoProfileExplicit) profileParser + return (CreateTransformsInfoProfileExplicit) profileParser .parseCreateTransformsInfoProfile( - profileElem); + profileElem); } return null; // this will not happen } /** - * Map a CreateSignatureEnvironmentProfile to a + * Map a CreateSignatureEnvironmentProfile to a * CreateSignatureEnvironmentProfileExplicit. - * + * * @param profile The profile object to map. - * @param config The MOA configuration to use for looking up the profile. + * @param config The MOA configuration to use for looking up the profile. * @return profile, if the given profile is of type - * EXPLICIT_CREATESIGNATUREENVIRONMENTPROFILE, otherwise the - * profile that is looked up and parsed from the configuration. + * EXPLICIT_CREATESIGNATUREENVIRONMENTPROFILE, otherwise + * the profile that is looked up and parsed from the configuration. * @throws MOAApplicationException An error occurred parsing the profile. */ public static CreateSignatureEnvironmentProfileExplicit mapCreateSignatureEnvironmentProfile( - CreateSignatureEnvironmentProfile profile, - ConfigurationProvider config) - throws MOAApplicationException { + CreateSignatureEnvironmentProfile profile, + ConfigurationProvider config) + throws MOAApplicationException { switch (profile.getCreateSignatureEnvironmentProfileType()) { - case CreateSignatureEnvironmentProfile - .EXPLICIT_CREATESIGNATUREENVIRONMENTPROFILE : + case CreateSignatureEnvironmentProfile.EXPLICIT_CREATESIGNATUREENVIRONMENTPROFILE: return (CreateSignatureEnvironmentProfileExplicit) profile; - case CreateSignatureEnvironmentProfile - .ID_CREATESIGNATUREENVIRONMENTPROFILE : + case CreateSignatureEnvironmentProfile.ID_CREATESIGNATUREENVIRONMENTPROFILE: - CreateSignatureEnvironmentProfileID profileIdObj = - (CreateSignatureEnvironmentProfileID) profile; - String profileID = - profileIdObj.getCreateSignatureEnvironmentProfileID(); - Element profileElem = - config.getCreateSignatureEnvironmentProfile(profileID); + final CreateSignatureEnvironmentProfileID profileIdObj = + (CreateSignatureEnvironmentProfileID) profile; + final String profileID = + profileIdObj.getCreateSignatureEnvironmentProfileID(); + final Element profileElem = + config.getCreateSignatureEnvironmentProfile(profileID); if (profileElem == null) { throw new MOAApplicationException("2236", new Object[] { profileID }); } - return ( - CreateSignatureEnvironmentProfileExplicit) profileParser + return (CreateSignatureEnvironmentProfileExplicit) profileParser .parseCreateSignatureEnvironmentProfile( - profileElem); + profileElem); } return null; @@ -142,25 +137,25 @@ public class ProfileMapper { } /** - * Map a List of SupplementProfiles to their - * explicit representation. - * + * Map a List of SupplementProfiles to their explicit + * representation. + * * @param profiles The profiles to map. - * @param config The MOA configuration to use for looking up profiles. + * @param config The MOA configuration to use for looking up profiles. * @return The mapped profiles. * @throws MOAApplicationException An error occurred mapping one of the - * profiles. + * profiles. */ public static List mapSupplementProfiles( - List profiles, - ConfigurationProvider config) - throws MOAApplicationException { + List profiles, + ConfigurationProvider config) + throws MOAApplicationException { - List mappedProfiles = new ArrayList(); + final List mappedProfiles = new ArrayList(); Iterator iter; for (iter = profiles.iterator(); iter.hasNext();) { - SupplementProfile profile = (SupplementProfile) iter.next(); + final SupplementProfile profile = (SupplementProfile) iter.next(); mappedProfiles.add(mapSupplementProfile(profile, config)); } @@ -168,63 +163,62 @@ public class ProfileMapper { } /** - * Map a SupplementProfile to a + * Map a SupplementProfile to a * SupplementProfileExplicit. - * + * * @param profile The profile object to map. - * @param config The MOA configuration to use for looking up the profile. + * @param config The MOA configuration to use for looking up the profile. * @return profile, if the given profile is of type - * EXPLICIT_SUPPLEMENTPROFILE, otherwise the - * profile that is looked up and parsed from the configuration. + * EXPLICIT_SUPPLEMENTPROFILE, otherwise the profile that + * is looked up and parsed from the configuration. * @throws MOAApplicationException An error occurred parsing the profile. */ public static SupplementProfileExplicit mapSupplementProfile( - SupplementProfile profile, - ConfigurationProvider config) - throws MOAApplicationException { + SupplementProfile profile, + ConfigurationProvider config) + throws MOAApplicationException { switch (profile.getSupplementProfileType()) { - case SupplementProfile.EXPLICIT_SUPPLEMENTPROFILE : + case SupplementProfile.EXPLICIT_SUPPLEMENTPROFILE: return (SupplementProfileExplicit) profile; - case SupplementProfile.ID_SUPPLEMENTPROFILE : - SupplementProfileID profileIdObj = (SupplementProfileID) profile; - String profileID = profileIdObj.getSupplementProfileID(); - Element profileElem = config.getSupplementProfile(profileID); + case SupplementProfile.ID_SUPPLEMENTPROFILE: + final SupplementProfileID profileIdObj = (SupplementProfileID) profile; + final String profileID = profileIdObj.getSupplementProfileID(); + final Element profileElem = config.getSupplementProfile(profileID); if (profileElem == null) { throw new MOAApplicationException("2267", new Object[] { profileID }); } - return ( - SupplementProfileExplicit) profileParser.parseSupplementProfile( - profileElem); + return (SupplementProfileExplicit) profileParser.parseSupplementProfile( + profileElem); } return null; } /** - * Map a List of VerifyTransformsInfoProfiles to - * their explicit representation. - * + * Map a List of VerifyTransformsInfoProfiles to their + * explicit representation. + * * @param profiles The profiles to map. - * @param config The MOA configuration to use for looking up profiles. + * @param config The MOA configuration to use for looking up profiles. * @return The mapped profiles. * @throws MOAApplicationException An error occurred mapping one of the - * profiles. + * profiles. */ public static List mapVerifyTransformsInfoProfiles( - List profiles, - ConfigurationProvider config) - throws MOAApplicationException { + List profiles, + ConfigurationProvider config) + throws MOAApplicationException { - List mappedProfiles = new ArrayList(); + final List mappedProfiles = new ArrayList(); Iterator iter; for (iter = profiles.iterator(); iter.hasNext();) { - VerifyTransformsInfoProfile profile = - (VerifyTransformsInfoProfile) iter.next(); + final VerifyTransformsInfoProfile profile = + (VerifyTransformsInfoProfile) iter.next(); mappedProfiles.add(mapVerifyTransformsInfoProfile(profile, config)); } @@ -232,40 +226,39 @@ public class ProfileMapper { } /** - * Map a VerifyTransformsInfoProfile to a + * Map a VerifyTransformsInfoProfile to a * VerifyTransformsInfoProfileExplicit. - * + * * @param profile The profile object to map. - * @param config The MOA configuration to use for looking up the profile. + * @param config The MOA configuration to use for looking up the profile. * @return profile, if the given profile is of type - * EXPLICIT_VERIFYTRANSFORMSINFOPROFILE, otherwise the - * profile that is looked up and parsed from the configuration. + * EXPLICIT_VERIFYTRANSFORMSINFOPROFILE, otherwise the + * profile that is looked up and parsed from the configuration. * @throws MOAApplicationException An error occurred parsing the profile. */ public static VerifyTransformsInfoProfileExplicit mapVerifyTransformsInfoProfile( - VerifyTransformsInfoProfile profile, - ConfigurationProvider config) - throws MOAApplicationException { + VerifyTransformsInfoProfile profile, + ConfigurationProvider config) + throws MOAApplicationException { switch (profile.getVerifyTransformsInfoProfileType()) { - case VerifyTransformsInfoProfile.EXPLICIT_VERIFYTRANSFORMSINFOPROFILE : + case VerifyTransformsInfoProfile.EXPLICIT_VERIFYTRANSFORMSINFOPROFILE: return (VerifyTransformsInfoProfileExplicit) profile; - case VerifyTransformsInfoProfile.ID_VERIFYTRANSFORMSINFOPROFILE : - VerifyTransformsInfoProfileID profileIdObj = - (VerifyTransformsInfoProfileID) profile; - String profileID = profileIdObj.getVerifyTransformsInfoProfileID(); - Element profileElem = - config.getVerifyTransformsInfoProfile(profileID); - + case VerifyTransformsInfoProfile.ID_VERIFYTRANSFORMSINFOPROFILE: + final VerifyTransformsInfoProfileID profileIdObj = + (VerifyTransformsInfoProfileID) profile; + final String profileID = profileIdObj.getVerifyTransformsInfoProfileID(); + final Element profileElem = + config.getVerifyTransformsInfoProfile(profileID); + if (profileElem == null) { - throw new MOAApplicationException("2268", new Object[] { profileID }); + throw new MOAApplicationException("2268", new Object[] { profileID }); } - return ( - VerifyTransformsInfoProfileExplicit) profileParser + return (VerifyTransformsInfoProfileExplicit) profileParser .parseVerifyTransformsInfoProfile( - profileElem); + profileElem); } return null; diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/ServiceContextUtils.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/ServiceContextUtils.java index 330ffdd..0674103 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/ServiceContextUtils.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/ServiceContextUtils.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.invoke; import at.gv.egovernment.moa.spss.server.config.ConfigurationException; @@ -32,37 +31,38 @@ import at.gv.egovernment.moaspss.logging.LoggingContext; import at.gv.egovernment.moaspss.logging.LoggingContextManager; /** - * A utility class for setting up and tearing down thread-local context + * A utility class for setting up and tearing down thread-local context * information needed for calling the Invoker classes. - * + * * @author Patrick Peck * @version $Id$ */ public class ServiceContextUtils { - + /** - * Set up the thread-local context information needed for calling the various + * 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. + * + * @throws ConfigurationException An error occurred setting up the configuration + * in the TransactionContext. */ public static void setUpContexts() throws ConfigurationException { - TransactionContextManager txMgr = TransactionContextManager.getInstance(); - LoggingContextManager logMgr = LoggingContextManager.getInstance(); - String transactionID = Thread.currentThread().getName(); - + final TransactionContextManager txMgr = TransactionContextManager.getInstance(); + final LoggingContextManager logMgr = LoggingContextManager.getInstance(); + final String transactionID = Thread.currentThread().getName(); + if (txMgr.getTransactionContext() == null) { - TransactionContext ctx = new TransactionContext(transactionID, null, ConfigurationProvider.getInstance()); + final TransactionContext ctx = new TransactionContext(transactionID, null, ConfigurationProvider + .getInstance()); txMgr.setTransactionContext(ctx); } - + if (logMgr.getLoggingContext() == null) { - LoggingContext ctx = new LoggingContext(transactionID); + final LoggingContext ctx = new LoggingContext(transactionID); logMgr.setLoggingContext(ctx); } } - + /** * Tear down thread-local context information. */ diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/SignatureCreationServiceImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/SignatureCreationServiceImpl.java index b746333..ec4bdd9 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/SignatureCreationServiceImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/SignatureCreationServiceImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.invoke; import java.util.Collections; @@ -33,9 +32,9 @@ import at.gv.egovernment.moa.spss.api.xmlsign.CreateXMLSignatureRequest; import at.gv.egovernment.moa.spss.api.xmlsign.CreateXMLSignatureResponse; /** - * An implementation of the SignatureCreationService, using - * the XMLSignatureCreationInvoker. - * + * An implementation of the SignatureCreationService, using the + * XMLSignatureCreationInvoker. + * * @author Patrick Peck * @version $Id$ */ @@ -43,25 +42,26 @@ public class SignatureCreationServiceImpl extends SignatureCreationService { /** * Create an XML signature. - * + * * @param request The CreateXMLSignatureRequest containing - * information about the signature(s) to create. + * information about the signature(s) to create. * @return The created signature(s). * @throws MOAException An error occurred creating the signature(s). */ + @Override public CreateXMLSignatureResponse createXMLSignature(CreateXMLSignatureRequest request) - throws MOAException { + throws MOAException { - XMLSignatureCreationInvoker invoker = - XMLSignatureCreationInvoker.getInstance(); + final XMLSignatureCreationInvoker invoker = + XMLSignatureCreationInvoker.getInstance(); CreateXMLSignatureResponse response; try { - + Configurator.getInstance().init(); ServiceContextUtils.setUpContexts(); response = invoker.createXMLSignature(request, Collections.EMPTY_SET); - + return response; } finally { ServiceContextUtils.tearDownContexts(); diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/SignatureVerificationServiceImpl.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/SignatureVerificationServiceImpl.java index 5b6033c..50b7c53 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/SignatureVerificationServiceImpl.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/SignatureVerificationServiceImpl.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.invoke; import at.gv.egovernment.moa.spss.MOAException; @@ -33,36 +32,37 @@ import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureRequest; import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureResponse; /** - * An implementation of the SignatureVerificationService using - * the XMLSignatureVerificationInvoker and the + * An implementation of the SignatureVerificationService using the + * XMLSignatureVerificationInvoker and the * CMSSignatureVerificationInvoker. - * + * * @author Patrick Peck * @version $Id$ */ public class SignatureVerificationServiceImpl - extends SignatureVerificationService { + extends SignatureVerificationService { /** * Verify a CMS signature. - * - * @param request The VerifyCMSSignatureRequest containing - * information about the signature verification. + * + * @param request The VerifyCMSSignatureRequest containing + * information about the signature verification. * @return The result of the signature verification. * @throws MOAException An error occurred during signature verification. */ + @Override public VerifyCMSSignatureResponse verifyCMSSignature(VerifyCMSSignatureRequest request) - throws MOAException { + throws MOAException { - CMSSignatureVerificationInvoker invoker = - CMSSignatureVerificationInvoker.getInstance(); + final CMSSignatureVerificationInvoker invoker = + CMSSignatureVerificationInvoker.getInstance(); VerifyCMSSignatureResponse response; try { Configurator.getInstance().init(); ServiceContextUtils.setUpContexts(); response = invoker.verifyCMSSignature(request); - + return response; } finally { ServiceContextUtils.tearDownContexts(); @@ -71,26 +71,26 @@ public class SignatureVerificationServiceImpl /** * Verify an XML signature. - * + * * @param request The VerifyXMLSignatureRequest containinig - * information about the signature verification. + * information about the signature verification. * @return The result of the signature verification. * @throws MOAException An error occurred during signature verification. */ + @Override public VerifyXMLSignatureResponse verifyXMLSignature(VerifyXMLSignatureRequest request) - throws MOAException { + throws MOAException { - XMLSignatureVerificationInvoker invoker = - XMLSignatureVerificationInvoker.getInstance(); + final XMLSignatureVerificationInvoker invoker = + XMLSignatureVerificationInvoker.getInstance(); VerifyXMLSignatureResponse response; try { - Configurator.getInstance().init(); ServiceContextUtils.setUpContexts(); response = invoker.verifyXMLSignature(request); - + return response; } finally { ServiceContextUtils.tearDownContexts(); diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/TransformationFactory.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/TransformationFactory.java index 7842f14..1eec502 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/TransformationFactory.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/TransformationFactory.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.invoke; import java.util.ArrayList; @@ -30,14 +29,6 @@ import java.util.Iterator; import java.util.List; import java.util.Map; -import iaik.server.modules.xml.Base64Transformation; -import iaik.server.modules.xml.Canonicalization; -import iaik.server.modules.xml.EnvelopedSignatureTransformation; -import iaik.server.modules.xml.Transformation; -import iaik.server.modules.xml.XPath2Transformation; -import iaik.server.modules.xml.XPathTransformation; -import iaik.server.modules.xml.XSLTTransformation; - import at.gv.egovernment.moa.spss.MOAApplicationException; import at.gv.egovernment.moa.spss.api.common.ExclusiveCanonicalizationTransform; import at.gv.egovernment.moa.spss.api.common.Transform; @@ -53,41 +44,49 @@ import at.gv.egovernment.moa.spss.server.iaik.xml.XPath2FilterImpl; import at.gv.egovernment.moa.spss.server.iaik.xml.XPath2TransformationImpl; import at.gv.egovernment.moa.spss.server.iaik.xml.XPathTransformationImpl; import at.gv.egovernment.moa.spss.server.iaik.xml.XSLTTransformationImpl; +import iaik.server.modules.xml.Base64Transformation; +import iaik.server.modules.xml.Canonicalization; +import iaik.server.modules.xml.EnvelopedSignatureTransformation; +import iaik.server.modules.xml.Transformation; +import iaik.server.modules.xml.XPath2Transformation; +import iaik.server.modules.xml.XPathTransformation; +import iaik.server.modules.xml.XSLTTransformation; /** - * A factory to create Transformation objects from + * A factory to create Transformation objects from * Transform objects. - * + * * @author Patrick Peck * @version $Id$ */ public class TransformationFactory { - /** The single instance of this class. */ private static TransformationFactory instance = null; - /** Maps XPathFilter filter types to - * XPath2Transformation filter types. */ + /** + * Maps XPathFilter filter types to + * XPath2Transformation filter types. + */ private static Map FILTER_TYPE_MAPPING; static { FILTER_TYPE_MAPPING = new HashMap(); FILTER_TYPE_MAPPING.put( - XPathFilter.INTERSECT_TYPE, - XPath2Transformation.XPath2Filter.INTERSECTION); + XPathFilter.INTERSECT_TYPE, + XPath2Transformation.XPath2Filter.INTERSECTION); FILTER_TYPE_MAPPING.put( - XPathFilter.SUBTRACT_TYPE, - XPath2Transformation.XPath2Filter.SUBTRACTION); + XPathFilter.SUBTRACT_TYPE, + XPath2Transformation.XPath2Filter.SUBTRACTION); FILTER_TYPE_MAPPING.put( - XPathFilter.UNION_TYPE, - XPath2Transformation.XPath2Filter.UNION); + XPathFilter.UNION_TYPE, + XPath2Transformation.XPath2Filter.UNION); } /** * Get the single instance of the factory. - * + * * @return TransformationFactory The single instance. */ public static synchronized TransformationFactory getInstance() { @@ -99,37 +98,36 @@ public class TransformationFactory { /** * Create a new TransformationFactory. - * + * * Protected to disallow multiple instances. */ protected TransformationFactory() { } /** - * Create a Transformation based on a - * Transform object. - * - * @param transform The Transform object to extract - * transformation data from. - * @return The transformation contained in the transform + * Create a Transformation based on a Transform * object. + * + * @param transform The Transform object to extract transformation + * data from. + * @return The transformation contained in the transform object. * @throws MOAApplicationException An error occured creating the - * Transformation. See exception message for details. + * Transformation. See exception + * message for details. */ public Transformation createTransformation(Transform transform) - throws MOAApplicationException { - String algorithmUri = transform.getAlgorithmURI(); + throws MOAApplicationException { + final String algorithmUri = transform.getAlgorithmURI(); if (Canonicalization.CANONICAL_XML.equals(algorithmUri) - || Canonicalization.CANONICAL_XML_WITH_COMMENTS.equals(algorithmUri)) { + || Canonicalization.CANONICAL_XML_WITH_COMMENTS.equals(algorithmUri)) { return createC14nTransformation(algorithmUri); - } else if ( - Canonicalization.EXCLUSIVE_CANONICAL_XML.equals(algorithmUri) + } else if (Canonicalization.EXCLUSIVE_CANONICAL_XML.equals(algorithmUri) || Canonicalization.EXCLUSIVE_CANONICAL_XML_WITH_COMMENTS.equals( - algorithmUri)) { + algorithmUri)) { return createExclusiveC14nTransformation( - (ExclusiveCanonicalizationTransform) transform); + (ExclusiveCanonicalizationTransform) transform); } else if (Base64Transformation.ALL.contains(algorithmUri)) { return createBase64Transformation(); @@ -147,23 +145,24 @@ public class TransformationFactory { } /** - * Create a List of Transformations from a + * Create a List of Transformations from a * List of Transforms. - * - * @param transforms The List containing the - * Transforms. + * + * @param transforms The List containing the + * Transforms. * @return The List of Transformations corresponding - * to the transforms. + * to the transforms. * @throws MOAApplicationException An error occurred building one of the - * transformations. See exception message for details. + * transformations. See exception message for + * details. */ public List createTransformationList(List transforms) - throws MOAApplicationException { - List transformationList = new ArrayList(); + throws MOAApplicationException { + final List transformationList = new ArrayList(); Iterator trIter; for (trIter = transforms.iterator(); trIter.hasNext();) { - Transform transform = (Transform) trIter.next(); + final Transform transform = (Transform) trIter.next(); transformationList.add(createTransformation(transform)); } @@ -172,7 +171,7 @@ public class TransformationFactory { /** * Create a Canonicalization. - * + * * @param algorithmUri The algorithm URI of the canonicalization. * @return The Canonicalization. */ @@ -182,20 +181,20 @@ public class TransformationFactory { /** * Create a ExclusiveCanonicalization. - * - * @param transform The ExclusiveCanonicalizationTransform - * containing the transformation data. + * + * @param transform The ExclusiveCanonicalizationTransform + * containing the transformation data. * @return The ExclusiveCanonicalization. */ private Transformation createExclusiveC14nTransformation(ExclusiveCanonicalizationTransform transform) { return new ExclusiveCanonicalizationImpl( - transform.getAlgorithmURI(), - transform.getInclusiveNamespacePrefixes()); + transform.getAlgorithmURI(), + transform.getInclusiveNamespacePrefixes()); } /** * Create a Base64Transformation. - * + * * @return The */ private Transformation createBase64Transformation() { @@ -204,7 +203,7 @@ public class TransformationFactory { /** * Create an EnvelopedSignatureTransformation. - * + * * @return An EnvelopedSignatureTransformation. */ private Transformation createEnvelopedSignatureTransformation() { @@ -213,47 +212,47 @@ public class TransformationFactory { /** * Create an XPathTransformation. - * - * @param transform The Transform object containing the - * XPath transformation. - * @return An XPathTransformation corresponding the - * transformation given in transform. - * @throws MOAApplicationException An error occurred creating the - * Transformation. + * + * @param transform The Transform object containing the XPath + * transformation. + * @return An XPathTransformation corresponding the transformation + * given in transform. + * @throws MOAApplicationException An error occurred creating the + * Transformation. */ private Transformation createXPathTransformation(XPathTransform transform) - throws MOAApplicationException { + throws MOAApplicationException { return new XPathTransformationImpl( - transform.getXPathExpression(), - transform.getNamespaceDeclarations()); + transform.getXPathExpression(), + transform.getNamespaceDeclarations()); } /** * Create an XPath2Transformation. - * - * @param transform The Transform object containing the - * XPath filter transformation. - * @return An XPath2Transformation corresponding the - * transformation given in transform. + * + * @param transform The Transform object containing the XPath + * filter transformation. + * @return An XPath2Transformation corresponding the transformation + * given in transform. * @throws MOAApplicationException An error occurred creating the - * Transformation. + * Transformation. */ private Transformation createXPath2Transformation(XPathFilter2Transform transform) - throws MOAApplicationException { + throws MOAApplicationException { - XPath2TransformationImpl xpath2 = new XPath2TransformationImpl(); + final XPath2TransformationImpl xpath2 = new XPath2TransformationImpl(); Iterator iter; for (iter = transform.getFilters().iterator(); iter.hasNext();) { - XPathFilter filter = (XPathFilter) iter.next(); - String mappedFilterType = - (String) FILTER_TYPE_MAPPING.get(filter.getFilterType()); - XPath2FilterImpl mappedFilter = - new XPath2FilterImpl( - mappedFilterType, - filter.getXPathExpression(), - filter.getNamespaceDeclarations()); + final XPathFilter filter = (XPathFilter) iter.next(); + final String mappedFilterType = + (String) FILTER_TYPE_MAPPING.get(filter.getFilterType()); + final XPath2FilterImpl mappedFilter = + new XPath2FilterImpl( + mappedFilterType, + filter.getXPathExpression(), + filter.getNamespaceDeclarations()); xpath2.addXPathFilter(mappedFilter); } @@ -266,15 +265,15 @@ public class TransformationFactory { /** * Create an XSLTTransformation. - * + * * @param transform The Transform containing the XSLT stylesheet. * @return An XSLTTransformation corresponding the transformation - * given in transform. + * given in transform. * @throws MOAApplicationException An error occurred creating the - * Transformation. + * Transformation. */ private Transformation createXSLTTransformation(XSLTTransform transform) - throws MOAApplicationException { + throws MOAApplicationException { return new XSLTTransformationImpl(transform.getStylesheet()); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/VerifyCMSSignatureResponseBuilder.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/VerifyCMSSignatureResponseBuilder.java index 7ebea52..813d28e 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/VerifyCMSSignatureResponseBuilder.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/VerifyCMSSignatureResponseBuilder.java @@ -21,13 +21,8 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.invoke; -import iaik.server.modules.cmsverify.CMSSignatureVerificationResult; -import iaik.server.modules.pdfverify.PDFSignatureVerificationResult; -import iaik.server.cmspdfverify.CertificateValidationResult; - import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; @@ -41,28 +36,35 @@ import at.gv.egovernment.moa.spss.api.common.ExtendedCertificateCheckResult; import at.gv.egovernment.moa.spss.api.common.SignerInfo; import at.gv.egovernment.moa.spss.api.common.TslInfos; import at.gv.egovernment.moa.spss.server.config.TrustProfile; +import iaik.server.cmspdfverify.CertificateValidationResult; +import iaik.server.modules.cmsverify.CMSSignatureVerificationResult; +import iaik.server.modules.pdfverify.PDFSignatureVerificationResult; /** * A class to build a VerifyCMSSignatureResponse object. - * - *

Via subsequent calls to addResult() a number of results from - * a CMS signature verification can be added to the response.

- * - *

The getResponseElement() method then returns the - * VerifyCMSSignatureResponse built so far.

- * + * + *

+ * Via subsequent calls to addResult() a number of results from a + * CMS signature verification can be added to the response. + *

+ * + *

+ * The getResponseElement() method then returns the + * VerifyCMSSignatureResponse built so far. + *

+ * * @author Patrick Peck * @version $Id$ */ public class VerifyCMSSignatureResponseBuilder { /** The SPSSFactory for creating API objects. */ - private SPSSFactory factory = SPSSFactory.getInstance(); + private final SPSSFactory factory = SPSSFactory.getInstance(); /** The elements making up the response. */ - private List responseElements = new ArrayList(); + private final List responseElements = new ArrayList(); /** * Get the VerifyCMSSignatureResponse built so far. - * + * * @return The VerifyCMSSignatureResponse built so far. */ public VerifyCMSSignatureResponse getResponse() { @@ -71,141 +73,146 @@ public class VerifyCMSSignatureResponseBuilder { /** * Add a verification result to the response. - * - * @param result The result to add. - * @param trustprofile The actual trustprofile - * @param checkQCFromTSL true, if the TSL check verifies the - * certificate as qualified, otherwise false. - * @param checkSSCD true, if the TSL check verifies the - * signature based on a SSDC, otherwise false. - * @param sscdSourceTSL true, if the SSCD information comes from the TSL, - * otherwise false. - * @throws MOAException + * + * @param result The result to add. + * @param trustprofile The actual trustprofile + * @param checkQCFromTSL true, if the TSL check verifies the + * certificate as qualified, otherwise false. + * @param checkSSCD true, if the TSL check verifies the + * signature based on a SSDC, otherwise + * false. + * @param sscdSourceTSL true, if the SSCD information comes from + * the TSL, otherwise false. + * @throws MOAException */ - public void addResult(CMSSignatureVerificationResult result, TrustProfile trustProfile, boolean checkQC, boolean qcSourceTSL, boolean checkSSCD, boolean sscdSourceTSL, String issuerCountryCode, List adesResults, - ExtendedCertificateCheckResult extendedCertificateCheckResult, TslInfos tslInfos, boolean extendedVerification) - throws MOAException { - - - int signatureCheckCode = result.getSignatureValueVerificationCode().intValue(); - CertificateValidationResult certResult = result.getCertificateValidationResult(); - + public void addResult(CMSSignatureVerificationResult result, TrustProfile trustProfile, boolean checkQC, + boolean qcSourceTSL, boolean checkSSCD, boolean sscdSourceTSL, String issuerCountryCode, + List adesResults, + ExtendedCertificateCheckResult extendedCertificateCheckResult, TslInfos tslInfos, + boolean extendedVerification) + throws MOAException { + + final int signatureCheckCode = result.getSignatureValueVerificationCode().intValue(); + final CertificateValidationResult certResult = result.getCertificateValidationResult(); + VerifyCMSSignatureResponseElement responseElement; SignerInfo signerInfo = null; CheckResult signatureCheck; CheckResult certificateCheck; - boolean qualifiedCertificate = checkQC; - - //add signature algorithm name in case of extended validation + final boolean qualifiedCertificate = checkQC; + + // add signature algorithm name in case of extended validation String sigAlgName = null; if (extendedVerification) { - sigAlgName = result.getSignatureAlgorithmName(); - + sigAlgName = result.getSignatureAlgorithmName(); + } - - //set code 99 if not certcheckresult exists + + // set code 99 if not certcheckresult exists int certificateCheckCode = 99; if (certResult != null) { - certificateCheckCode = certResult.getValidationResultCode().intValue(); - - // add SignerInfo element - signerInfo = - factory.createSignerInfo( - (X509Certificate) certResult.getCertificateChain().get(0), - qualifiedCertificate, - qcSourceTSL, - certResult.isPublicAuthorityCertificate(), - certResult.getPublicAuthorityID(), - checkSSCD, - sscdSourceTSL, - issuerCountryCode, - result.getSigningTime(), - tslInfos); + certificateCheckCode = certResult.getValidationResultCode().intValue(); + + // add SignerInfo element + signerInfo = + factory.createSignerInfo( + (X509Certificate) certResult.getCertificateChain().get(0), + qualifiedCertificate, + qcSourceTSL, + certResult.isPublicAuthorityCertificate(), + certResult.getPublicAuthorityID(), + checkSSCD, + sscdSourceTSL, + issuerCountryCode, + result.getSigningTime(), + tslInfos); } - + // add SignatureCheck element signatureCheck = factory.createCheckResult(signatureCheckCode, null); // add CertificateCheck element certificateCheck = factory.createCheckResult(certificateCheckCode, null); - + // build the response element responseElement = - factory.createVerifyCMSSignatureResponseElement( - signerInfo, - signatureCheck, - certificateCheck, - adesResults, - extendedCertificateCheckResult, - sigAlgName, - null, - null); + factory.createVerifyCMSSignatureResponseElement( + signerInfo, + signatureCheck, + certificateCheck, + adesResults, + extendedCertificateCheckResult, + sigAlgName, + null, + null); responseElements.add(responseElement); } - -/** - * - * @param result - * @param trustProfile - * @param checkQC - * @param qcSourceTSL - * @param checkSSCD - * @param sscdSourceTSL - * @param issuerCountryCode - * @param adesResults - * @param extendedCertificateCheckResult - * @param tslInfos - * @param extendedVerification - * @throws MOAException - */ - public void addResult(PDFSignatureVerificationResult result, TrustProfile trustProfile, boolean checkQC, boolean qcSourceTSL, boolean checkSSCD, boolean sscdSourceTSL, String issuerCountryCode, List adesResults, - ExtendedCertificateCheckResult extendedCertificateCheckResult, TslInfos tslInfos, boolean extendedVerification) - throws MOAException { - - CertificateValidationResult certResult = - result.getCertificateValidationResult(); - int signatureCheckCode = - result.getSignatureValueVerificationCode().intValue(); - + + /** + * + * @param result + * @param trustProfile + * @param checkQC + * @param qcSourceTSL + * @param checkSSCD + * @param sscdSourceTSL + * @param issuerCountryCode + * @param adesResults + * @param extendedCertificateCheckResult + * @param tslInfos + * @param extendedVerification + * @throws MOAException + */ + public void addResult(PDFSignatureVerificationResult result, TrustProfile trustProfile, boolean checkQC, + boolean qcSourceTSL, boolean checkSSCD, boolean sscdSourceTSL, String issuerCountryCode, + List adesResults, + ExtendedCertificateCheckResult extendedCertificateCheckResult, TslInfos tslInfos, + boolean extendedVerification) + throws MOAException { + + final CertificateValidationResult certResult = + result.getCertificateValidationResult(); + final int signatureCheckCode = + result.getSignatureValueVerificationCode().intValue(); + VerifyCMSSignatureResponseElement responseElement; SignerInfo signerInfo = null; CheckResult signatureCheck; CheckResult certificateCheck; - boolean qualifiedCertificate = checkQC; - - //add signature algorithm name in case of extended validation + final boolean qualifiedCertificate = checkQC; + + // add signature algorithm name in case of extended validation String sigAlgName = null; Boolean coversFullDoc = null; int[] sigByteRange = null; - + if (extendedVerification) { - sigAlgName = result.getSignatureAlgorithmName(); - coversFullDoc = result.byteRangeCoversWholeDocument(); - sigByteRange = result.getByteRange(); - - } + sigAlgName = result.getSignatureAlgorithmName(); + coversFullDoc = result.byteRangeCoversWholeDocument(); + sigByteRange = result.getByteRange(); + } - //set code 99 if not certcheckresult exists + // set code 99 if not certcheckresult exists int certificateCheckCode = 99; if (certResult != null) { - certificateCheckCode = certResult.getValidationResultCode().intValue(); - - // add SignerInfo element - signerInfo = - factory.createSignerInfo( - (X509Certificate) certResult.getCertificateChain().get(0), - qualifiedCertificate, - qcSourceTSL, - certResult.isPublicAuthorityCertificate(), - certResult.getPublicAuthorityID(), - checkSSCD, - sscdSourceTSL, - issuerCountryCode, - result.getSigningTime(), - tslInfos); + certificateCheckCode = certResult.getValidationResultCode().intValue(); + + // add SignerInfo element + signerInfo = + factory.createSignerInfo( + (X509Certificate) certResult.getCertificateChain().get(0), + qualifiedCertificate, + qcSourceTSL, + certResult.isPublicAuthorityCertificate(), + certResult.getPublicAuthorityID(), + checkSSCD, + sscdSourceTSL, + issuerCountryCode, + result.getSigningTime(), + tslInfos); } // add SignatureCheck element @@ -213,18 +220,18 @@ public class VerifyCMSSignatureResponseBuilder { // add CertificateCheck element certificateCheck = factory.createCheckResult(certificateCheckCode, null); - + // build the response element responseElement = - factory.createVerifyCMSSignatureResponseElement( - signerInfo, - signatureCheck, - certificateCheck, - adesResults, - extendedCertificateCheckResult, - sigAlgName, - coversFullDoc, - sigByteRange); + factory.createVerifyCMSSignatureResponseElement( + signerInfo, + signatureCheck, + certificateCheck, + adesResults, + extendedCertificateCheckResult, + sigAlgName, + coversFullDoc, + sigByteRange); responseElements.add(responseElement); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/VerifyXMLSignatureResponseBuilder.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/VerifyXMLSignatureResponseBuilder.java index 22ef789..7e882ed 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/VerifyXMLSignatureResponseBuilder.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/VerifyXMLSignatureResponseBuilder.java @@ -21,16 +21,15 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.invoke; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.util.ArrayList; +import java.util.Date; import java.util.Iterator; import java.util.List; -import java.util.Date; import javax.xml.crypto.OctetStreamData; import javax.xml.crypto.dsig.CanonicalizationMethod; @@ -69,25 +68,28 @@ import iaik.server.modules.xmlverify.SecurityLayerManifest; import iaik.server.modules.xmlverify.XMLSignatureVerificationProfile; import iaik.server.modules.xmlverify.XMLSignatureVerificationResult; import iaik.x509.X509Certificate; -import iaik.xml.crypto.alg.transform.C14NTransformService; import iaik.xml.crypto.dsig.CanonicalizationMethodImpl; /** * A class to build a VerifyXMLSignatureResponse object. - * - *

Via a call to addResult() the only result of the - * signature verification must be added.

- * - *

The getResponseElement() method then returns the - * VerifyXMLSignatureResponse built so far.

- * + * + *

+ * Via a call to addResult() the only result of the signature + * verification must be added. + *

+ * + *

+ * The getResponseElement() method then returns the + * VerifyXMLSignatureResponse built so far. + *

+ * * @author Patrick Peck * @version $Id$ */ public class VerifyXMLSignatureResponseBuilder { /** The SPSSFactory for creating API objects. */ - private SPSSFactory factory = SPSSFactory.getInstance(); + private final SPSSFactory factory = SPSSFactory.getInstance(); /** Information about the signer certificate. */ private SignerInfo signerInfo; @@ -106,216 +108,203 @@ public class VerifyXMLSignatureResponseBuilder { private List adesFormResults = null; private ExtendedCertificateCheckResult extCheckResult = null; private Date signingTime; - + private String signatureAlgorithm = null; - + /** * Get the VerifyMLSignatureResponse built so far. - * + * * @return The VerifyXMLSignatureResponse built so far. */ public VerifyXMLSignatureResponse getResponse() { return factory.createVerifyXMLSignatureResponse( - signerInfo, - hashInputDatas, - referenceInputDatas, - signatureCheck, - signatureManifestCheck, - xmlDsigManifestChecks, - certificateCheck, - adesFormResults, - extCheckResult, - signatureAlgorithm); + signerInfo, + hashInputDatas, + referenceInputDatas, + signatureCheck, + signatureManifestCheck, + xmlDsigManifestChecks, + certificateCheck, + adesFormResults, + extCheckResult, + signatureAlgorithm); } - + public void setExtendedCertificateCheckResult(ExtendedCertificateCheckResult extCheckResult) { - this.extCheckResult = extCheckResult; + this.extCheckResult = extCheckResult; } - + public void setAdESFormResults(List adesForm) { - this.adesFormResults = adesForm; + this.adesFormResults = adesForm; } /** * Sets the verification result to the response. - * + * * This method must be called exactly once to ensure a valid * VerifyXMLSignatureResponse. - * - * @param result The result to set for the response. - * @param profile The profile used for verifying the signature. - * @param transformsSignatureManifestCheck The overall result for the signature - * manifest check. - * @param certificateCheck The overall result for the certificate check. - * @param checkQC true, if the certificate is QC, otherwise false. - * @param qcSourceTSL true, if the QC information comes from the TSL, - * otherwise false. - * @param checkSSCD true, if the signature is created by an SSCD, otherwise false. - * @param sscdSourceTSL true, if the SSCD information comes from the TSL, - * otherwise false. + * + * @param result The result to set for the response. + * @param profile The profile used for verifying the + * signature. + * @param transformsSignatureManifestCheck The overall result for the signature + * manifest check. + * @param certificateCheck The overall result for the + * certificate check. + * @param checkQC true, if the certificate + * is QC, otherwise false. + * @param qcSourceTSL true, if the QC + * information comes from the TSL, + * otherwise false. + * @param checkSSCD true, if the signature + * is created by an SSCD, otherwise + * false. + * @param sscdSourceTSL true, if the SSCD + * information comes from the TSL, + * otherwise false. * @throws MOAApplicationException An error occurred adding the result. */ public void setResult( - XMLSignatureVerificationResult result, - XMLSignatureVerificationProfile profile, - ReferencesCheckResult transformsSignatureManifestCheck, - CheckResult certificateCheck, - boolean checkQC, - boolean qcSourceTSL, - boolean checkSSCD, - boolean sscdSourceTSL, - boolean isTSLEnabledTrustprofile, - String issuerCountryCode, - TslInfos tslInfos, - boolean isExtendedValidation) - throws MOAApplicationException { - - CertificateValidationResult certResult = - result.getCertificateValidationResult(); + XMLSignatureVerificationResult result, + XMLSignatureVerificationProfile profile, + ReferencesCheckResult transformsSignatureManifestCheck, + CheckResult certificateCheck, + boolean checkQC, + boolean qcSourceTSL, + boolean checkSSCD, + boolean sscdSourceTSL, + boolean isTSLEnabledTrustprofile, + String issuerCountryCode, + TslInfos tslInfos, + boolean isExtendedValidation) + throws MOAApplicationException { + + final CertificateValidationResult certResult = + result.getCertificateValidationResult(); List referenceDataList; - ReferenceData referenceData; + final ReferenceData referenceData; List dsigManifestList; ReferencesCheckResultInfo checkResultInfo; int[] failedReferences; Iterator iter; boolean qualifiedCertificate = false; - + qualifiedCertificate = checkQC; - - if (isExtendedValidation) - signatureAlgorithm = result.getSignatureAlgorithmName(); - + + if (isExtendedValidation) { + signatureAlgorithm = result.getSignatureAlgorithmName(); + } + // create the SignerInfo; signerInfo = - factory.createSignerInfo( - (X509Certificate) certResult.getCertificateChain().get(0), - qualifiedCertificate, - qcSourceTSL, - certResult.isPublicAuthorityCertificate(), - certResult.getPublicAuthorityID(), - checkSSCD, - sscdSourceTSL, - issuerCountryCode, - result.getSigningTime(), - tslInfos); - - - - //TODO: add hash algo. infos + factory.createSignerInfo( + (X509Certificate) certResult.getCertificateChain().get(0), + qualifiedCertificate, + qcSourceTSL, + certResult.isPublicAuthorityCertificate(), + certResult.getPublicAuthorityID(), + checkSSCD, + sscdSourceTSL, + issuerCountryCode, + result.getSigningTime(), + tslInfos); + + // TODO: add hash algo. infos // Create HashInputData Content objects referenceDataList = result.getReferenceDataList(); if (profile.includeHashInputData()) { hashInputDatas = new ArrayList(); - + // Include SignedInfo references addHashInputDatas( - hashInputDatas, - referenceDataList, - InputData.CONTAINER_SIGNEDINFO_, - InputData.REFERER_NONE_); - + hashInputDatas, + referenceDataList, + InputData.CONTAINER_SIGNEDINFO_, + InputData.REFERER_NONE_); + // Include XMLDSIGManifest references - List xMLDSIGManifests = result.getDsigManifestList(); - for (iter = xMLDSIGManifests.iterator(); iter.hasNext();) - { - DsigManifest currentMF = (DsigManifest) iter.next(); - List xMLDSIGMFReferenceDataList = currentMF.getReferenceDataList(); + final List xMLDSIGManifests = result.getDsigManifestList(); + for (iter = xMLDSIGManifests.iterator(); iter.hasNext();) { + final DsigManifest currentMF = (DsigManifest) iter.next(); + final List xMLDSIGMFReferenceDataList = currentMF.getReferenceDataList(); addHashInputDatas( - hashInputDatas, - xMLDSIGMFReferenceDataList, - InputData.CONTAINER_XMLDSIGMANIFEST_, - currentMF.getReferringReferenceInfo().getReferenceIndex()); + hashInputDatas, + xMLDSIGMFReferenceDataList, + InputData.CONTAINER_XMLDSIGMANIFEST_, + currentMF.getReferringReferenceInfo().getReferenceIndex()); } } // Create the ReferenceInputData Content objects if (profile.includeReferenceInputData()) { referenceInputDatas = new ArrayList(); - + // Include SignedInfo references addReferenceInputDatas( - referenceInputDatas, - referenceDataList, - InputData.CONTAINER_SIGNEDINFO_, - InputData.REFERER_NONE_); + referenceInputDatas, + referenceDataList, + InputData.CONTAINER_SIGNEDINFO_, + InputData.REFERER_NONE_); // Include XMLDSIGManifest references - List xMLDSIGManifests = result.getDsigManifestList(); - for (iter = xMLDSIGManifests.iterator(); iter.hasNext();) - { - DsigManifest currentMF = (DsigManifest) iter.next(); - List xMLDSIGMFReferenceDataList = currentMF.getReferenceDataList(); + final List xMLDSIGManifests = result.getDsigManifestList(); + for (iter = xMLDSIGManifests.iterator(); iter.hasNext();) { + final DsigManifest currentMF = (DsigManifest) iter.next(); + final List xMLDSIGMFReferenceDataList = currentMF.getReferenceDataList(); addReferenceInputDatas( - referenceInputDatas, - xMLDSIGMFReferenceDataList, - InputData.CONTAINER_XMLDSIGMANIFEST_, - currentMF.getReferringReferenceInfo().getReferenceIndex()); + referenceInputDatas, + xMLDSIGMFReferenceDataList, + InputData.CONTAINER_XMLDSIGMANIFEST_, + currentMF.getReferringReferenceInfo().getReferenceIndex()); } } // create the signature check failedReferences = buildFailedReferences(result.getReferenceDataList()); checkResultInfo = - failedReferences != null - ? factory.createReferencesCheckResultInfo(null, failedReferences) - : null; + failedReferences != null + ? factory.createReferencesCheckResultInfo(null, failedReferences) + : null; signatureCheck = - factory.createReferencesCheckResult( - result.getSignatureValueVerificationCode().intValue(), - checkResultInfo); + factory.createReferencesCheckResult( + result.getSignatureValueVerificationCode().intValue(), + checkResultInfo); // create the signature manifest check - if (profile.checkSecurityLayerManifest()) - { - if (transformsSignatureManifestCheck.getCode() == 1) - { + if (profile.checkSecurityLayerManifest()) { + if (transformsSignatureManifestCheck.getCode() == 1) { // checking the transforms failed signatureManifestCheck = transformsSignatureManifestCheck; - } - else if (result.isSecurityLayerManifestRequired()) - { - if (!result.containsSecurityLayerManifest()) - { + } else if (result.isSecurityLayerManifestRequired()) { + if (!result.containsSecurityLayerManifest()) { // required security layer manifest is missing in signature signatureManifestCheck = factory.createReferencesCheckResult(2, null); - } - else - { + } else { // security layer manifest exists, so we have to check its validity - SecurityLayerManifest slManifest = result.getSecurityLayerManifest(); - int verificationResult = slManifest.getManifestVerificationResult().intValue(); + final SecurityLayerManifest slManifest = result.getSecurityLayerManifest(); + final int verificationResult = slManifest.getManifestVerificationResult().intValue(); - if (SecurityLayerManifest.CODE_MANIFEST_VALID.intValue() == verificationResult) - { + if (SecurityLayerManifest.CODE_MANIFEST_VALID.intValue() == verificationResult) { // security layer manifest exists and is free of errors signatureManifestCheck = factory.createReferencesCheckResult(0, null); - } - else - { + } else { // security layer manifest exists, but has errors failedReferences = buildFailedReferences(slManifest.getReferenceDataList()); - checkResultInfo = (failedReferences != null) - ? factory.createReferencesCheckResultInfo(null, failedReferences) - : null; - if (SecurityLayerManifest.CODE_MANIFEST_INCOMPLETE.intValue() == verificationResult) - { - signatureManifestCheck = factory.createReferencesCheckResult(3, checkResultInfo); - } - else if (SecurityLayerManifest.CODE_REFERENCE_HASH_INVALID.intValue() == verificationResult) - { - signatureManifestCheck = factory.createReferencesCheckResult(4, checkResultInfo); - } - else - { + checkResultInfo = failedReferences != null + ? factory.createReferencesCheckResultInfo(null, failedReferences) + : null; + if (SecurityLayerManifest.CODE_MANIFEST_INCOMPLETE.intValue() == verificationResult) { + signatureManifestCheck = factory.createReferencesCheckResult(3, checkResultInfo); + } else if (SecurityLayerManifest.CODE_REFERENCE_HASH_INVALID.intValue() == verificationResult) { + signatureManifestCheck = factory.createReferencesCheckResult(4, checkResultInfo); + } else { // Should not happen throw new RuntimeException("Unexpected result from security layer manifest verification."); } } } - } - else - { + } else { // no security layer manifest is required, so the signature manifest check is ok signatureManifestCheck = factory.createReferencesCheckResult(0, null); } @@ -326,172 +315,181 @@ public class VerifyXMLSignatureResponseBuilder { xmlDsigManifestChecks = new ArrayList(); dsigManifestList = result.getDsigManifestList(); for (iter = dsigManifestList.iterator(); iter.hasNext();) { - DsigManifest dsigManifest = (DsigManifest) iter.next(); - int refIndex = - dsigManifest.getReferringReferenceInfo().getReferenceIndex(); + final DsigManifest dsigManifest = (DsigManifest) iter.next(); + final int refIndex = + dsigManifest.getReferringReferenceInfo().getReferenceIndex(); ManifestRefsCheckResultInfo manifestCheckResultInfo; failedReferences = - buildFailedReferences(dsigManifest.getReferenceDataList()); + buildFailedReferences(dsigManifest.getReferenceDataList()); manifestCheckResultInfo = - factory.createManifestRefsCheckResultInfo( - null, - failedReferences, - refIndex); + factory.createManifestRefsCheckResultInfo( + null, + failedReferences, + refIndex); xmlDsigManifestChecks.add( - factory.createManifestRefsCheckResult( - dsigManifest.getManifestVerificationResult().intValue(), - manifestCheckResultInfo)); + factory.createManifestRefsCheckResult( + dsigManifest.getManifestVerificationResult().intValue(), + manifestCheckResultInfo)); } } - // create the certificate check + // create the certificate check this.certificateCheck = certificateCheck; - + this.signingTime = result.getSigningTime(); - + } /** - * Adds {@link InputData} entries to the specified inputDatas list. The content of the entry will - * be created from {@link ReferenceData#getHashInputData()}. - * - * @param inputDatas The list to be amended. - * - * @param referenceDataList The list of {@link ReferenceData} objects to be investigated. - * - * @param containerType The type of container of the {@link InputData} objects to be created. - * - * @param refererNumber The number of the referring reference for the {@link InputData} objects to be created. - * - * @throws MOAApplicationException if creating an {@link InputData} fails. + * Adds {@link InputData} entries to the specified inputDatas list. + * The content of the entry will be created from + * {@link ReferenceData#getHashInputData()}. + * + * @param inputDatas The list to be amended. + * + * @param referenceDataList The list of {@link ReferenceData} objects to be + * investigated. + * + * @param containerType The type of container of the {@link InputData} + * objects to be created. + * + * @param refererNumber The number of the referring reference for the + * {@link InputData} objects to be created. + * + * @throws MOAApplicationException if creating an {@link InputData} fails. */ - private void addHashInputDatas(List inputDatas, List referenceDataList, String containerType, int refererNumber) - throws MOAApplicationException - { - for (Iterator iter = referenceDataList.iterator(); iter.hasNext();) - { - ReferenceData referenceData = (ReferenceData) iter.next(); + private void addHashInputDatas(List inputDatas, List referenceDataList, String containerType, + int refererNumber) + throws MOAApplicationException { + for (final Object element : referenceDataList) { + final ReferenceData referenceData = (ReferenceData) element; inputDatas.add(buildInputData( - referenceData.getHashInputData(), - containerType, - refererNumber, - referenceData.getHashAlgorithmName())); + referenceData.getHashInputData(), + containerType, + refererNumber, + referenceData.getHashAlgorithmName())); } } - + /** - * Adds {@link InputData} entries to the specified inputDatas list. The content of the entry will - * be created from {@link ReferenceData#getReferenceInputData()}. - * - * @param inputDatas The list to be amended. - * - * @param referenceDataList The list of {@link ReferenceData} objects to be investigated. - * - * @param containerType The type of container of the {@link InputData} objects to be created. - * - * @param refererNumber The number of the referring reference for the {@link InputData} objects to be created. - * - * @throws MOAApplicationException if creating an {@link InputData} fails. + * Adds {@link InputData} entries to the specified inputDatas list. + * The content of the entry will be created from + * {@link ReferenceData#getReferenceInputData()}. + * + * @param inputDatas The list to be amended. + * + * @param referenceDataList The list of {@link ReferenceData} objects to be + * investigated. + * + * @param containerType The type of container of the {@link InputData} + * objects to be created. + * + * @param refererNumber The number of the referring reference for the + * {@link InputData} objects to be created. + * + * @throws MOAApplicationException if creating an {@link InputData} fails. */ - private void addReferenceInputDatas(List inputDatas, List referenceDataList, String containerType, int refererNumber) - throws MOAApplicationException - { - for (Iterator iter = referenceDataList.iterator(); iter.hasNext();) - { - ReferenceData referenceData = (ReferenceData) iter.next(); + private void addReferenceInputDatas(List inputDatas, List referenceDataList, String containerType, + int refererNumber) + throws MOAApplicationException { + for (final Object element : referenceDataList) { + final ReferenceData referenceData = (ReferenceData) element; inputDatas.add(buildInputData( - referenceData.getReferenceInputData(), - containerType, - refererNumber, - referenceData.getHashAlgorithmName())); + referenceData.getReferenceInputData(), + containerType, + refererNumber, + referenceData.getHashAlgorithmName())); } } /** * Build a InputDataBinaryImpl or an InputDataXMLImpl * object from the given DataObject and the given attributes. - * - * @param dataObject The DataObject from which to build the result. - * Based on the type of this parameter, the type of the result will either be - * InputDataBinaryImpl or InputDataXMLImpl. - * - * @param partof see {@link InputData} - * + * + * @param dataObject The DataObject from which to + * build the result. Based on the type of this + * parameter, the type of the result will either + * be InputDataBinaryImpl or + * InputDataXMLImpl. + * + * @param partof see {@link InputData} + * * @param referringReferenceNumber see {@link InputData} - * - * @param hashAlg see {@link InputData} - * - * @return The corresponinding input data implementation. + * + * @param hashAlg see {@link InputData} + * + * @return The corresponinding input data implementation. * @throws MOAApplicationException An error occurred creating the result. */ - private Content buildInputData(DataObject dataObject, String partOf, int referringReferenceNumber, String hashAlg) - throws MOAApplicationException { + private Content buildInputData(DataObject dataObject, String partOf, int referringReferenceNumber, + String hashAlg) + throws MOAApplicationException { if (dataObject instanceof BinaryDataObject) { - BinaryDataObject binaryData = (BinaryDataObject) dataObject; + final BinaryDataObject binaryData = (BinaryDataObject) dataObject; return new InputDataBinaryImpl( - factory.createContent(binaryData.getInputStream(), null), - partOf, - referringReferenceNumber, - hashAlg); + factory.createContent(binaryData.getInputStream(), null), + partOf, + referringReferenceNumber, + hashAlg); } else if (dataObject instanceof XMLDataObject) { - XMLDataObject xmlData = (XMLDataObject) dataObject; - List nodes = new ArrayList(); + final XMLDataObject xmlData = (XMLDataObject) dataObject; + final List nodes = new ArrayList(); nodes.add(xmlData.getElement()); return new InputDataXMLImpl( - factory.createContent(new NodeListAdapter(nodes), null), - partOf, - referringReferenceNumber, - hashAlg); + factory.createContent(new NodeListAdapter(nodes), null), + partOf, + referringReferenceNumber, + hashAlg); } else { // dataObject instanceof XMLNodeListDataObject // if the data in the NodeList can be converted back to valid XML, - // write it as XMLContent; otherwise, write it as Base64Content - XMLNodeListDataObject nodeData = (XMLNodeListDataObject) dataObject; - NodeList nodes = nodeData.getNodeList(); - + // write it as XMLContent; otherwise, write it as Base64Content + final XMLNodeListDataObject nodeData = (XMLNodeListDataObject) dataObject; + final NodeList nodes = nodeData.getNodeList(); + if (DOMUtils.checkAttributeParentsInNodeList(nodes)) { // insert as XMLContent try { - DocumentFragment fragment = DOMUtils.nodeList2DocumentFragment(nodes); + final DocumentFragment fragment = DOMUtils.nodeList2DocumentFragment(nodes); return new InputDataXMLImpl( - factory.createContent(fragment.getChildNodes(), null), - partOf, - referringReferenceNumber, - hashAlg); - } catch (Exception e) { + factory.createContent(fragment.getChildNodes(), null), + partOf, + referringReferenceNumber, + hashAlg); + } catch (final Exception e) { // not successful -> fall through to the Base64Content } } - + // insert canonicalized NodeList as binary content try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - for(int i = 0; i < nodes.getLength(); i++) { - baos.write(DOMUtils.nodeToByteArray(nodes.item(i))); - } - baos.close(); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - OctetStreamData inputData = new OctetStreamData(bais); - - CanonicalizationMethodImpl canonicalizationMethodImpl = new CanonicalizationMethodImpl( - CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, new ExcC14NParameterSpec()); - OctetStreamData data = (OctetStreamData)canonicalizationMethodImpl.transform(inputData, null); - bais.close(); - //CanonicalizationAlgorithm c14n = - //new CanonicalizationAlgorithmImplExclusiveCanonicalXMLWithComments(); - InputStream is = data.getOctetStream(); - - //c14n.setInput(nodes); - //is = c14n.canonicalize(); + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + for (int i = 0; i < nodes.getLength(); i++) { + baos.write(DOMUtils.nodeToByteArray(nodes.item(i))); + } + baos.close(); + final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + final OctetStreamData inputData = new OctetStreamData(bais); + + final CanonicalizationMethodImpl canonicalizationMethodImpl = new CanonicalizationMethodImpl( + CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, new ExcC14NParameterSpec()); + final OctetStreamData data = (OctetStreamData) canonicalizationMethodImpl.transform(inputData, null); + bais.close(); + // CanonicalizationAlgorithm c14n = + // new CanonicalizationAlgorithmImplExclusiveCanonicalXMLWithComments(); + final InputStream is = data.getOctetStream(); + + // c14n.setInput(nodes); + // is = c14n.canonicalize(); return new InputDataBinaryImpl( - factory.createContent(is, null), - partOf, - referringReferenceNumber, - hashAlg); - } catch (Exception e) { + factory.createContent(is, null), + partOf, + referringReferenceNumber, + hashAlg); + } catch (final Exception e) { throw new MOAApplicationException("2200", null); } } @@ -499,27 +497,27 @@ public class VerifyXMLSignatureResponseBuilder { /** * Build the failed references. - * + * * Failed references are references for which the isHashValid() * method returns false. - * - * @param refInfos A List containing the - * ReferenceInfo objects to be checked. - * @return The indexes of the failed references. + * + * @param refInfos A List containing the ReferenceInfo + * objects to be checked. + * @return The indexes of the failed references. */ private int[] buildFailedReferences(List refInfos) { - List failedReferencesList = new ArrayList(); + final List failedReferencesList = new ArrayList(); int i; // find out the failed references for (i = 0; i < refInfos.size(); i++) { - ReferenceInfo refInfo = (ReferenceInfo) refInfos.get(i); + final ReferenceInfo refInfo = (ReferenceInfo) refInfos.get(i); try { if (refInfo.isHashCalculated() && !refInfo.isHashValid()) { failedReferencesList.add(new Integer(i + 1)); } - } catch (HashUnavailableException e) { + } catch (final HashUnavailableException e) { // nothing to do here because we called refInfo.isHashCalculated first } } @@ -528,7 +526,7 @@ public class VerifyXMLSignatureResponseBuilder { if (failedReferencesList.isEmpty()) { return null; } else { - int[] failedReferences = CollectionUtils.toIntArray(failedReferencesList); + final int[] failedReferences = CollectionUtils.toIntArray(failedReferencesList); return failedReferences; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/XMLSignatureCreationInvoker.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/XMLSignatureCreationInvoker.java index ecdd811..e039cb9 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/XMLSignatureCreationInvoker.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/XMLSignatureCreationInvoker.java @@ -21,18 +21,8 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.invoke; -import iaik.server.modules.IAIKException; -import iaik.server.modules.IAIKRuntimeException; -import iaik.server.modules.xml.DataObject; -import iaik.server.modules.xml.XMLDataObject; -import iaik.server.modules.xml.XMLSignature; -import iaik.server.modules.xmlsign.XMLSignatureCreationModule; -import iaik.server.modules.xmlsign.XMLSignatureCreationModuleFactory; -import iaik.server.modules.xmlsign.XMLSignatureCreationProfile; - import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -71,17 +61,25 @@ import at.gv.egovernment.moaspss.logging.LoggingContext; import at.gv.egovernment.moaspss.logging.LoggingContextManager; import at.gv.egovernment.moaspss.util.Constants; import at.gv.egovernment.moaspss.util.XPathUtils; +import iaik.server.modules.IAIKException; +import iaik.server.modules.IAIKRuntimeException; +import iaik.server.modules.xml.DataObject; +import iaik.server.modules.xml.XMLDataObject; +import iaik.server.modules.xml.XMLSignature; +import iaik.server.modules.xmlsign.XMLSignatureCreationModule; +import iaik.server.modules.xmlsign.XMLSignatureCreationModuleFactory; +import iaik.server.modules.xmlsign.XMLSignatureCreationProfile; /** * A class providing an API based interface to the * XMLSignatureCreationModule. - * - * This class performs the invocation of the + * + * This class performs the invocation of the * iaik.server.modules.xmlsign.XMLSignatureCreationModule from a * CreateXMLSignatureRequest given as an API object. The result of * the invocation is integrated into a CreateXMLSignatureResponse * and returned. - * + * * @author Patrick Peck * @version $Id$ */ @@ -92,7 +90,7 @@ public class XMLSignatureCreationInvoker { /** * Get the only instance of this class. - * + * * @return The only instance of this class. */ public static synchronized XMLSignatureCreationInvoker getInstance() { @@ -104,7 +102,7 @@ public class XMLSignatureCreationInvoker { /** * Create a new XMLSignatureCreationInvoker. - * + * * Protected to disallow multiple instances. */ protected XMLSignatureCreationInvoker() { @@ -114,31 +112,31 @@ public class XMLSignatureCreationInvoker { * Process the CreateXMLSignatureRequest message and invoke the * XMLSignatureCreationModule for every * SingleSignatureInfo contained in the request. - * + * * @param request A CreateXMLSignatureRequest API object * containing the information for creating the signature(s). - * @param reserved A Set of reserved object IDs. - * - * @return A CreateXMLSignatureResponse API object containing - * the created signature(s). The response contains either a - * SignatureEnvironment or a ErrorResponse - * for each SingleSignatureInfo in the request. - * @throws MOAException An error occurred during signature creation. + * @param reserved A Set of reserved object IDs. + * + * @return A CreateXMLSignatureResponse API object containing the + * created signature(s). The response contains either a + * SignatureEnvironment or a ErrorResponse for + * each SingleSignatureInfo in the request. + * @throws MOAException An error occurred during signature creation. */ public CreateXMLSignatureResponse createXMLSignature( - CreateXMLSignatureRequest request, - Set reserved) - throws MOAException { - - TransactionContext context = - TransactionContextManager.getInstance().getTransactionContext(); - LoggingContext loggingCtx = - LoggingContextManager.getInstance().getLoggingContext(); + CreateXMLSignatureRequest request, + Set reserved) + throws MOAException { + + final TransactionContext context = + TransactionContextManager.getInstance().getTransactionContext(); + final LoggingContext loggingCtx = + LoggingContextManager.getInstance().getLoggingContext(); reserved = new HashSet(reserved); - XMLSignatureCreationProfileFactory profileFactory = - new XMLSignatureCreationProfileFactory(request, reserved); - CreateXMLSignatureResponseBuilder responseBuilder = - new CreateXMLSignatureResponseBuilder(); + final XMLSignatureCreationProfileFactory profileFactory = + new XMLSignatureCreationProfileFactory(request, reserved); + final CreateXMLSignatureResponseBuilder responseBuilder = + new CreateXMLSignatureResponseBuilder(); int createCount = 1; IdGenerator refIdGen; XMLSignatureCreationModule module; @@ -153,8 +151,8 @@ public class XMLSignatureCreationInvoker { // iterate over all the SingleSignatureInfo elements in the request while (singleSignatureInfoIter.hasNext()) { - SingleSignatureInfo singleSignatureInfo = - (SingleSignatureInfo) singleSignatureInfoIter.next(); + final SingleSignatureInfo singleSignatureInfo = + (SingleSignatureInfo) singleSignatureInfoIter.next(); CreateSignatureInfo createSignatureInfo; List dataObjectList; XMLSignatureCreationProfile profile; @@ -170,44 +168,47 @@ public class XMLSignatureCreationInvoker { // build the signature environment createSignatureInfo = singleSignatureInfo.getCreateSignatureInfo(); if (createSignatureInfo != null) { - DataObjectFactory dataObjFactory = DataObjectFactory.getInstance(); + final DataObjectFactory dataObjFactory = DataObjectFactory.getInstance(); signatureEnvironment = - dataObjFactory.createSignatureEnvironment( - createSignatureInfo.getCreateSignatureEnvironment(), - getCreateSignatureEnvironmentProfileSupplements(singleSignatureInfo)); + dataObjFactory.createSignatureEnvironment( + createSignatureInfo.getCreateSignatureEnvironment(), + getCreateSignatureEnvironmentProfileSupplements(singleSignatureInfo)); } else { signatureEnvironment = null; } - - HashSet sigInfoReservedIDs = new HashSet(); - if (signatureEnvironment != null) - { + + final HashSet sigInfoReservedIDs = new HashSet(); + if (signatureEnvironment != null) { // Find Id attributes of existing XML signatures in signature environment - HashMap nSMap = new HashMap(); - String dsp = Constants.DSIG_PREFIX; - nSMap.put(dsp, Constants.DSIG_NS_URI); - String xPathExpr = "//" + dsp + ":Signature/@Id | //" + dsp + ":Reference/@Id | //" - + dsp + ":Object/@Id | //" + dsp + ":Manifest/@Id"; - NodeList idAttrs = XPathUtils.selectNodeList(signatureEnvironment.getElement(), nSMap, xPathExpr); - - // Add found Id attributes to set of reserved IDs - for (int i = 0; i < idAttrs.getLength(); i++) sigInfoReservedIDs.add(idAttrs.item(i).getNodeValue()); + final HashMap nSMap = new HashMap(); + final String dsp = Constants.DSIG_PREFIX; + nSMap.put(dsp, Constants.DSIG_NS_URI); + final String xPathExpr = "//" + dsp + ":Signature/@Id | //" + dsp + ":Reference/@Id | //" + + dsp + ":Object/@Id | //" + dsp + ":Manifest/@Id"; + final NodeList idAttrs = XPathUtils.selectNodeList(signatureEnvironment.getElement(), nSMap, + xPathExpr); + + // Add found Id attributes to set of reserved IDs + for (int i = 0; i < idAttrs.getLength(); i++) { + sigInfoReservedIDs.add(idAttrs.item(i).getNodeValue()); + } } // create the reference id generator - HashSet allReservedIDs = new HashSet(reserved); + final HashSet allReservedIDs = new HashSet(reserved); allReservedIDs.addAll(sigInfoReservedIDs); refIdGen = new IdGenerator("reference-" + createCount++, allReservedIDs); // build the list of DataObjects - List createTransformsProfiles = profileFactory.getCreateTransformsInfoProfiles(singleSignatureInfo); + final List createTransformsProfiles = profileFactory.getCreateTransformsInfoProfiles( + singleSignatureInfo); dataObjectList = - buildDataObjectList( - singleSignatureInfo, - createTransformsProfiles, - signatureEnvironment, - refIdGen); + buildDataObjectList( + singleSignatureInfo, + createTransformsProfiles, + signatureEnvironment, + refIdGen); // build the XMLSignatureCreationProfile profile = profileFactory.createProfile(singleSignatureInfo, sigInfoReservedIDs); @@ -218,78 +219,78 @@ public class XMLSignatureCreationInvoker { // build the signatureParentElement if (signatureEnvironment != null) { signatureParent = - buildSignatureParentElement( - signatureEnvironment.getElement(), - singleSignatureInfo); + buildSignatureParentElement( + signatureEnvironment.getElement(), + singleSignatureInfo); } else { signatureParent = null; } - // make the signature environment the root of the document, if it is - // not a separate document anyway; this is done to assure that - // canonicalization of the signature environment contains the correct + // make the signature environment the root of the document, if it is + // not a separate document anyway; this is done to assure that + // canonicalization of the signature environment contains the correct // namespace declarations if (signatureEnvironment != null) { - Document requestDoc = - signatureEnvironment.getElement().getOwnerDocument(); + final Document requestDoc = + signatureEnvironment.getElement().getOwnerDocument(); requestElement = requestDoc.getDocumentElement(); if (requestElement != signatureEnvironment.getElement()) { signatureEnvironmentParent = - signatureEnvironment.getElement().getParentNode(); + signatureEnvironment.getElement().getParentNode(); requestElement.getOwnerDocument().replaceChild( - signatureEnvironment.getElement(), - requestElement); + signatureEnvironment.getElement(), + requestElement); } } try { - ConfigurationProvider config = context.getConfiguration(); - String xadesVersion = config.getXAdESVersion(); - - if (xadesVersion!= null && xadesVersion.compareTo(XMLSignatureCreationModule.XADES_VERSION_1_4_2) == 0) { - // create the signature (XAdES 1.4.2) - signature = - module.createSignature( + final ConfigurationProvider config = context.getConfiguration(); + final String xadesVersion = config.getXAdESVersion(); + + if (xadesVersion != null && xadesVersion.compareTo( + XMLSignatureCreationModule.XADES_VERSION_1_4_2) == 0) { + // create the signature (XAdES 1.4.2) + signature = + module.createSignature( dataObjectList, profile, additionalSignedProperties, signatureParent, XMLSignatureCreationModule.XADES_VERSION_1_4_2, new TransactionId(context.getTransactionID())); - } - else { - // create the signature (XAdES 1.1.1 = default) - signature = - module.createSignature( + } else { + // create the signature (XAdES 1.1.1 = default) + signature = + module.createSignature( dataObjectList, profile, additionalSignedProperties, signatureParent, XMLSignatureCreationModule.XADES_VERSION_1_1_1, new TransactionId(context.getTransactionID())); - } + } // insert the result into the response if (signatureParent != null) { responseBuilder.addSignatureEnvironment( - signatureEnvironment.getElement()); + signatureEnvironment.getElement()); } else { responseBuilder.addSignatureEnvironment(signature.getElement()); } - } catch (IAIKException e) { - MOAException moaException = IaikExceptionMapper.getInstance().map(e); + } catch (final IAIKException e) { + final MOAException moaException = IaikExceptionMapper.getInstance().map(e); responseBuilder.addError( - moaException.getMessageId(), - moaException.getMessage()); + moaException.getMessageId(), + moaException.getMessage()); Logger.warn(moaException.getMessage(), e); - } catch (IAIKRuntimeException e) { - MOAException moaException = IaikExceptionMapper.getInstance().map(e); + } catch (final IAIKRuntimeException e) { + final MOAException moaException = IaikExceptionMapper.getInstance().map(e); responseBuilder.addError( - moaException.getMessageId(), - moaException.getMessage()); + moaException.getMessageId(), + moaException.getMessage()); Logger.warn(moaException.getMessage(), e); } @@ -297,14 +298,14 @@ public class XMLSignatureCreationInvoker { if (signatureEnvironment != null) { if (requestElement != signatureEnvironment.getElement()) { requestElement.getOwnerDocument().replaceChild( - requestElement, - signatureEnvironment.getElement()); + requestElement, + signatureEnvironment.getElement()); signatureEnvironmentParent.appendChild( - signatureEnvironment.getElement()); + signatureEnvironment.getElement()); } } - } catch (MOAException e) { + } catch (final MOAException e) { responseBuilder.addError(e.getMessageId(), e.getMessage()); Logger.warn(e.getMessage(), e); } @@ -317,85 +318,88 @@ public class XMLSignatureCreationInvoker { /** * Build the list of DataObjects from the given * SingleSignatureInfo object. - * + * *

- * Only the following cases of DataObjects are - * valid in case of an enveloping signature: - * + * Only the following cases of DataObjects are valid in case of an + * enveloping signature: + * *

    - *
  • Reference == null && Content != null: The + *
  • Reference == null && Content != null: The * Content will be used in the DataObject.
  • *
  • Reference != null && Content == null: Resolve the - * Reference and use it as DataObject. - * Set the Reference in the DataObject as well.
  • + * Reference and use it as DataObject. Set the + * Reference in the DataObject as well. *
*

- * + * *

- * Only the following cases of DataObjects are valid in case - * of a detached signature: - * + * Only the following cases of DataObjects are valid in case of a + * detached signature: + * *

    *
  • Reference != null && Content == null: Resolve the - * Reference and use it as DataObject. - * Set the Reference in the DataObject as well.
  • + * Reference and use it as DataObject. Set the + * Reference in the DataObject as well. *
  • Reference != null && Content != null: The - * Content will be used in the DataObject. - * Set the Reference in the DataObject as well.
  • + * Content will be used in the DataObject. Set the + * Reference in the DataObject as well. *
*

- * + * *

* All other cases will lead to an error. *

- * - * @param singleSignatureInfo The SingleSignatureInfo object - * containing the DataObjectInfo objects. - * @param createTransformsProfiles A list of objects of type {@link CreateTransformsInfoProfileExplicit}, - * each representing the transforms info profile information for the corresponding DataObject. - * @param signatureEnvironment The - * @param idGen The ID generator for DataObject references. + * + * @param singleSignatureInfo The SingleSignatureInfo object + * containing the DataObjectInfo + * objects. + * @param createTransformsProfiles A list of objects of type + * {@link CreateTransformsInfoProfileExplicit}, + * each representing the transforms info profile + * information for the corresponding + * DataObject. + * @param signatureEnvironment The + * @param idGen The ID generator for DataObject + * references. * @return The List of DataObjects contained in the - * given singleSignatureInfo. - * @throws MOASystemException A system error occurred building the data - * objects. - * @throws MOAApplicationException An error occurred building the data - * objects. + * given singleSignatureInfo. + * @throws MOASystemException A system error occurred building the data + * objects. + * @throws MOAApplicationException An error occurred building the data objects. */ private List buildDataObjectList( - SingleSignatureInfo singleSignatureInfo, - List createTransformsProfiles, - XMLDataObject signatureEnvironment, - IdGenerator idGen) - throws MOASystemException, MOAApplicationException { - - List dataObjInfos = singleSignatureInfo.getDataObjectInfos(); - List dataObjects = new ArrayList(); + SingleSignatureInfo singleSignatureInfo, + List createTransformsProfiles, + XMLDataObject signatureEnvironment, + IdGenerator idGen) + throws MOASystemException, MOAApplicationException { + + final List dataObjInfos = singleSignatureInfo.getDataObjectInfos(); + final List dataObjects = new ArrayList(); Iterator dtIter; - Iterator ctpIter = createTransformsProfiles.iterator(); + final Iterator ctpIter = createTransformsProfiles.iterator(); - for (dtIter = dataObjInfos.iterator(); dtIter.hasNext();) - { - DataObjectInfo dataObjInfo = (DataObjectInfo) dtIter.next(); - String structure = dataObjInfo.getStructure(); - - CreateTransformsInfoProfileExplicit transformsProfile = - (CreateTransformsInfoProfileExplicit) ctpIter.next(); - MetaInfo finalDataMetaInfo = transformsProfile.getCreateTransformsInfo().getFinalDataMetaInfo(); + for (dtIter = dataObjInfos.iterator(); dtIter.hasNext();) { + final DataObjectInfo dataObjInfo = (DataObjectInfo) dtIter.next(); + final String structure = dataObjInfo.getStructure(); + + final CreateTransformsInfoProfileExplicit transformsProfile = + (CreateTransformsInfoProfileExplicit) ctpIter.next(); + final MetaInfo finalDataMetaInfo = transformsProfile.getCreateTransformsInfo().getFinalDataMetaInfo(); if (DataObjectInfo.STRUCTURE_ENVELOPING.equals(structure)) { dataObjects.add( - buildEnvelopingDataObject( - dataObjInfo.getDataObject(), - finalDataMetaInfo, - idGen.uniqueId())); + buildEnvelopingDataObject( + dataObjInfo.getDataObject(), + finalDataMetaInfo, + idGen.uniqueId())); } else if (DataObjectInfo.STRUCTURE_DETACHED.equals(structure)) { dataObjects.add( - buildDetachedDataObject( - dataObjInfo.getDataObject(), - finalDataMetaInfo, - signatureEnvironment, - idGen.uniqueId())); + buildDetachedDataObject( + dataObjInfo.getDataObject(), + finalDataMetaInfo, + signatureEnvironment, + idGen.uniqueId())); } else { throw new MOAApplicationException("1103", new Object[] { structure }); } @@ -406,126 +410,128 @@ public class XMLSignatureCreationInvoker { } /** - * Build a DataObject to be used in an enveloping - * signature. - * - * @param content The Content object containing the data object. - * ContentOptionalRefType. - * @param finalDataMetaInfo The meta information corresponding with content. - * @param referenceID The reference ID to use in the signature for the - * DataObject created. + * Build a DataObject to be used in an enveloping signature. + * + * @param content The Content object containing the data + * object. ContentOptionalRefType. + * @param finalDataMetaInfo The meta information corresponding with + * content. + * @param referenceID The reference ID to use in the signature for the + * DataObject created. * @return The DataObject representing the data contained in - * dataObjectElem. - * @throws MOAApplicationException An error occurred during the creation of - * the DataObject. - * @throws MOASystemException A system error occurred during the creation of - * the DataObject. + * dataObjectElem. + * @throws MOAApplicationException An error occurred during the creation of the + * DataObject. + * @throws MOASystemException A system error occurred during the creation + * of the DataObject. */ private DataObject buildEnvelopingDataObject( - Content content, - MetaInfo finalDataMetaInfo, - String referenceID) - throws MOASystemException, MOAApplicationException { + Content content, + MetaInfo finalDataMetaInfo, + String referenceID) + throws MOASystemException, MOAApplicationException { - DataObjectFactory factory = DataObjectFactory.getInstance(); + final DataObjectFactory factory = DataObjectFactory.getInstance(); DataObject dataObject; dataObject = - factory.createFromContentOptionalRefType( - content, - finalDataMetaInfo, - referenceID, - false, - false, - true, - false); + factory.createFromContentOptionalRefType( + content, + finalDataMetaInfo, + referenceID, + false, + false, + true, + false); return dataObject; } /** * Build a DataObject to be used in a detached signature. - * - * @param content The Content object containing an the data. - * @param finalDataMetaInfo The meta information corresponding with content. + * + * @param content The Content object containing an the + * data. + * @param finalDataMetaInfo The meta information corresponding with + * content. * @param signatureEnvironment The signature environment where the signature - * will be inserted. - * @param referenceID The reference ID to use in the signature for the - * DataObject created. + * will be inserted. + * @param referenceID The reference ID to use in the signature for the + * DataObject created. * @return The DataObject representing the data contained in - * dataObjectElem. - * @throws MOAApplicationException An error occurred during the creation of - * the DataObject. - * @throws MOASystemException A system error occurred during the creation of - * the DataObject. + * dataObjectElem. + * @throws MOAApplicationException An error occurred during the creation of the + * DataObject. + * @throws MOASystemException A system error occurred during the creation + * of the DataObject. */ private DataObject buildDetachedDataObject( - Content content, - MetaInfo finalDataMetaInfo, - XMLDataObject signatureEnvironment, - String referenceID) - throws MOASystemException, MOAApplicationException { - - String reference = content.getReference(); - DataObjectFactory factory = DataObjectFactory.getInstance(); + Content content, + MetaInfo finalDataMetaInfo, + XMLDataObject signatureEnvironment, + String referenceID) + throws MOASystemException, MOAApplicationException { + + final String reference = content.getReference(); + final DataObjectFactory factory = DataObjectFactory.getInstance(); DataObject dataObject; if (reference == null) { throw new MOAApplicationException("1102", null); } else if ("".equals(reference) || reference.startsWith("#")) { dataObject = - factory.createFromSignatureEnvironment( - signatureEnvironment.getElement(), - reference, - referenceID); + factory.createFromSignatureEnvironment( + signatureEnvironment.getElement(), + reference, + referenceID); } else { dataObject = - factory.createFromContentOptionalRefType( - content, - finalDataMetaInfo, - referenceID, - true, - false, - true, - false); + factory.createFromContentOptionalRefType( + content, + finalDataMetaInfo, + referenceID, + true, + false, + true, + false); } return dataObject; } /** * Build the signature parent element. - * - * @param signatureEnvironment The signature environment containing the - * document in which to insert the signature. - * @param singleSignatureInfo The SingleSignatureInfo - * containing the signature parent element. - * @return An XMLDataObject containing the signature parent - * element or null, if the CreateSignatureInfo is - * null. - * @throws MOAApplicationException An error occurred during the creation of - * the signature parent. + * + * @param signatureEnvironment The signature environment containing the document + * in which to insert the signature. + * @param singleSignatureInfo The SingleSignatureInfo containing + * the signature parent element. + * @return An XMLDataObject containing the signature parent element + * or null, if the CreateSignatureInfo is + * null. + * @throws MOAApplicationException An error occurred during the creation of the + * signature parent. */ private XMLDataObject buildSignatureParentElement( - Element signatureEnvironment, - SingleSignatureInfo singleSignatureInfo) - throws MOAApplicationException { + Element signatureEnvironment, + SingleSignatureInfo singleSignatureInfo) + throws MOAApplicationException { - CreateSignatureInfo createInfo = - singleSignatureInfo.getCreateSignatureInfo(); + final CreateSignatureInfo createInfo = + singleSignatureInfo.getCreateSignatureInfo(); // evaluate the CreateSignatureLocation if (createInfo != null) { - TransactionContext context = - TransactionContextManager.getInstance().getTransactionContext(); - ConfigurationProvider config = context.getConfiguration(); - CreateSignatureEnvironmentProfileExplicit createProfile = - ProfileMapper.mapCreateSignatureEnvironmentProfile( - createInfo.getCreateSignatureEnvironmentProfile(), - config); - CreateSignatureLocation location = - createProfile.getCreateSignatureLocation(); - Element signatureParent = - InvokerUtils.evaluateSignatureLocation(signatureEnvironment, location); + final TransactionContext context = + TransactionContextManager.getInstance().getTransactionContext(); + final ConfigurationProvider config = context.getConfiguration(); + final CreateSignatureEnvironmentProfileExplicit createProfile = + ProfileMapper.mapCreateSignatureEnvironmentProfile( + createInfo.getCreateSignatureEnvironmentProfile(), + config); + final CreateSignatureLocation location = + createProfile.getCreateSignatureLocation(); + final Element signatureParent = + InvokerUtils.evaluateSignatureLocation(signatureEnvironment, location); return new XMLDataObjectImpl(signatureParent); } else { @@ -534,31 +540,31 @@ public class XMLSignatureCreationInvoker { } /** - * Get the supplements contained in the - * CreateSignatureEnvironmentProfile of the given + * Get the supplements contained in the + * CreateSignatureEnvironmentProfile of the given * SingleSignatureInfo. - * - * @param singleSigInfo The SingleSignatureInfo from which - * to extract the supplements. - * @return A List of XMLDataObjectAssociations - * or null, if the singleSigInfo does not contain - * supplements. - * @throws MOAApplicationException An error occurred parsing the - * CreateSignatureEnvironmentProfile. + * + * @param singleSigInfo The SingleSignatureInfo from which to + * extract the supplements. + * @return A List of XMLDataObjectAssociations or + * null, if the singleSigInfo does not contain + * supplements. + * @throws MOAApplicationException An error occurred parsing the + * CreateSignatureEnvironmentProfile. */ private List getCreateSignatureEnvironmentProfileSupplements(SingleSignatureInfo singleSigInfo) - throws MOAApplicationException { - CreateSignatureInfo sigInfo = singleSigInfo.getCreateSignatureInfo(); + throws MOAApplicationException { + final CreateSignatureInfo sigInfo = singleSigInfo.getCreateSignatureInfo(); if (sigInfo != null) { - TransactionContext context = - TransactionContextManager.getInstance().getTransactionContext(); - ConfigurationProvider config = context.getConfiguration(); - CreateSignatureEnvironmentProfileExplicit profile = - ProfileMapper.mapCreateSignatureEnvironmentProfile( - sigInfo.getCreateSignatureEnvironmentProfile(), - config); - List supplements = profile.getSupplements(); + final TransactionContext context = + TransactionContextManager.getInstance().getTransactionContext(); + final ConfigurationProvider config = context.getConfiguration(); + final CreateSignatureEnvironmentProfileExplicit profile = + ProfileMapper.mapCreateSignatureEnvironmentProfile( + sigInfo.getCreateSignatureEnvironmentProfile(), + config); + final List supplements = profile.getSupplements(); return supplements; } @@ -567,18 +573,18 @@ public class XMLSignatureCreationInvoker { /** * Build the list of additional signed properties. - * + * * Based on the generic configuration setting - * ConfigurationProvider.TEST_SIGNING_TIME_PROPERTY, a - * constant SigningTime will be added to the properties. - * + * ConfigurationProvider.TEST_SIGNING_TIME_PROPERTY, a constant + * SigningTime will be added to the properties. + * * @return The List of additional signed properties. */ private List buildAdditionalSignedProperties() { - TransactionContext context = - TransactionContextManager.getInstance().getTransactionContext(); - ConfigurationProvider config = context.getConfiguration(); - List additionalSignedProperties = Collections.EMPTY_LIST; + final TransactionContext context = + TransactionContextManager.getInstance().getTransactionContext(); + final ConfigurationProvider config = context.getConfiguration(); + final List additionalSignedProperties = Collections.EMPTY_LIST; return additionalSignedProperties; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/XMLSignatureCreationProfileFactory.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/XMLSignatureCreationProfileFactory.java index 32eab9e..c097b0c 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/XMLSignatureCreationProfileFactory.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/XMLSignatureCreationProfileFactory.java @@ -21,18 +21,8 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.invoke; -import iaik.server.modules.algorithms.HashAlgorithms; -import iaik.server.modules.keys.KeyEntryID; -import iaik.server.modules.keys.KeyModule; -import iaik.server.modules.keys.KeyModuleFactory; -import iaik.server.modules.xml.Canonicalization; -import iaik.server.modules.xmlsign.SignatureStructureTypes; -import iaik.server.modules.xmlsign.XMLSignatureCreationProfile; -import iaik.server.modules.xmlsign.XMLSignatureInsertionLocation; - import java.math.BigInteger; import java.security.Principal; import java.security.cert.X509Certificate; @@ -70,12 +60,20 @@ import at.gv.egovernment.moa.spss.util.MessageProvider; import at.gv.egovernment.moaspss.logging.LogMsg; import at.gv.egovernment.moaspss.logging.Logger; import at.gv.egovernment.moaspss.util.Constants; +import iaik.server.modules.algorithms.HashAlgorithms; +import iaik.server.modules.keys.KeyEntryID; +import iaik.server.modules.keys.KeyModule; +import iaik.server.modules.keys.KeyModuleFactory; +import iaik.server.modules.xml.Canonicalization; +import iaik.server.modules.xmlsign.SignatureStructureTypes; +import iaik.server.modules.xmlsign.XMLSignatureCreationProfile; +import iaik.server.modules.xmlsign.XMLSignatureInsertionLocation; /** * A factory to create XMLSignatureCreationProfiles from a * CreateXMLSignatureRequest, based on the current MOA * configuration. - * + * * @author Patrick Peck * @version $Id$ */ @@ -91,24 +89,25 @@ public class XMLSignatureCreationProfileFactory { HASH_ALGORITHM_MAPPING.put(Constants.SHA512_URI, HashAlgorithms.SHA512); } - /** The CreateXMLSignatureRequest for which to create the - * profile.*/ - private CreateXMLSignatureRequest request; + /** + * The CreateXMLSignatureRequest for which to create the profile. + */ + private final CreateXMLSignatureRequest request; /** How many profiles have been created based on the same request. */ private int createProfileCount; - /** The Set of reserved object IDs.*/ - private Set reserved; + /** The Set of reserved object IDs. */ + private final Set reserved; /** * Create a new XMLSignatureCreationProfileFactory. - * - * @param request The request for which to create profiles. - * @param reserved The Set of reserved object IDs. IDs will - * be added during signature creation. + * + * @param request The request for which to create profiles. + * @param reserved The Set of reserved object IDs. IDs will be + * added during signature creation. */ public XMLSignatureCreationProfileFactory( - CreateXMLSignatureRequest request, - Set reserved) { + CreateXMLSignatureRequest request, + Set reserved) { this.request = request; this.reserved = reserved; createProfileCount = 1; @@ -117,98 +116,98 @@ public class XMLSignatureCreationProfileFactory { /** * Create a XMLSignatureCreationProfile for the given * SingleSignatureInfo object.. - * + * * @param singleSignatureInfo The SingleSignatureInfo object - * containing information about the creation of a signature. - * @param sigInfoReservedIDs The Set of reserved ID attribue values - * for the particular singleSignatureInfo. + * containing information about the creation of a + * signature. + * @param sigInfoReservedIDs The Set of reserved ID attribue + * values for the particular + * singleSignatureInfo. * @return The XMLSignatureCreationProfile containing additional - * information for creating an XML signature. - * @throws MOASystemException A system error occurred during creation of the - * profile. See message for details - * @throws MOAApplicationException An application error occurred during - * creation of the profile. See message for details. + * information for creating an XML signature. + * @throws MOASystemException A system error occurred during creation of + * the profile. See message for details + * @throws MOAApplicationException An application error occurred during creation + * of the profile. See message for details. */ public XMLSignatureCreationProfile createProfile(SingleSignatureInfo singleSignatureInfo, - Set sigInfoReservedIDs) throws MOASystemException, MOAApplicationException { + Set sigInfoReservedIDs) throws MOASystemException, MOAApplicationException { - HashSet allReservedIDs = new HashSet(reserved); + final HashSet allReservedIDs = new HashSet(reserved); allReservedIDs.addAll(sigInfoReservedIDs); - TransactionContext context = - TransactionContextManager.getInstance().getTransactionContext(); - ConfigurationProvider config = context.getConfiguration(); + final TransactionContext context = + TransactionContextManager.getInstance().getTransactionContext(); + final ConfigurationProvider config = context.getConfiguration(); List dataObjectTreatmentList; Set keySet; List transformationSupplements; List createTransformsProfiles; // get the key group id - String keyGroupID = request.getKeyIdentifier(); + final String keyGroupID = request.getKeyIdentifier(); // get digest method on key group level (if configured) - KeyGroup keygroup = config.getKeyGroup(keyGroupID); - if(null == keygroup) { - Logger.error("Could not find key group '" + keyGroupID + "'"); - throw new MOAApplicationException("2231", null); + final KeyGroup keygroup = config.getKeyGroup(keyGroupID); + if (null == keygroup) { + Logger.error("Could not find key group '" + keyGroupID + "'"); + throw new MOAApplicationException("2231", null); } - String configDigestMethodKG = keygroup.getDigestMethodAlgorithm(); + final String configDigestMethodKG = keygroup.getDigestMethodAlgorithm(); // get default digest method (if configured) - String configDigestMethod = config.getDigestMethodAlgorithmName(); - - String xadesVersion = config.getXAdESVersion(); - + final String configDigestMethod = config.getDigestMethodAlgorithmName(); + + final String xadesVersion = config.getXAdESVersion(); + String digestMethodXAdES142 = null; boolean isXAdES142 = false; // if XAdES Version 1.4.2 is configured if (xadesVersion != null && xadesVersion.compareTo("1.4.2") == 0) { - isXAdES142 = true; - Logger.debug("XAdES version '" + xadesVersion + "' used"); + isXAdES142 = true; + Logger.debug("XAdES version '" + xadesVersion + "' used"); } - + if (isXAdES142) { - if (configDigestMethodKG != null) { - // if KG specific digest method is configured - digestMethodXAdES142 = (String) HASH_ALGORITHM_MAPPING.get(configDigestMethodKG); - if (digestMethodXAdES142 == null) { - error( - "config.17", - new Object[] { configDigestMethodKG}); - throw new MOASystemException("2900", null); - } - Logger.debug("Digest algorithm: " + digestMethodXAdES142 + "(configured in KeyGroup)"); - } - else { - // else get default configured digest method - digestMethodXAdES142 = (String) HASH_ALGORITHM_MAPPING.get(configDigestMethod); - if (digestMethodXAdES142 == null) { - error( - "config.17", - new Object[] { configDigestMethod}); - throw new MOASystemException("2900", null); - } - Logger.debug("Digest algorithm: " + digestMethodXAdES142 + "(default)"); - - } + if (configDigestMethodKG != null) { + // if KG specific digest method is configured + digestMethodXAdES142 = (String) HASH_ALGORITHM_MAPPING.get(configDigestMethodKG); + if (digestMethodXAdES142 == null) { + error( + "config.17", + new Object[] { configDigestMethodKG }); + throw new MOASystemException("2900", null); + } + Logger.debug("Digest algorithm: " + digestMethodXAdES142 + "(configured in KeyGroup)"); + } else { + // else get default configured digest method + digestMethodXAdES142 = (String) HASH_ALGORITHM_MAPPING.get(configDigestMethod); + if (digestMethodXAdES142 == null) { + error( + "config.17", + new Object[] { configDigestMethod }); + throw new MOASystemException("2900", null); + } + Logger.debug("Digest algorithm: " + digestMethodXAdES142 + "(default)"); + + } } - - XMLSignatureCreationProfileImpl profile = - new XMLSignatureCreationProfileImpl(createProfileCount, allReservedIDs, digestMethodXAdES142); - + final XMLSignatureCreationProfileImpl profile = + new XMLSignatureCreationProfileImpl(createProfileCount, allReservedIDs, digestMethodXAdES142); + // build the transformation supplements createTransformsProfiles = - getCreateTransformsInfoProfiles(singleSignatureInfo); + getCreateTransformsInfoProfiles(singleSignatureInfo); transformationSupplements = - buildTransformationSupplements(createTransformsProfiles); + buildTransformationSupplements(createTransformsProfiles); // build and set the data object treatment list dataObjectTreatmentList = - buildDataObjectTreatmentList( - singleSignatureInfo, - createTransformsProfiles, - transformationSupplements, - allReservedIDs, - digestMethodXAdES142); + buildDataObjectTreatmentList( + singleSignatureInfo, + createTransformsProfiles, + transformationSupplements, + allReservedIDs, + digestMethodXAdES142); profile.setDataObjectTreatmentList(dataObjectTreatmentList); // set the key set @@ -232,27 +231,28 @@ public class XMLSignatureCreationProfileFactory { // set insertion location profile.setSignatureInsertionLocation( - getSignatureInsertionLocationIndex(singleSignatureInfo)); + getSignatureInsertionLocationIndex(singleSignatureInfo)); // set the canonicalization algorithm - String canonicalizationURI = config.getCanonicalizationAlgorithmName(); + final String canonicalizationURI = config.getCanonicalizationAlgorithmName(); if (Canonicalization.ALL_EXCLUSIVE.contains(canonicalizationURI)) { - ExclusiveCanonicalizationImpl canonicalization = new ExclusiveCanonicalizationImpl(config.getCanonicalizationAlgorithmName(), null); - profile.setSignedInfoCanonicalization(canonicalization); - + final ExclusiveCanonicalizationImpl canonicalization = new ExclusiveCanonicalizationImpl(config + .getCanonicalizationAlgorithmName(), null); + profile.setSignedInfoCanonicalization(canonicalization); + } else { - CanonicalizationImpl canonicalization = - new CanonicalizationImpl(config.getCanonicalizationAlgorithmName()); - profile.setSignedInfoCanonicalization(canonicalization); - + final CanonicalizationImpl canonicalization = + new CanonicalizationImpl(config.getCanonicalizationAlgorithmName()); + profile.setSignedInfoCanonicalization(canonicalization); + } - + // set the signed properties profile.setSignedProperties(Collections.EMPTY_LIST); // set security layer conformity profile.setSecurityLayerConform( - singleSignatureInfo.isSecurityLayerConform()); + singleSignatureInfo.isSecurityLayerConform()); // update the createProfileCount createProfileCount++; @@ -262,31 +262,32 @@ public class XMLSignatureCreationProfileFactory { /** * Get the List of all CreateTransformsInfoProfiles - * contained in all the DataObjectInfos of the given + * contained in all the DataObjectInfos of the given * SingleSignatureInfo. - * + * * @param singleSignatureInfo The SingleSignatureInfo object from - * which to extract the CreateTransformsInfoProfiles. - * @return All CreateTransformsInfoProfiles of all - * DataObjectInfos of singleSignatureInfo. + * which to extract the + * CreateTransformsInfoProfiles. + * @return All CreateTransformsInfoProfiles of all + * DataObjectInfos of singleSignatureInfo. * @throws MOAApplicationException An error occurred creating one of the - * profiles. + * profiles. */ List getCreateTransformsInfoProfiles(SingleSignatureInfo singleSignatureInfo) - throws MOAApplicationException { - TransactionContext context = - TransactionContextManager.getInstance().getTransactionContext(); - ConfigurationProvider config = context.getConfiguration(); - List dataObjInfos = singleSignatureInfo.getDataObjectInfos(); - List profiles = new ArrayList(); + throws MOAApplicationException { + final TransactionContext context = + TransactionContextManager.getInstance().getTransactionContext(); + final ConfigurationProvider config = context.getConfiguration(); + final List dataObjInfos = singleSignatureInfo.getDataObjectInfos(); + final List profiles = new ArrayList(); Iterator dtIter; for (dtIter = dataObjInfos.iterator(); dtIter.hasNext();) { - DataObjectInfo dataObjInfo = (DataObjectInfo) dtIter.next(); - CreateTransformsInfoProfileExplicit profile = - ProfileMapper.mapCreateTransformsInfoProfile( - dataObjInfo.getCreateTransformsInfoProfile(), - config); + final DataObjectInfo dataObjInfo = (DataObjectInfo) dtIter.next(); + final CreateTransformsInfoProfileExplicit profile = + ProfileMapper.mapCreateTransformsInfoProfile( + dataObjInfo.getCreateTransformsInfoProfile(), + config); profiles.add(profile); } @@ -296,41 +297,42 @@ public class XMLSignatureCreationProfileFactory { /** * Build the List of transformation supplements contained in a * SingleSignatureInfo object. - * - * @param createTransformsInfoProfiles The - * CreateTransformsInfoProfile object from which to extract the - * transformation supplements. + * + * @param createTransformsInfoProfiles The + * CreateTransformsInfoProfile + * object from which to extract the + * transformation supplements. * @return A List of DataObjects containing the - * transformation supplements. - * @throws MOASystemException A system error occurred creating one of the - * transformation supplements. + * transformation supplements. + * @throws MOASystemException A system error occurred creating one of the + * transformation supplements. * @throws MOAApplicationException An error occurred creating one of the - * transformation supplements. + * transformation supplements. */ private List buildTransformationSupplements(List createTransformsInfoProfiles) - throws MOASystemException, MOAApplicationException { + throws MOASystemException, MOAApplicationException { - List transformationSupplements = new ArrayList(); - DataObjectFactory factory = DataObjectFactory.getInstance(); + final List transformationSupplements = new ArrayList(); + final DataObjectFactory factory = DataObjectFactory.getInstance(); Iterator iter; for (iter = createTransformsInfoProfiles.iterator(); iter.hasNext();) { - CreateTransformsInfoProfileExplicit profile = - (CreateTransformsInfoProfileExplicit) iter.next(); - List supplements = profile.getSupplements(); + final CreateTransformsInfoProfileExplicit profile = + (CreateTransformsInfoProfileExplicit) iter.next(); + final List supplements = profile.getSupplements(); if (supplements != null) { Iterator supplIter; for (supplIter = supplements.iterator(); supplIter.hasNext();) { - XMLDataObjectAssociation supplement = - (XMLDataObjectAssociation) supplIter.next(); + final XMLDataObjectAssociation supplement = + (XMLDataObjectAssociation) supplIter.next(); transformationSupplements.add( - factory.createFromXmlDataObjectAssociation( - supplement, - false, - true)); + factory.createFromXmlDataObjectAssociation( + supplement, + false, + true)); } } } @@ -341,35 +343,40 @@ public class XMLSignatureCreationProfileFactory { /** * Build the List of DataObjectTreatments for the * given SingleSignatureInfo object.. - * - * @param singleSignatureInfo The SingleSignatureInfo object - * from which to exctract the CreateTransformsInfoProfiles - * containing the data for the DataObjectTreatments. - * @param createTransformsInfoProfiles The - * CreateTransformsInfoProfiles contained in the - * singleSignatureInfo. - * @param transformationSupplements Additional parameters for - * transformations contained in DataObjectTreatments. - * @param reservedIDs The Set of reserved object IDs. + * + * @param singleSignatureInfo The SingleSignatureInfo + * object from which to exctract the + * CreateTransformsInfoProfiles + * containing the data for the + * DataObjectTreatments. + * @param createTransformsInfoProfiles The + * CreateTransformsInfoProfiles + * contained in the + * singleSignatureInfo. + * @param transformationSupplements Additional parameters for transformations + * contained in + * DataObjectTreatments. + * @param reservedIDs The Set of reserved object + * IDs. * @return A List of DataObjectTreatment objects. * @throws MOAApplicationException An error occurred building one of the - * DataObjectTreatments. - * @throws MOASystemException A system error occurred building one of the - * DataObjectTreatments. + * DataObjectTreatments. + * @throws MOASystemException A system error occurred building one of the + * DataObjectTreatments. */ private List buildDataObjectTreatmentList( - SingleSignatureInfo singleSignatureInfo, - List createTransformsInfoProfiles, - List transformationSupplements, - Set reservedIDs, - String digestMethodXAdES142) - throws MOASystemException, MOAApplicationException { - - TransactionContext context = - TransactionContextManager.getInstance().getTransactionContext(); - ConfigurationProvider config = context.getConfiguration(); - List treatments = new ArrayList(); - List dataObjInfos = singleSignatureInfo.getDataObjectInfos(); + SingleSignatureInfo singleSignatureInfo, + List createTransformsInfoProfiles, + List transformationSupplements, + Set reservedIDs, + String digestMethodXAdES142) + throws MOASystemException, MOAApplicationException { + + final TransactionContext context = + TransactionContextManager.getInstance().getTransactionContext(); + final ConfigurationProvider config = context.getConfiguration(); + final List treatments = new ArrayList(); + final List dataObjInfos = singleSignatureInfo.getDataObjectInfos(); int dataObjectTreatmentCount = 1; String hashAlgorithmName; Iterator dtIter; @@ -377,44 +384,40 @@ public class XMLSignatureCreationProfileFactory { prIter = createTransformsInfoProfiles.iterator(); for (dtIter = dataObjInfos.iterator(); dtIter.hasNext();) { - CreateTransformsInfoProfileExplicit profile = - (CreateTransformsInfoProfileExplicit) prIter.next(); - DataObjectInfo dataObjInfo = (DataObjectInfo) dtIter.next(); - IdGenerator objIdGen = - new IdGenerator( - ("signed-data-" + createProfileCount) - + ("-" + dataObjectTreatmentCount++), - reservedIDs); - DataObjectTreatmentImpl treatment = new DataObjectTreatmentImpl(objIdGen); + final CreateTransformsInfoProfileExplicit profile = + (CreateTransformsInfoProfileExplicit) prIter.next(); + final DataObjectInfo dataObjInfo = (DataObjectInfo) dtIter.next(); + final IdGenerator objIdGen = + new IdGenerator( + "signed-data-" + createProfileCount + + "-" + dataObjectTreatmentCount++, + reservedIDs); + final DataObjectTreatmentImpl treatment = new DataObjectTreatmentImpl(objIdGen); treatment.setFinalContentType( - profile.getCreateTransformsInfo().getFinalDataMetaInfo().getMimeType()); + profile.getCreateTransformsInfo().getFinalDataMetaInfo().getMimeType()); treatment.setTransformationList(buildTransformationList(profile)); treatment.setReferenceInManifest(dataObjInfo.isChildOfManifest()); // if XAdES version is 1.4.2 if (digestMethodXAdES142 != null) { - // use configured digest algorithm - hashAlgorithmName = digestMethodXAdES142; - } - else { - // stay as it is - hashAlgorithmName = (String) HASH_ALGORITHM_MAPPING.get( - config.getDigestMethodAlgorithmName()); - if (hashAlgorithmName == null) { - error( - "config.17", - new Object[] { config.getDigestMethodAlgorithmName()}); - throw new MOASystemException("2900", null); - } + // use configured digest algorithm + hashAlgorithmName = digestMethodXAdES142; + } else { + // stay as it is + hashAlgorithmName = (String) HASH_ALGORITHM_MAPPING.get( + config.getDigestMethodAlgorithmName()); + if (hashAlgorithmName == null) { + error( + "config.17", + new Object[] { config.getDigestMethodAlgorithmName() }); + throw new MOASystemException("2900", null); + } } - - - treatment.setHashAlgorithmName(hashAlgorithmName); treatment.setIncludedInSignature( - DataObjectInfo.STRUCTURE_ENVELOPING.equals(dataObjInfo.getStructure())); + DataObjectInfo.STRUCTURE_ENVELOPING.equals(dataObjInfo.getStructure())); treatment.setTransformationSupplements(transformationSupplements); treatments.add(treatment); @@ -427,48 +430,48 @@ public class XMLSignatureCreationProfileFactory { /** * Build the List of transformations contained in a * CreateTransformsInfoProfile object. - * - * @param profile The CreateTransformsInfoProfile object - * from which to extract the Transforms. - * @return A List of Transformations contained in - * the given CreateTransformsInfoProfile. + * + * @param profile The CreateTransformsInfoProfile object from which + * to extract the Transforms. + * @return A List of Transformations contained in the + * given CreateTransformsInfoProfile. * @throws MOAApplicationException An error occurred building one of the - * Transformations. + * Transformations. */ private List buildTransformationList(CreateTransformsInfoProfileExplicit profile) - throws MOAApplicationException { + throws MOAApplicationException { - TransformationFactory factory = TransformationFactory.getInstance(); - List transforms = profile.getCreateTransformsInfo().getTransforms(); + final TransformationFactory factory = TransformationFactory.getInstance(); + final List transforms = profile.getCreateTransformsInfo().getTransforms(); return transforms != null - ? factory.createTransformationList(transforms) - : Collections.EMPTY_LIST; + ? factory.createTransformationList(transforms) + : Collections.EMPTY_LIST; } /** * Build the set of KeyEntryIDs available to the given * keyGroupID. - * + * * @param keyGroupID The keygroup ID for which the available keys should be - * returned. - * @return The Set of KeyEntryIDs - * identifying the available keys. + * returned. + * @return The Set of KeyEntryIDs identifying the + * available keys. */ private Set buildKeySet(String keyGroupID) { - TransactionContext context = - TransactionContextManager.getInstance().getTransactionContext(); - ConfigurationProvider config = context.getConfiguration(); + final TransactionContext context = + TransactionContextManager.getInstance().getTransactionContext(); + final ConfigurationProvider config = context.getConfiguration(); Set keyGroupEntries; // get the KeyGroup entries from the configuration if (context.getClientCertificate() != null) { - X509Certificate cert = context.getClientCertificate()[0]; - Principal issuer = cert.getIssuerDN(); - BigInteger serialNumber = cert.getSerialNumber(); + final X509Certificate cert = context.getClientCertificate()[0]; + final Principal issuer = cert.getIssuerDN(); + final BigInteger serialNumber = cert.getSerialNumber(); keyGroupEntries = - config.getKeyGroupEntries(issuer, serialNumber, keyGroupID); + config.getKeyGroupEntries(issuer, serialNumber, keyGroupID); } else { keyGroupEntries = config.getKeyGroupEntries(null, null, keyGroupID); } @@ -479,23 +482,23 @@ public class XMLSignatureCreationProfileFactory { } else if (keyGroupEntries.size() == 0) { return Collections.EMPTY_SET; } else { - KeyModule module = - KeyModuleFactory.getInstance( - new TransactionId(context.getTransactionID())); - Set keyEntryIDs = module.getPrivateKeyEntryIDs(); - Set keySet = new HashSet(); + final KeyModule module = + KeyModuleFactory.getInstance( + new TransactionId(context.getTransactionID())); + final Set keyEntryIDs = module.getPrivateKeyEntryIDs(); + final Set keySet = new HashSet(); Iterator iter; // filter out the keys that do not exist in the IAIK configuration // by walking through the key entries and checking if the exist in the // keyGroupEntries for (iter = keyEntryIDs.iterator(); iter.hasNext();) { - KeyEntryID entryID = (KeyEntryID) iter.next(); - KeyGroupEntry entry = - new KeyGroupEntry( - entryID.getModuleID(), - entryID.getCertificateIssuer(), - entryID.getCertificateSerialNumber()); + final KeyEntryID entryID = (KeyEntryID) iter.next(); + final KeyGroupEntry entry = + new KeyGroupEntry( + entryID.getModuleID(), + entryID.getCertificateIssuer(), + entryID.getCertificateSerialNumber()); if (keyGroupEntries.contains(entry)) { keySet.add(entryID); } @@ -507,29 +510,31 @@ public class XMLSignatureCreationProfileFactory { /** * Get the signature location index where the signature will be inserted into * the signature parent element. - * + * * @param singleSignatureInfo The SingleSignatureInfo object - * containing the CreateSignatureLocation. + * containing the + * CreateSignatureLocation. * @return The index at which to insert the signature into the signature - * environment. - * @throws MOAApplicationException An error occurred parsing the - * CreateSignatureEnvironmentProfile. + * environment. + * @throws MOAApplicationException An error occurred parsing the + * CreateSignatureEnvironmentProfile. */ - private XMLSignatureInsertionLocation getSignatureInsertionLocationIndex(SingleSignatureInfo singleSignatureInfo) - throws MOAApplicationException { + private XMLSignatureInsertionLocation getSignatureInsertionLocationIndex( + SingleSignatureInfo singleSignatureInfo) + throws MOAApplicationException { - CreateSignatureInfo createInfo = - singleSignatureInfo.getCreateSignatureInfo(); + final CreateSignatureInfo createInfo = + singleSignatureInfo.getCreateSignatureInfo(); if (createInfo != null) { - TransactionContext context = - TransactionContextManager.getInstance().getTransactionContext(); - ConfigurationProvider config = context.getConfiguration(); - CreateSignatureEnvironmentProfileExplicit profile = - ProfileMapper.mapCreateSignatureEnvironmentProfile( - createInfo.getCreateSignatureEnvironmentProfile(), - config); - int index = profile.getCreateSignatureLocation().getIndex(); + final TransactionContext context = + TransactionContextManager.getInstance().getTransactionContext(); + final ConfigurationProvider config = context.getConfiguration(); + final CreateSignatureEnvironmentProfileExplicit profile = + ProfileMapper.mapCreateSignatureEnvironmentProfile( + createInfo.getCreateSignatureEnvironmentProfile(), + config); + final int index = profile.getCreateSignatureLocation().getIndex(); return new XMLSignatureInsertionLocationImpl(index); } else { @@ -539,12 +544,12 @@ public class XMLSignatureCreationProfileFactory { /** * Utility function to issue an error message to the log. - * - * @param messageId The ID of the message to log. + * + * @param messageId The ID of the message to log. * @param parameters Additional message parameters. */ private static void error(String messageId, Object[] parameters) { - MessageProvider msg = MessageProvider.getInstance(); + final MessageProvider msg = MessageProvider.getInstance(); Logger.error(new LogMsg(msg.getMessage(messageId, parameters))); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/XMLSignatureVerificationInvoker.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/XMLSignatureVerificationInvoker.java index 74c4f0b..b97cc95 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/XMLSignatureVerificationInvoker.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/XMLSignatureVerificationInvoker.java @@ -37,8 +37,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import javax.xml.ws.soap.AddressingFeature.Responses; - import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -49,7 +47,6 @@ import at.gv.egovernment.moa.spss.api.SPSSFactory; import at.gv.egovernment.moa.spss.api.common.CheckResult; import at.gv.egovernment.moa.spss.api.common.ExtendedCertificateCheckResult; import at.gv.egovernment.moa.spss.api.common.XMLDataObjectAssociation; -import at.gv.egovernment.moa.spss.api.impl.AdESFormResultsImpl; import at.gv.egovernment.moa.spss.api.xmlverify.ReferenceInfo; import at.gv.egovernment.moa.spss.api.xmlverify.ReferencesCheckResult; import at.gv.egovernment.moa.spss.api.xmlverify.ReferencesCheckResultInfo; @@ -78,12 +75,9 @@ import at.gv.egovernment.moaspss.logging.LoggingContextManager; import at.gv.egovernment.moaspss.util.CollectionUtils; import at.gv.egovernment.moaspss.util.Constants; import iaik.server.ConfigurationException; -import iaik.server.modules.AdESConstants; -import iaik.server.modules.AdESFormVerificationResult; import iaik.server.modules.IAIKException; import iaik.server.modules.IAIKRuntimeException; import iaik.server.modules.SignatureVerificationProfile; -import iaik.server.modules.SignatureVerificationResult; import iaik.server.modules.xml.DataObject; import iaik.server.modules.xml.XMLDataObject; import iaik.server.modules.xml.XMLSignature; @@ -103,667 +97,667 @@ import iaik.xml.crypto.utils.URIException; /** * A class providing a DOM based interface to the * XMLSignatureVerificationModule. - * + * * This class performs the invocation of the * iaik.server.modules.xmlverify.XMLSignatureVerificationModule * from a VerifyXMLSignatureRequest given as a DOM element. The * result of the invocation is integrated into a * VerifyXMLSignatureResponse and returned. - * + * * @author Patrick Peck * @version $Id$ */ public class XMLSignatureVerificationInvoker { - /** The single instance of this class. */ - private static XMLSignatureVerificationInvoker instance = null; - - private static Set FILTERED_REF_TYPES; - - static { - FILTERED_REF_TYPES = new HashSet(); - FILTERED_REF_TYPES.add(DsigManifest.XML_DSIG_MANIFEST_TYPE); - FILTERED_REF_TYPES.add(SecurityLayerManifest.SECURITY_LAYER_MANIFEST_TYPE); - FILTERED_REF_TYPES.add(SecurityLayerManifest.SECURITY_LAYER_MANIFEST_TYPE_OLD); - FILTERED_REF_TYPES.add(XMLConstants.NAMESPACE_ETSI_STRING + "SignedProperties"); - FILTERED_REF_TYPES.add("http://uri.etsi.org/01903#SignedProperties"); - } - - /** - * Get the single instance of this class. - * - * @return The single instance of this class. - */ - public static synchronized XMLSignatureVerificationInvoker getInstance() { - if (instance == null) { - instance = new XMLSignatureVerificationInvoker(); - } - return instance; - } - - /** - * Create a new XMLSignatureCreationInvoker. - * - * Protected to disallow multiple instances. - */ - protected XMLSignatureVerificationInvoker() { - } - - /** - * Process the VerifyXMLSignatureRequest message and invoke the - * XMLSignatureVerificationModule. - * - * @param request - * A VerifyXMLSignatureRequest API object - * containing the data for verifying an XML signature. - * @return A VerifyXMLSignatureResponse containing the answert - * to the VerifyXMLSignatureRequest. MOA schema - * definition. - * @throws MOAException - * An error occurred during signature verification. - */ - public VerifyXMLSignatureResponse verifyXMLSignature(VerifyXMLSignatureRequest request) throws MOAException { - - TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); - LoggingContext loggingCtx = LoggingContextManager.getInstance().getLoggingContext(); - XMLSignatureVerificationProfileFactory profileFactory = new XMLSignatureVerificationProfileFactory(request); - VerifyXMLSignatureResponseBuilder responseBuilder = new VerifyXMLSignatureResponseBuilder(); - ExtendedXMLSignatureVerificationResult result = null; - XMLSignatureVerificationResult plainResult; - XMLSignatureVerificationProfile profile; - ReferencesCheckResult signatureManifestCheck; - DataObjectFactory dataObjFactory; - XMLDataObject signatureEnvironment; - Node signatureEnvironmentParent = null; - Element requestElement = null; - XMLSignature xmlSignature; - Date signingTime; - List supplements; - List dataObjectList; - - // get the supplements - supplements = getSupplements(request); - - // build XMLSignature - dataObjFactory = DataObjectFactory.getInstance(); - signatureEnvironment = dataObjFactory - .createSignatureEnvironment(request.getSignatureInfo().getVerifySignatureEnvironment(), supplements); - xmlSignature = buildXMLSignature(signatureEnvironment, request); - - // build the list of DataObjects - dataObjectList = buildDataObjectList(supplements); - - // build profile - profile = profileFactory.createProfile(); - - // get the signingTime - signingTime = request.getDateTime(); - - // make the signature environment the root of the document, if it is not - // a - // separate document anyway; this is done to assure that - // canonicalization - // of the signature environment contains the correct namespace - // declarations - requestElement = signatureEnvironment.getElement().getOwnerDocument().getDocumentElement(); - if (requestElement != signatureEnvironment.getElement()) { - signatureEnvironmentParent = signatureEnvironment.getElement().getParentNode(); - requestElement.getOwnerDocument().replaceChild(signatureEnvironment.getElement(), requestElement); - } - - QCSSCDResult qcsscdresult = new QCSSCDResult(); - String tpID = profile.getCertificateValidationProfile().getTrustStoreProfile().getId(); - ConfigurationProvider config = ConfigurationProvider.getInstance(); - TrustProfile tp = config.getTrustProfile(tpID); - - // verify the signature - try { - XMLSignatureVerificationModule module = XMLSignatureVerificationModuleFactory.getInstance(); - - module.setLog(new IaikLog(loggingCtx.getNodeID())); - - if(request.getExtendedValidaiton()) { - result = module.verifyXAdESSignature(xmlSignature, dataObjectList, profile, signingTime, - new TransactionId(context.getTransactionID())); - plainResult = result.getXMLSignatureVerificationResult(); - } else { - plainResult = module.verifySignature(xmlSignature, dataObjectList, profile, signingTime, - new TransactionId(context.getTransactionID())); - } - } catch (IAIKException e) { - MOAException moaException = IaikExceptionMapper.getInstance().map(e); - throw moaException; - } catch (IAIKRuntimeException e) { - MOAException moaException = IaikExceptionMapper.getInstance().map(e); - throw moaException; - } - - ExtendedCertificateCheckResult extCheckResult; - if(result != null) { - List adesResults = null;// - - adesResults = AdESResultUtils.getAdESResult(result.getFormVerificationResult()); - - if (Logger.isDebugEnabled()) { - if (adesResults != null) { - Iterator adesIterator = adesResults.iterator(); - while (adesIterator.hasNext()) { - Logger.debug("ADES Formresults: " + adesIterator.next().toString()); - } - } - } - - responseBuilder.setAdESFormResults(adesResults); - - try { - //Logger.info("Extended Validation Report: " + result.getName()); - Logger.debug("Extended Validation Code: " + result.getResultCode().toString()); - Logger.debug("Extended Validation Info: " + result.getInfo()); - - extCheckResult = AdESResultUtils.getExtendedResult(result.getResultCode()); - responseBuilder.setExtendedCertificateCheckResult(extCheckResult); - - } catch (NullPointerException e) { - Logger.info("No extendend validation result available."); - } - } - // QC/SSCD check - List list = plainResult.getCertificateValidationResult().getCertificateChain(); - if (list != null) { - X509Certificate[] chain = new X509Certificate[list.size()]; - - Iterator it = list.iterator(); - int i = 0; - while (it.hasNext()) { - chain[i] = (X509Certificate) it.next(); - i++; - } - - qcsscdresult = CertificateUtils.checkQCSSCD(chain, plainResult.getSigningTime(), tp.isTSLEnabled(), config); - } - - // get signer certificate issuer country code - String issuerCountryCode = CertificateUtils.getIssuerCountry((X509Certificate) list.get(0)); - - // swap back in the request as root document - if (requestElement != signatureEnvironment.getElement()) { - requestElement.getOwnerDocument().replaceChild(requestElement, signatureEnvironment.getElement()); - signatureEnvironmentParent.appendChild(signatureEnvironment.getElement()); - } - - // check the result - signatureManifestCheck = validateSignatureManifest(request, plainResult, - profile); - - // Check if signer certificate is in trust profile's allowed signer - // certificates pool - TrustProfile trustProfile = context.getConfiguration().getTrustProfile(request.getTrustProfileId()); - CheckResult certificateCheck = validateSignerCertificate(plainResult, - trustProfile); - - // build the response - responseBuilder.setResult(plainResult, profile, signatureManifestCheck, - certificateCheck, qcsscdresult.isQC(), qcsscdresult.isQCSourceTSL(), qcsscdresult.isSSCD(), - qcsscdresult.isSSCDSourceTSL(), tp.isTSLEnabled(), issuerCountryCode, qcsscdresult.getTslInfos(), request.getExtendedValidaiton()); - return responseBuilder.getResponse(); - } - - /** - * Checks if the signer certificate matches one of the allowed signer - * certificates specified in the provided trustProfile. - * - * @param result - * The result produced by the - * XMLSignatureVerificationModule. - * - * @param trustProfile - * The trust profile the signer certificate is validated against. - * - * @return The overal result of the certificate validation for the signer - * certificate. - * - * @throws MOAException - * if one of the signer certificates specified in the - * trustProfile cannot be read from the file - * system. - */ - private CheckResult validateSignerCertificate(XMLSignatureVerificationResult result, - TrustProfile trustProfile) - throws MOAException { - MessageProvider msg = MessageProvider.getInstance(); - - int resultCode = result.getCertificateValidationResult().getValidationResultCode().intValue(); - - if (resultCode == 0 && trustProfile.getSignerCertsUri() != null) { - X509Certificate signerCertificate = (X509Certificate) result.getCertificateValidationResult() - .getCertificateChain().get(0); - - File signerCertsDir = null; - try { - signerCertsDir = new File(new URI(trustProfile.getSignerCertsUri()).getPath()); - } catch (URIException e) { - throw new MOASystemException("2900", null, e); // Should not - // happen, - // already - // checked at - // loading the - // MOA - // configuration - } - - File[] files = signerCertsDir.listFiles(); - if (files == null) - resultCode = 1; - int i; - for (i = 0; i < files.length; i++) { - if (!files[i].isDirectory()) { - FileInputStream currentFIS = null; - try { - currentFIS = new FileInputStream(files[i]); - } catch (FileNotFoundException e) { - throw new MOASystemException("2900", null, e); - } - - try { - X509Certificate currentCert = new X509Certificate(currentFIS); - currentFIS.close(); - if (currentCert.equals(signerCertificate)) - break; - } catch (Exception e) { - // Simply ignore file if it cannot be interpreted as - // certificate - String logMsg = msg.getMessage("invoker.03", - new Object[] { trustProfile.getId(), files[i].getName() }); - Logger.warn(logMsg); - try { - currentFIS.close(); - } catch (IOException e1) { - // If clean-up fails, do nothing - } - } - } - } - if (i >= files.length) { - resultCode = 1; // No signer certificate from the trustprofile - // pool matches the actual signer certificate - } - } - - SPSSFactory factory = SPSSFactory.getInstance(); - return factory.createCheckResult(resultCode, null); - } - - /** - * Select the dsig:Signature DOM element within the signature - * environment. - * - * @param signatureEnvironment - * The signature environment containing the - * dsig:Signature. - * @param request - * The VerifyXMLSignatureRequest containing the - * signature environment. - * @return The dsig:Signature element wrapped in a - * XMLSignature object. - * @throws MOAApplicationException - * An error occurred locating the dsig:Signature. - */ - private XMLSignature buildXMLSignature(XMLDataObject signatureEnvironment, VerifyXMLSignatureRequest request) - throws MOAApplicationException { - - VerifySignatureLocation signatureLocation = request.getSignatureInfo().getVerifySignatureLocation(); - Element signatureParent; - - // evaluate the VerifySignatureLocation to get the signature parent - signatureParent = InvokerUtils.evaluateSignatureLocation(signatureEnvironment.getElement(), signatureLocation); - - // check for signatureParent to be a dsig:Signature element - if (!"Signature".equals(signatureParent.getLocalName()) - || !Constants.DSIG_NS_URI.equals(signatureParent.getNamespaceURI())) { - throw new MOAApplicationException("2266", null); - } - - return new XMLSignatureImpl(signatureParent); - } - - /** - * Build the supplemental data objects contained in the - * VerifyXMLSignatureRequest. - * - * @param supplements - * A List of XMLDataObjectAssociations - * containing the supplement data. - * @return A List of DataObjects representing the - * supplemental data objects. - * @throws MOASystemException - * A system error occurred building one of the data objects. - * @throws MOAApplicationException - * An error occurred building one of the data objects. - */ - private List buildDataObjectList(List supplements) throws MOASystemException, MOAApplicationException { - List dataObjectList = new ArrayList(); - - DataObjectFactory factory = DataObjectFactory.getInstance(); - DataObject dataObject; - Iterator iter; - - if (supplements != null) { - for (iter = supplements.iterator(); iter.hasNext();) { - XMLDataObjectAssociation supplement = (XMLDataObjectAssociation) iter.next(); - dataObject = factory.createFromXmlDataObjectAssociation(supplement, true, false); - dataObjectList.add(dataObject); - } - } - - return dataObjectList; - - } - - /** - * Get the supplemental data contained in the - * VerifyXMLSignatureRequest. - * - * @param request - * The VerifyXMLSignatureRequest containing the - * supplemental data. - * @return A List of XMLDataObjectAssociation - * objects containing the supplemental data. - * @throws MOAApplicationException - * An error occurred resolving one of the supplement profiles. - */ - private List getSupplements(VerifyXMLSignatureRequest request) throws MOAApplicationException { - TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); - ConfigurationProvider config = context.getConfiguration(); - List supplementProfiles = request.getSupplementProfiles(); - - List supplements = new ArrayList(); - - if (supplementProfiles != null) { - - List mappedProfiles = ProfileMapper.mapSupplementProfiles(supplementProfiles, config); - Iterator iter; - - for (iter = mappedProfiles.iterator(); iter.hasNext();) { - SupplementProfileExplicit profile = (SupplementProfileExplicit) iter.next(); - supplements.add(profile.getSupplementProfile()); - } - - } - return supplements; - } - - /** - * Perform additional validations of the - * XMLSignatureVerificationResult. - * - *

- * In particular, it is verified that: - *

    - *
  • Each ReferenceData object contains transformation chain - * that matches one of the Transforms given in the - * corresponding SignatureManifestCheckParams/ReferenceInfo - *
  • - *
  • The hash values of the TransformParameters are valid. - *
  • - *
- *

- * - * @param request - * The VerifyXMLSignatureRequest containing the - * signature to verify. - * @param result - * The result produced by - * XMLSignatureVerificationModule. - * @param profile - * The profile used for validating the request. - * @return The result of additional validations of the signature manifest. - * @throws MOAApplicationException - * Post-validation of the - * XMLSignatureVerificaitonResult failed. - */ - private ReferencesCheckResult validateSignatureManifest(VerifyXMLSignatureRequest request, - XMLSignatureVerificationResult result, XMLSignatureVerificationProfile profile) - throws MOAApplicationException { - - SPSSFactory factory = SPSSFactory.getInstance(); - MessageProvider msg = MessageProvider.getInstance(); - - // validate that each ReferenceData object contains transforms specified - // in the corresponding SignatureManifestCheckParams/ReferenceInfo - if (request.getSignatureManifestCheckParams() != null) { - List refInfos = request.getSignatureManifestCheckParams().getReferenceInfos(); - List refDatas = filterReferenceInfos(result.getReferenceDataList()); - List failedReferencesList = new ArrayList(); - Iterator refInfoIter; - Iterator refDataIter; - - if (refInfos.size() != refDatas.size()) { - return factory.createReferencesCheckResult(1, null); - } - - refInfoIter = refInfos.iterator(); - refDataIter = filterReferenceInfos(result.getReferenceDataList()).iterator(); - - while (refInfoIter.hasNext()) { - ReferenceInfo refInfo = (ReferenceInfo) refInfoIter.next(); - ReferenceData refData = (ReferenceData) refDataIter.next(); - List transforms = buildTransformsList(refInfo); - boolean found = false; - Iterator trIter; - - for (trIter = transforms.iterator(); trIter.hasNext() && !found;) { - found = trIter.next().equals(refData.getTransformationList()); - } - - if (!found) { - Integer refIndex = new Integer(refData.getReferenceIndex()); - String logMsg = msg.getMessage("invoker.01", new Object[] { refIndex }); - - failedReferencesList.add(refIndex); - Logger.debug(new LogMsg(logMsg)); - } - } - - if (!failedReferencesList.isEmpty()) { - // at least one reference failed - return their indexes and - // check code 1 - int[] failedReferences = CollectionUtils.toIntArray(failedReferencesList); - ReferencesCheckResultInfo checkInfo = factory.createReferencesCheckResultInfo(null, failedReferences); - - return factory.createReferencesCheckResult(1, checkInfo); - } - } - - // validate the hashes contained in all the ReferenceInfo objects of the - // security layer manifest - if (request.getSignatureManifestCheckParams() != null && result.containsSecurityLayerManifest()) { - Map hashValues = buildTransformParameterHashValues(request); - Set transformParameterURIs = buildTransformParameterURIs(profile.getTransformationSupplements()); - List referenceInfoList = result.getSecurityLayerManifest().getReferenceDataList(); - Iterator refIter; - - for (refIter = referenceInfoList.iterator(); refIter.hasNext();) { - iaik.server.modules.xmlverify.ReferenceInfo ref = (iaik.server.modules.xmlverify.ReferenceInfo) refIter - .next(); - byte[] hash = (byte[]) hashValues.get(ref.getURI()); - - if (!transformParameterURIs.contains(ref.getURI()) - || (hash != null && !Arrays.equals(hash, ref.getHashValue()))) { - - // the transform parameter doesn't exist or the hashs do not - // match - // return the index of the failed reference and check code 1 - int[] failedReferences = new int[] { ref.getReferenceIndex() }; - ReferencesCheckResultInfo checkInfo = factory.createReferencesCheckResultInfo(null, - failedReferences); - String logMsg = msg.getMessage("invoker.02", new Object[] { new Integer(ref.getReferenceIndex()) }); - - Logger.debug(new LogMsg(logMsg)); - - return factory.createReferencesCheckResult(1, checkInfo); - } - } - } - - return factory.createReferencesCheckResult(0, null); - } - - /** - * Get all Transforms contained in all the - * VerifyTransformsInfoProfiles of the given - * ReferenceInfo. - * - * @param refInfo - * The ReferenceInfo object containing the - * transformations. - * @return A List of Lists. Each of the - * Lists contains Transformation objects. - * @throws MOAApplicationException - * An error occurred building one of the - * Transformations. - */ - private List buildTransformsList(ReferenceInfo refInfo) throws MOAApplicationException { - - TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); - ConfigurationProvider config = context.getConfiguration(); - List profiles = refInfo.getVerifyTransformsInfoProfiles(); - List mappedProfiles = ProfileMapper.mapVerifyTransformsInfoProfiles(profiles, config); - List transformsList = new ArrayList(); - TransformationFactory factory = TransformationFactory.getInstance(); - Iterator iter; - - for (iter = mappedProfiles.iterator(); iter.hasNext();) { - VerifyTransformsInfoProfileExplicit profile = (VerifyTransformsInfoProfileExplicit) iter.next(); - List transforms = profile.getTransforms(); - - if (transforms != null) { - transformsList.add(factory.createTransformationList(transforms)); - } - } - - return transformsList; - } - - /** - * Build the Set of all TransformParameter URIs. - * - * @param transformParameters - * The List of TransformParameters, as - * provided to the verification. - * @return The Set of all TransformParameter URIs. - */ - private Set buildTransformParameterURIs(List transformParameters) { - Set uris = new HashSet(); - Iterator iter; - - for (iter = transformParameters.iterator(); iter.hasNext();) { - DataObject transformParameter = (DataObject) iter.next(); - uris.add(transformParameter.getURI()); - } - - return uris; - } - - /** - * Build a mapping between TransformParameter URIs (a - * String and dsig:HashValue (a - * byte[]). - * - * @param request - * The VerifyXMLSignatureRequest. - * @return Map The resulting mapping. - * @throws MOAApplicationException - * An error occurred accessing one of the profiles. - */ - private Map buildTransformParameterHashValues(VerifyXMLSignatureRequest request) throws MOAApplicationException { - - TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); - ConfigurationProvider config = context.getConfiguration(); - Map hashValues = new HashMap(); - List refInfos = request.getSignatureManifestCheckParams().getReferenceInfos(); - Iterator refIter; - - for (refIter = refInfos.iterator(); refIter.hasNext();) { - ReferenceInfo refInfo = (ReferenceInfo) refIter.next(); - List profiles = refInfo.getVerifyTransformsInfoProfiles(); - List mappedProfiles = ProfileMapper.mapVerifyTransformsInfoProfiles(profiles, config); - Iterator prIter; - - for (prIter = mappedProfiles.iterator(); prIter.hasNext();) { - VerifyTransformsInfoProfileExplicit profile = (VerifyTransformsInfoProfileExplicit) prIter.next(); - List trParameters = profile.getTransformParameters(); - Iterator trIter; - - for (trIter = trParameters.iterator(); trIter.hasNext();) { - TransformParameter transformParameter = (TransformParameter) trIter.next(); - String uri = transformParameter.getURI(); - - if (transformParameter.getTransformParameterType() == TransformParameter.HASH_TRANSFORMPARAMETER) { - hashValues.put(uri, ((TransformParameterHash) transformParameter).getDigestValue()); - } - - } - } - } - return hashValues; - } - - /** - * Filter the ReferenceInfos returned by the - * VerifyXMLSignatureResult for comparison with the - * ReferenceInfo elements in the request. - * - * @param referenceInfos - * The ReferenceInfos from the - * VerifyXMLSignatureResult. - * @return A List of all ReferenceInfos whose type - * is not a XMLDsig manifest, Security Layer manifest, or ETSI - * signed property. - */ - private List filterReferenceInfos(List referenceInfos) { - List filtered = new ArrayList(); - Iterator iter; - - for (iter = referenceInfos.iterator(); iter.hasNext();) { - iaik.server.modules.xmlverify.ReferenceInfo refInfo = (iaik.server.modules.xmlverify.ReferenceInfo) iter - .next(); - String refType = refInfo.getReferenceType(); - - if (refType == null || !FILTERED_REF_TYPES.contains(refType)) { - filtered.add(refInfo); - } - } - - return filtered; - } - - private List getAdESResult(ExtendedXMLSignatureVerificationResult adesFormVerification) throws ConfigurationException { - if (adesFormVerification == null) { - // no form information - return null; - } - - List adesList = new ArrayList(); - - /* - checkSubResult(adesFormVerification.getSubResult(SignatureVerificationProfile.LEVEL_LTA), - SignatureVerificationProfile.LEVEL_LTA, adesList); - checkSubResult(adesFormVerification.getSubResult(SignatureVerificationProfile.LEVEL_LT), - SignatureVerificationProfile.LEVEL_LT, adesList); - checkSubResult(adesFormVerification.getSubResult(SignatureVerificationProfile.LEVEL_T), - SignatureVerificationProfile.LEVEL_T, adesList); - checkSubResult(adesFormVerification.getSubResult(SignatureVerificationProfile.LEVEL_B), - SignatureVerificationProfile.LEVEL_B, adesList); - */ - - AdESResultUtils.checkSubResult(adesFormVerification.getSubResult(AdESConstants.LONG_TERM_VALIDATION), - SignatureVerificationProfile.LEVEL_LT, adesList); - AdESResultUtils.checkSubResult(adesFormVerification.getSubResult(AdESConstants.ADES_T_VALIDATION), - SignatureVerificationProfile.LEVEL_T, adesList); - AdESResultUtils.checkSubResult(adesFormVerification.getSubResult("basic report"), - SignatureVerificationProfile.LEVEL_B, adesList); - - return adesList; - } + /** The single instance of this class. */ + private static XMLSignatureVerificationInvoker instance = null; + + private static Set FILTERED_REF_TYPES; + + static { + FILTERED_REF_TYPES = new HashSet(); + FILTERED_REF_TYPES.add(DsigManifest.XML_DSIG_MANIFEST_TYPE); + FILTERED_REF_TYPES.add(SecurityLayerManifest.SECURITY_LAYER_MANIFEST_TYPE); + FILTERED_REF_TYPES.add(SecurityLayerManifest.SECURITY_LAYER_MANIFEST_TYPE_OLD); + FILTERED_REF_TYPES.add(XMLConstants.NAMESPACE_ETSI_STRING + "SignedProperties"); + FILTERED_REF_TYPES.add("http://uri.etsi.org/01903#SignedProperties"); + } + + /** + * Get the single instance of this class. + * + * @return The single instance of this class. + */ + public static synchronized XMLSignatureVerificationInvoker getInstance() { + if (instance == null) { + instance = new XMLSignatureVerificationInvoker(); + } + return instance; + } + + /** + * Create a new XMLSignatureCreationInvoker. + * + * Protected to disallow multiple instances. + */ + protected XMLSignatureVerificationInvoker() { + } + + /** + * Process the VerifyXMLSignatureRequest message and invoke the + * XMLSignatureVerificationModule. + * + * @param request A VerifyXMLSignatureRequest API object + * containing the data for verifying an XML signature. + * @return A VerifyXMLSignatureResponse containing the answert + * to the VerifyXMLSignatureRequest. MOA schema + * definition. + * @throws MOAException An error occurred during signature verification. + */ + public VerifyXMLSignatureResponse verifyXMLSignature(VerifyXMLSignatureRequest request) + throws MOAException { + + final TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); + final LoggingContext loggingCtx = LoggingContextManager.getInstance().getLoggingContext(); + final XMLSignatureVerificationProfileFactory profileFactory = new XMLSignatureVerificationProfileFactory( + request); + final VerifyXMLSignatureResponseBuilder responseBuilder = new VerifyXMLSignatureResponseBuilder(); + ExtendedXMLSignatureVerificationResult result = null; + XMLSignatureVerificationResult plainResult; + XMLSignatureVerificationProfile profile; + ReferencesCheckResult signatureManifestCheck; + DataObjectFactory dataObjFactory; + XMLDataObject signatureEnvironment; + Node signatureEnvironmentParent = null; + Element requestElement = null; + XMLSignature xmlSignature; + Date signingTime; + List supplements; + List dataObjectList; + + // get the supplements + supplements = getSupplements(request); + + // build XMLSignature + dataObjFactory = DataObjectFactory.getInstance(); + signatureEnvironment = dataObjFactory + .createSignatureEnvironment(request.getSignatureInfo().getVerifySignatureEnvironment(), supplements); + xmlSignature = buildXMLSignature(signatureEnvironment, request); + + // build the list of DataObjects + dataObjectList = buildDataObjectList(supplements); + + // build profile + profile = profileFactory.createProfile(); + + // get the signingTime + signingTime = request.getDateTime(); + + // make the signature environment the root of the document, if it is not + // a + // separate document anyway; this is done to assure that + // canonicalization + // of the signature environment contains the correct namespace + // declarations + requestElement = signatureEnvironment.getElement().getOwnerDocument().getDocumentElement(); + if (requestElement != signatureEnvironment.getElement()) { + signatureEnvironmentParent = signatureEnvironment.getElement().getParentNode(); + requestElement.getOwnerDocument().replaceChild(signatureEnvironment.getElement(), requestElement); + } + + QCSSCDResult qcsscdresult = new QCSSCDResult(); + final String tpID = profile.getCertificateValidationProfile().getTrustStoreProfile().getId(); + final ConfigurationProvider config = ConfigurationProvider.getInstance(); + final TrustProfile tp = config.getTrustProfile(tpID); + + // verify the signature + try { + final XMLSignatureVerificationModule module = XMLSignatureVerificationModuleFactory.getInstance(); + + module.setLog(new IaikLog(loggingCtx.getNodeID())); + + if (request.getExtendedValidaiton()) { + result = module.verifyXAdESSignature(xmlSignature, dataObjectList, profile, signingTime, + new TransactionId(context.getTransactionID())); + plainResult = result.getXMLSignatureVerificationResult(); + } else { + plainResult = module.verifySignature(xmlSignature, dataObjectList, profile, signingTime, + new TransactionId(context.getTransactionID())); + } + } catch (final IAIKException e) { + final MOAException moaException = IaikExceptionMapper.getInstance().map(e); + throw moaException; + } catch (final IAIKRuntimeException e) { + final MOAException moaException = IaikExceptionMapper.getInstance().map(e); + throw moaException; + } + + ExtendedCertificateCheckResult extCheckResult; + if (result != null) { + List adesResults = null;// + + adesResults = AdESResultUtils.getAdESResult(result.getFormVerificationResult()); + + if (Logger.isDebugEnabled()) { + if (adesResults != null) { + final Iterator adesIterator = adesResults.iterator(); + while (adesIterator.hasNext()) { + Logger.debug("ADES Formresults: " + adesIterator.next().toString()); + } + } + } + + responseBuilder.setAdESFormResults(adesResults); + + try { + // Logger.info("Extended Validation Report: " + result.getName()); + Logger.debug("Extended Validation Code: " + result.getResultCode().toString()); + Logger.debug("Extended Validation Info: " + result.getInfo()); + + extCheckResult = AdESResultUtils.getExtendedResult(result.getResultCode()); + responseBuilder.setExtendedCertificateCheckResult(extCheckResult); + + } catch (final NullPointerException e) { + Logger.info("No extendend validation result available."); + } + } + // QC/SSCD check + final List list = plainResult.getCertificateValidationResult().getCertificateChain(); + if (list != null) { + final X509Certificate[] chain = new X509Certificate[list.size()]; + + final Iterator it = list.iterator(); + int i = 0; + while (it.hasNext()) { + chain[i] = (X509Certificate) it.next(); + i++; + } + + qcsscdresult = CertificateUtils.checkQCSSCD(chain, plainResult.getSigningTime(), tp.isTSLEnabled(), + config); + } + + // get signer certificate issuer country code + final String issuerCountryCode = CertificateUtils.getIssuerCountry((X509Certificate) list.get(0)); + + // swap back in the request as root document + if (requestElement != signatureEnvironment.getElement()) { + requestElement.getOwnerDocument().replaceChild(requestElement, signatureEnvironment.getElement()); + signatureEnvironmentParent.appendChild(signatureEnvironment.getElement()); + } + + // check the result + signatureManifestCheck = validateSignatureManifest(request, plainResult, + profile); + + // Check if signer certificate is in trust profile's allowed signer + // certificates pool + final TrustProfile trustProfile = context.getConfiguration().getTrustProfile(request.getTrustProfileId()); + final CheckResult certificateCheck = validateSignerCertificate(plainResult, + trustProfile); + + // build the response + responseBuilder.setResult(plainResult, profile, signatureManifestCheck, + certificateCheck, qcsscdresult.isQC(), qcsscdresult.isQCSourceTSL(), qcsscdresult.isSSCD(), + qcsscdresult.isSSCDSourceTSL(), tp.isTSLEnabled(), issuerCountryCode, qcsscdresult.getTslInfos(), + request.getExtendedValidaiton()); + return responseBuilder.getResponse(); + } + + /** + * Checks if the signer certificate matches one of the allowed signer + * certificates specified in the provided trustProfile. + * + * @param result The result produced by the + * XMLSignatureVerificationModule. + * + * @param trustProfile The trust profile the signer certificate is validated + * against. + * + * @return The overal result of the certificate validation for the signer + * certificate. + * + * @throws MOAException if one of the signer certificates specified in the + * trustProfile cannot be read from the file + * system. + */ + private CheckResult validateSignerCertificate(XMLSignatureVerificationResult result, + TrustProfile trustProfile) + throws MOAException { + final MessageProvider msg = MessageProvider.getInstance(); + + int resultCode = result.getCertificateValidationResult().getValidationResultCode().intValue(); + + if (resultCode == 0 && trustProfile.getSignerCertsUri() != null) { + final X509Certificate signerCertificate = (X509Certificate) result.getCertificateValidationResult() + .getCertificateChain().get(0); + + File signerCertsDir = null; + try { + signerCertsDir = new File(new URI(trustProfile.getSignerCertsUri()).getPath()); + } catch (final URIException e) { + throw new MOASystemException("2900", null, e); // Should not + // happen, + // already + // checked at + // loading the + // MOA + // configuration + } + + final File[] files = signerCertsDir.listFiles(); + if (files == null) { + resultCode = 1; + } + int i; + for (i = 0; i < files.length; i++) { + if (!files[i].isDirectory()) { + FileInputStream currentFIS = null; + try { + currentFIS = new FileInputStream(files[i]); + } catch (final FileNotFoundException e) { + throw new MOASystemException("2900", null, e); + } + + try { + final X509Certificate currentCert = new X509Certificate(currentFIS); + currentFIS.close(); + if (currentCert.equals(signerCertificate)) { + break; + } + } catch (final Exception e) { + // Simply ignore file if it cannot be interpreted as + // certificate + final String logMsg = msg.getMessage("invoker.03", + new Object[] { trustProfile.getId(), files[i].getName() }); + Logger.warn(logMsg); + try { + currentFIS.close(); + } catch (final IOException e1) { + // If clean-up fails, do nothing + } + } + } + } + if (i >= files.length) { + resultCode = 1; // No signer certificate from the trustprofile + // pool matches the actual signer certificate + } + } + + final SPSSFactory factory = SPSSFactory.getInstance(); + return factory.createCheckResult(resultCode, null); + } + + /** + * Select the dsig:Signature DOM element within the signature + * environment. + * + * @param signatureEnvironment The signature environment containing the + * dsig:Signature. + * @param request The VerifyXMLSignatureRequest + * containing the signature environment. + * @return The dsig:Signature element wrapped in a + * XMLSignature object. + * @throws MOAApplicationException An error occurred locating the + * dsig:Signature. + */ + private XMLSignature buildXMLSignature(XMLDataObject signatureEnvironment, + VerifyXMLSignatureRequest request) + throws MOAApplicationException { + + final VerifySignatureLocation signatureLocation = request.getSignatureInfo().getVerifySignatureLocation(); + Element signatureParent; + + // evaluate the VerifySignatureLocation to get the signature parent + signatureParent = InvokerUtils.evaluateSignatureLocation(signatureEnvironment.getElement(), + signatureLocation); + + // check for signatureParent to be a dsig:Signature element + if (!"Signature".equals(signatureParent.getLocalName()) + || !Constants.DSIG_NS_URI.equals(signatureParent.getNamespaceURI())) { + throw new MOAApplicationException("2266", null); + } + + return new XMLSignatureImpl(signatureParent); + } + + /** + * Build the supplemental data objects contained in the + * VerifyXMLSignatureRequest. + * + * @param supplements A List of + * XMLDataObjectAssociations containing the + * supplement data. + * @return A List of DataObjects representing the + * supplemental data objects. + * @throws MOASystemException A system error occurred building one of the + * data objects. + * @throws MOAApplicationException An error occurred building one of the data + * objects. + */ + private List buildDataObjectList(List supplements) throws MOASystemException, MOAApplicationException { + final List dataObjectList = new ArrayList(); + + final DataObjectFactory factory = DataObjectFactory.getInstance(); + DataObject dataObject; + Iterator iter; + + if (supplements != null) { + for (iter = supplements.iterator(); iter.hasNext();) { + final XMLDataObjectAssociation supplement = (XMLDataObjectAssociation) iter.next(); + dataObject = factory.createFromXmlDataObjectAssociation(supplement, true, false); + dataObjectList.add(dataObject); + } + } + + return dataObjectList; + + } + + /** + * Get the supplemental data contained in the + * VerifyXMLSignatureRequest. + * + * @param request The VerifyXMLSignatureRequest containing the + * supplemental data. + * @return A List of XMLDataObjectAssociation objects + * containing the supplemental data. + * @throws MOAApplicationException An error occurred resolving one of the + * supplement profiles. + */ + private List getSupplements(VerifyXMLSignatureRequest request) throws MOAApplicationException { + final TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); + final ConfigurationProvider config = context.getConfiguration(); + final List supplementProfiles = request.getSupplementProfiles(); + + final List supplements = new ArrayList(); + + if (supplementProfiles != null) { + + final List mappedProfiles = ProfileMapper.mapSupplementProfiles(supplementProfiles, config); + Iterator iter; + + for (iter = mappedProfiles.iterator(); iter.hasNext();) { + final SupplementProfileExplicit profile = (SupplementProfileExplicit) iter.next(); + supplements.add(profile.getSupplementProfile()); + } + + } + return supplements; + } + + /** + * Perform additional validations of the + * XMLSignatureVerificationResult. + * + *

+ * In particular, it is verified that: + *

    + *
  • Each ReferenceData object contains transformation chain that + * matches one of the Transforms given in the corresponding + * SignatureManifestCheckParams/ReferenceInfo
  • + *
  • The hash values of the TransformParameters are valid.
  • + *
+ *

+ * + * @param request The VerifyXMLSignatureRequest containing the + * signature to verify. + * @param result The result produced by + * XMLSignatureVerificationModule. + * @param profile The profile used for validating the request. + * @return The result of additional validations of the signature manifest. + * @throws MOAApplicationException Post-validation of the + * XMLSignatureVerificaitonResult + * failed. + */ + private ReferencesCheckResult validateSignatureManifest(VerifyXMLSignatureRequest request, + XMLSignatureVerificationResult result, XMLSignatureVerificationProfile profile) + throws MOAApplicationException { + + final SPSSFactory factory = SPSSFactory.getInstance(); + final MessageProvider msg = MessageProvider.getInstance(); + + // validate that each ReferenceData object contains transforms specified + // in the corresponding SignatureManifestCheckParams/ReferenceInfo + if (request.getSignatureManifestCheckParams() != null) { + final List refInfos = request.getSignatureManifestCheckParams().getReferenceInfos(); + final List refDatas = filterReferenceInfos(result.getReferenceDataList()); + final List failedReferencesList = new ArrayList(); + Iterator refInfoIter; + Iterator refDataIter; + + if (refInfos.size() != refDatas.size()) { + return factory.createReferencesCheckResult(1, null); + } + + refInfoIter = refInfos.iterator(); + refDataIter = filterReferenceInfos(result.getReferenceDataList()).iterator(); + + while (refInfoIter.hasNext()) { + final ReferenceInfo refInfo = (ReferenceInfo) refInfoIter.next(); + final ReferenceData refData = (ReferenceData) refDataIter.next(); + final List transforms = buildTransformsList(refInfo); + boolean found = false; + Iterator trIter; + + for (trIter = transforms.iterator(); trIter.hasNext() && !found;) { + found = trIter.next().equals(refData.getTransformationList()); + } + + if (!found) { + final Integer refIndex = new Integer(refData.getReferenceIndex()); + final String logMsg = msg.getMessage("invoker.01", new Object[] { refIndex }); + + failedReferencesList.add(refIndex); + Logger.debug(new LogMsg(logMsg)); + } + } + + if (!failedReferencesList.isEmpty()) { + // at least one reference failed - return their indexes and + // check code 1 + final int[] failedReferences = CollectionUtils.toIntArray(failedReferencesList); + final ReferencesCheckResultInfo checkInfo = factory.createReferencesCheckResultInfo(null, + failedReferences); + + return factory.createReferencesCheckResult(1, checkInfo); + } + } + + // validate the hashes contained in all the ReferenceInfo objects of the + // security layer manifest + if (request.getSignatureManifestCheckParams() != null && result.containsSecurityLayerManifest()) { + final Map hashValues = buildTransformParameterHashValues(request); + final Set transformParameterURIs = buildTransformParameterURIs(profile.getTransformationSupplements()); + final List referenceInfoList = result.getSecurityLayerManifest().getReferenceDataList(); + Iterator refIter; + + for (refIter = referenceInfoList.iterator(); refIter.hasNext();) { + final iaik.server.modules.xmlverify.ReferenceInfo ref = + (iaik.server.modules.xmlverify.ReferenceInfo) refIter + .next(); + final byte[] hash = (byte[]) hashValues.get(ref.getURI()); + + if (!transformParameterURIs.contains(ref.getURI()) + || hash != null && !Arrays.equals(hash, ref.getHashValue())) { + + // the transform parameter doesn't exist or the hashs do not + // match + // return the index of the failed reference and check code 1 + final int[] failedReferences = new int[] { ref.getReferenceIndex() }; + final ReferencesCheckResultInfo checkInfo = factory.createReferencesCheckResultInfo(null, + failedReferences); + final String logMsg = msg.getMessage("invoker.02", new Object[] { new Integer(ref + .getReferenceIndex()) }); + + Logger.debug(new LogMsg(logMsg)); + + return factory.createReferencesCheckResult(1, checkInfo); + } + } + } + + return factory.createReferencesCheckResult(0, null); + } + + /** + * Get all Transforms contained in all the + * VerifyTransformsInfoProfiles of the given + * ReferenceInfo. + * + * @param refInfo The ReferenceInfo object containing the + * transformations. + * @return A List of Lists. Each of the + * Lists contains Transformation objects. + * @throws MOAApplicationException An error occurred building one of the + * Transformations. + */ + private List buildTransformsList(ReferenceInfo refInfo) throws MOAApplicationException { + + final TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); + final ConfigurationProvider config = context.getConfiguration(); + final List profiles = refInfo.getVerifyTransformsInfoProfiles(); + final List mappedProfiles = ProfileMapper.mapVerifyTransformsInfoProfiles(profiles, config); + final List transformsList = new ArrayList(); + final TransformationFactory factory = TransformationFactory.getInstance(); + Iterator iter; + + for (iter = mappedProfiles.iterator(); iter.hasNext();) { + final VerifyTransformsInfoProfileExplicit profile = (VerifyTransformsInfoProfileExplicit) iter.next(); + final List transforms = profile.getTransforms(); + + if (transforms != null) { + transformsList.add(factory.createTransformationList(transforms)); + } + } + + return transformsList; + } + + /** + * Build the Set of all TransformParameter URIs. + * + * @param transformParameters The List of + * TransformParameters, as provided to + * the verification. + * @return The Set of all TransformParameter URIs. + */ + private Set buildTransformParameterURIs(List transformParameters) { + final Set uris = new HashSet(); + Iterator iter; + + for (iter = transformParameters.iterator(); iter.hasNext();) { + final DataObject transformParameter = (DataObject) iter.next(); + uris.add(transformParameter.getURI()); + } + + return uris; + } + + /** + * Build a mapping between TransformParameter URIs (a + * String and dsig:HashValue (a byte[]). + * + * @param request The VerifyXMLSignatureRequest. + * @return Map The resulting mapping. + * @throws MOAApplicationException An error occurred accessing one of the + * profiles. + */ + private Map buildTransformParameterHashValues(VerifyXMLSignatureRequest request) + throws MOAApplicationException { + + final TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); + final ConfigurationProvider config = context.getConfiguration(); + final Map hashValues = new HashMap(); + final List refInfos = request.getSignatureManifestCheckParams().getReferenceInfos(); + Iterator refIter; + + for (refIter = refInfos.iterator(); refIter.hasNext();) { + final ReferenceInfo refInfo = (ReferenceInfo) refIter.next(); + final List profiles = refInfo.getVerifyTransformsInfoProfiles(); + final List mappedProfiles = ProfileMapper.mapVerifyTransformsInfoProfiles(profiles, config); + Iterator prIter; + + for (prIter = mappedProfiles.iterator(); prIter.hasNext();) { + final VerifyTransformsInfoProfileExplicit profile = (VerifyTransformsInfoProfileExplicit) prIter + .next(); + final List trParameters = profile.getTransformParameters(); + Iterator trIter; + + for (trIter = trParameters.iterator(); trIter.hasNext();) { + final TransformParameter transformParameter = (TransformParameter) trIter.next(); + final String uri = transformParameter.getURI(); + + if (transformParameter.getTransformParameterType() == TransformParameter.HASH_TRANSFORMPARAMETER) { + hashValues.put(uri, ((TransformParameterHash) transformParameter).getDigestValue()); + } + + } + } + } + return hashValues; + } + + /** + * Filter the ReferenceInfos returned by the + * VerifyXMLSignatureResult for comparison with the + * ReferenceInfo elements in the request. + * + * @param referenceInfos The ReferenceInfos from the + * VerifyXMLSignatureResult. + * @return A List of all ReferenceInfos whose type is + * not a XMLDsig manifest, Security Layer manifest, or ETSI signed + * property. + */ + private List filterReferenceInfos(List referenceInfos) { + final List filtered = new ArrayList(); + Iterator iter; + + for (iter = referenceInfos.iterator(); iter.hasNext();) { + final iaik.server.modules.xmlverify.ReferenceInfo refInfo = + (iaik.server.modules.xmlverify.ReferenceInfo) iter + .next(); + final String refType = refInfo.getReferenceType(); + + if (refType == null || !FILTERED_REF_TYPES.contains(refType)) { + filtered.add(refInfo); + } + } + + return filtered; + } + + private List getAdESResult(ExtendedXMLSignatureVerificationResult adesFormVerification) + throws ConfigurationException { + if (adesFormVerification == null) { + // no form information + return null; + } + + final List adesList = new ArrayList(); + + /* + * checkSubResult(adesFormVerification.getSubResult(SignatureVerificationProfile + * .LEVEL_LTA), SignatureVerificationProfile.LEVEL_LTA, adesList); + * checkSubResult(adesFormVerification.getSubResult(SignatureVerificationProfile + * .LEVEL_LT), SignatureVerificationProfile.LEVEL_LT, adesList); + * checkSubResult(adesFormVerification.getSubResult(SignatureVerificationProfile + * .LEVEL_T), SignatureVerificationProfile.LEVEL_T, adesList); + * checkSubResult(adesFormVerification.getSubResult(SignatureVerificationProfile + * .LEVEL_B), SignatureVerificationProfile.LEVEL_B, adesList); + */ + + AdESResultUtils.checkSubResult(adesFormVerification.getSubResult( + iaik.esi.sva.util.Constants.LONG_TERM_VALIDATION), + SignatureVerificationProfile.LEVEL_LT, adesList); + AdESResultUtils.checkSubResult(adesFormVerification.getSubResult( + iaik.esi.sva.util.Constants.ADES_T_VALIDATION), + SignatureVerificationProfile.LEVEL_T, adesList); + AdESResultUtils.checkSubResult(adesFormVerification.getSubResult("basic report"), + SignatureVerificationProfile.LEVEL_B, adesList); + + return adesList; + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/XMLSignatureVerificationProfileFactory.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/XMLSignatureVerificationProfileFactory.java index 3e4c712..7fcd0e9 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/XMLSignatureVerificationProfileFactory.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/invoke/XMLSignatureVerificationProfileFactory.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.invoke; import java.util.ArrayList; @@ -29,8 +28,6 @@ import java.util.Collections; import java.util.Iterator; import java.util.List; -import iaik.server.modules.xmlverify.XMLSignatureVerificationProfile; - import at.gv.egovernment.moa.spss.MOAApplicationException; import at.gv.egovernment.moa.spss.MOASystemException; import at.gv.egovernment.moa.spss.api.xmlverify.ReferenceInfo; @@ -43,26 +40,29 @@ import at.gv.egovernment.moa.spss.server.iaik.pki.PKIProfileImpl; import at.gv.egovernment.moa.spss.server.iaik.xmlverify.XMLSignatureVerificationProfileImpl; import at.gv.egovernment.moa.spss.server.transaction.TransactionContext; import at.gv.egovernment.moa.spss.server.transaction.TransactionContextManager; +import iaik.server.modules.xmlverify.XMLSignatureVerificationProfile; /** * A factory to create a XMLSignatureVerificationProfile from a * VerifyXMLSignatureRequest, based on the current MOA * configuration. - * + * * @author Patrick Peck * @version $Id$ */ public class XMLSignatureVerificationProfileFactory { - /** The VerifyXMLSignatureRequest for which to create profile - * information. */ - private VerifyXMLSignatureRequest request; + /** + * The VerifyXMLSignatureRequest for which to create profile + * information. + */ + private final VerifyXMLSignatureRequest request; /** * Create a new XMLSignatureVerificationProfileFactory. - * - * @param request The VerifyXMLSignatureRequest to extract - * profile data from. + * + * @param request The VerifyXMLSignatureRequest to extract profile + * data from. */ public XMLSignatureVerificationProfileFactory(VerifyXMLSignatureRequest request) { this.request = request; @@ -71,19 +71,19 @@ public class XMLSignatureVerificationProfileFactory { /** * Create a XMLSignatureCreationProfile from the * VerifyXMLSignaturesRequest and the current MOA configuration. - * + * * @return The XMLSignatureVerificationProfile containing - * additional information for verifying an XML signature. - * @throws MOASystemException A system error occurred building the profile. + * additional information for verifying an XML signature. + * @throws MOASystemException A system error occurred building the profile. * @throws MOAApplicationException An error occurred building the profile. */ public XMLSignatureVerificationProfile createProfile() - throws MOASystemException, MOAApplicationException { - TransactionContext context = - TransactionContextManager.getInstance().getTransactionContext(); - ConfigurationProvider config = context.getConfiguration(); - XMLSignatureVerificationProfileImpl profile = - new XMLSignatureVerificationProfileImpl(); + throws MOASystemException, MOAApplicationException { + final TransactionContext context = + TransactionContextManager.getInstance().getTransactionContext(); + final ConfigurationProvider config = context.getConfiguration(); + final XMLSignatureVerificationProfileImpl profile = + new XMLSignatureVerificationProfileImpl(); SignatureManifestCheckParams checkParams; String trustProfileID; @@ -93,49 +93,50 @@ public class XMLSignatureVerificationProfileFactory { // set the certificate validation profile trustProfileID = request.getTrustProfileId(); profile.setCertificateValidationProfile( - new PKIProfileImpl(config, trustProfileID)); + new PKIProfileImpl(config, trustProfileID)); // set whether hash input data is to be included profile.setIncludeHashInputData(request.getReturnHashInputData()); // set the security layer manifest check parameters - // and transformation supplements (if present) + // and transformation supplements (if present) checkParams = request.getSignatureManifestCheckParams(); profile.setCheckSecurityLayerManifest(true); - profile.setIncludeReferenceInputData(checkParams != null ? checkParams.getReturnReferenceInputData() : false); + profile.setIncludeReferenceInputData(checkParams != null ? checkParams.getReturnReferenceInputData() + : false); if (checkParams != null) { - List transformationSupplements; - transformationSupplements = buildTransformationSupplements(); - profile.setTransformationSupplements(transformationSupplements); + List transformationSupplements; + transformationSupplements = buildTransformationSupplements(); + profile.setTransformationSupplements(transformationSupplements); } else { - profile.setTransformationSupplements(Collections.EMPTY_LIST); + profile.setTransformationSupplements(Collections.EMPTY_LIST); } - + profile.setPermitFileURIs(config.getPermitFileURIs()); - + return profile; } /** * Build supplemental data objects used in the transformations. - * + * * @return A List of DataObjects providing - * supplemental data to the transformations. - * @throws MOASystemException A system error occurred building one of the - * transformations. + * supplemental data to the transformations. + * @throws MOASystemException A system error occurred building one of the + * transformations. * @throws MOAApplicationException An error occurred building one of the - * transformations. + * transformations. */ public List buildTransformationSupplements() - throws MOASystemException, MOAApplicationException { - TransactionContext context = - TransactionContextManager.getInstance().getTransactionContext(); - ConfigurationProvider config = context.getConfiguration(); - SignatureManifestCheckParams checkParams = - request.getSignatureManifestCheckParams(); - List transformsProfiles = new ArrayList(); - List transformationSupplements = new ArrayList(); - DataObjectFactory factory = DataObjectFactory.getInstance(); + throws MOASystemException, MOAApplicationException { + final TransactionContext context = + TransactionContextManager.getInstance().getTransactionContext(); + final ConfigurationProvider config = context.getConfiguration(); + final SignatureManifestCheckParams checkParams = + request.getSignatureManifestCheckParams(); + final List transformsProfiles = new ArrayList(); + final List transformationSupplements = new ArrayList(); + final DataObjectFactory factory = DataObjectFactory.getInstance(); List refInfos = checkParams.getReferenceInfos(); Iterator refIter; Iterator prIter; @@ -144,26 +145,26 @@ public class XMLSignatureVerificationProfileFactory { // build the list of all VerifyTransformsInfoProfiles in all ReferenceInfos refInfos = checkParams.getReferenceInfos(); for (refIter = refInfos.iterator(); refIter.hasNext();) { - ReferenceInfo refInfo = (ReferenceInfo) refIter.next(); - List profiles = refInfo.getVerifyTransformsInfoProfiles(); + final ReferenceInfo refInfo = (ReferenceInfo) refIter.next(); + final List profiles = refInfo.getVerifyTransformsInfoProfiles(); transformsProfiles.addAll( - ProfileMapper.mapVerifyTransformsInfoProfiles(profiles, config)); + ProfileMapper.mapVerifyTransformsInfoProfiles(profiles, config)); } // build the DataObjects for (prIter = transformsProfiles.iterator(); prIter.hasNext();) { - VerifyTransformsInfoProfileExplicit profile = - (VerifyTransformsInfoProfileExplicit) prIter.next(); - List transformParameters = profile.getTransformParameters(); + final VerifyTransformsInfoProfileExplicit profile = + (VerifyTransformsInfoProfileExplicit) prIter.next(); + final List transformParameters = profile.getTransformParameters(); for (trIter = transformParameters.iterator(); trIter.hasNext();) { - TransformParameter trParam = (TransformParameter) trIter.next(); + final TransformParameter trParam = (TransformParameter) trIter.next(); transformationSupplements.add( - factory.createFromTransformParameter(trParam)); + factory.createFromTransformParameter(trParam)); } } - + return transformationSupplements; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/logging/IaikLog.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/logging/IaikLog.java index dcb1397..f477588 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/logging/IaikLog.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/logging/IaikLog.java @@ -21,20 +21,17 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.logging; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import iaik.logging.TransactionId; /** - * An implementation of the iaik.logging.Log - * interface that is based on Jakarta Commons-Logging. - * + * An implementation of the iaik.logging.Log interface that is + * based on Jakarta Commons-Logging. + * * @author Fatemeh Philippi * @version $Id$ */ @@ -45,11 +42,11 @@ public class IaikLog implements iaik.logging.Log { private static Logger log = LoggerFactory.getLogger(IAIK_LOG_HIERARCHY); /** The node ID to use. */ private String nodeId; - + /** * Create a new IaikLog. - * - * @param nodeId The node ID for this Log object. + * + * @param nodeId The node ID for this Log object. */ public IaikLog(String nodeId) { this.nodeId = nodeId; @@ -58,6 +55,7 @@ public class IaikLog implements iaik.logging.Log { /** * @see iaik.logging.Log#isDebugEnabled() */ + @Override public boolean isDebugEnabled() { return log.isDebugEnabled(); } @@ -65,8 +63,9 @@ public class IaikLog implements iaik.logging.Log { /** * @see iaik.logging.Log#debug(TransactionId, Object, Throwable) */ + @Override public void debug(TransactionId transactionId, Object message, Throwable t) { - IaikLogMsg msg = new IaikLogMsg(transactionId, nodeId, message); + final IaikLogMsg msg = new IaikLogMsg(transactionId, nodeId, message); log.debug(msg.toString(), t); } @@ -74,6 +73,7 @@ public class IaikLog implements iaik.logging.Log { /** * @see iaik.logging.Log#isInfoEnabled() */ + @Override public boolean isInfoEnabled() { return log.isInfoEnabled(); } @@ -81,8 +81,9 @@ public class IaikLog implements iaik.logging.Log { /** * @see iaik.logging.Log#info(TransactionId, Object, Throwable) */ + @Override public void info(TransactionId transactionId, Object message, Throwable t) { - IaikLogMsg msg = new IaikLogMsg(transactionId, nodeId, message); + final IaikLogMsg msg = new IaikLogMsg(transactionId, nodeId, message); log.info(msg.toString(), t); } @@ -90,6 +91,7 @@ public class IaikLog implements iaik.logging.Log { /** * @see iaik.logging.Log#isWarnEnabled() */ + @Override public boolean isWarnEnabled() { return log.isWarnEnabled(); } @@ -97,8 +99,9 @@ public class IaikLog implements iaik.logging.Log { /** * @see iaik.logging.Log#warn(TransactionId, Object, Throwable) */ + @Override public void warn(TransactionId transactionId, Object message, Throwable t) { - IaikLogMsg msg = new IaikLogMsg(transactionId, nodeId, message); + final IaikLogMsg msg = new IaikLogMsg(transactionId, nodeId, message); log.warn(msg.toString(), t); } @@ -106,6 +109,7 @@ public class IaikLog implements iaik.logging.Log { /** * @see iaik.logging.Log#isErrorEnabled() */ + @Override public boolean isErrorEnabled() { return log.isErrorEnabled(); } @@ -113,8 +117,9 @@ public class IaikLog implements iaik.logging.Log { /** * @see iaik.logging.Log#error(TransactionId, Object, Throwable) */ + @Override public void error(TransactionId transactionId, Object message, Throwable t) { - IaikLogMsg msg = new IaikLogMsg(transactionId, nodeId, message); + final IaikLogMsg msg = new IaikLogMsg(transactionId, nodeId, message); log.error(msg.toString(), t); } @@ -122,6 +127,7 @@ public class IaikLog implements iaik.logging.Log { /** * @see iaik.logging.Log#isFatalEnabled() */ + @Override public boolean isFatalEnabled() { return log.isErrorEnabled(); } @@ -129,8 +135,9 @@ public class IaikLog implements iaik.logging.Log { /** * @see iaik.logging.Log#fatal(TransactionId, Object, Throwable) */ + @Override public void fatal(TransactionId transactionId, Object message, Throwable t) { - IaikLogMsg msg = new IaikLogMsg(transactionId, nodeId, message); + final IaikLogMsg msg = new IaikLogMsg(transactionId, nodeId, message); log.error(msg.toString(), t); } @@ -138,6 +145,7 @@ public class IaikLog implements iaik.logging.Log { /** * @see iaik.logging.Log#setNodeId(String) */ + @Override public void setNodeId(String nodeId) { this.nodeId = nodeId; } @@ -145,6 +153,7 @@ public class IaikLog implements iaik.logging.Log { /** * @see iaik.logging.Log#getNodeId() */ + @Override public String getNodeId() { return nodeId; } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/logging/IaikLogFactory.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/logging/IaikLogFactory.java index 9989087..e0a4ea6 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/logging/IaikLogFactory.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/logging/IaikLogFactory.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.logging; import at.gv.egovernment.moaspss.logging.LoggingContext; @@ -31,36 +30,40 @@ import iaik.logging.LogConfigurationException; import iaik.logging.LogFactory; /** - * An implementation of the iaik.logging.LogFactory abstract - * class to log messages to the MOA logging subsystem. - * + * An implementation of the iaik.logging.LogFactory abstract class + * to log messages to the MOA logging subsystem. + * * @author Patrick Peck * @version $Id$ */ public class IaikLogFactory extends LogFactory { + @Override public Log getInstance(Class clazz) throws LogConfigurationException { return getInstanceImpl(clazz.getName()); } + @Override public Log getInstance(String name) throws LogConfigurationException { return getInstanceImpl(name); } /** * Return an instance of iaik.logging.Log. - * + * * @return The iaik.logging.Log object to log messages to. - */ + */ private Log getInstanceImpl(String name) { - LoggingContext context = LoggingContextManager.getInstance().getLoggingContext(); - if (context != null) - return new IaikLog(context.getNodeID()); - else - return new IaikLog("Internal"); - + final LoggingContext context = LoggingContextManager.getInstance().getLoggingContext(); + if (context != null) { + return new IaikLog(context.getNodeID()); + } else { + return new IaikLog("Internal"); + } + } + @Override public void release() { // we do not hold any resources } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/logging/IaikLogMsg.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/logging/IaikLogMsg.java index 7e4ff84..d096b2e 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/logging/IaikLogMsg.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/logging/IaikLogMsg.java @@ -21,34 +21,33 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.logging; import iaik.logging.TransactionId; /** * A unified message type to log messages from the IAIK subsystem. - * + * * @author Patrick Peck * @version $Id$ */ public class IaikLogMsg { - + /** The transaction ID of this message. */ - private TransactionId transactionId; + private final TransactionId transactionId; /** The node ID of this message. */ - private String nodeId; + private final String nodeId; /** The message to log. */ - private Object message; - + private final Object message; + /** * Create a IaikLogMsg object. - * - * @param transactionId The transaction id of the transaction which - * generated this log message. May be null. - * @param nodeId The node id where this message was generated. May be - * null. - * @param message The actual message to log. May be null. + * + * @param transactionId The transaction id of the transaction which generated + * this log message. May be null. + * @param nodeId The node id where this message was generated. May be + * null. + * @param message The actual message to log. May be null. */ public IaikLogMsg(TransactionId transactionId, String nodeId, Object message) { this.transactionId = transactionId; @@ -56,22 +55,22 @@ public class IaikLogMsg { this.message = message; } - /** * Convert this log message to a String. - * - * @return The String representation of this log message. + * + * @return The String representation of this log message. */ + @Override public String toString() { - StringBuffer msg = new StringBuffer(); - + final StringBuffer msg = new StringBuffer(); + msg.append("TID="); msg.append(transactionId != null ? transactionId.getLogID() : ""); msg.append(" NID="); msg.append(nodeId != null ? nodeId : ""); msg.append(" MSG="); msg.append(message != null ? message.toString() : ""); - + return msg.toString(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/logging/TransactionId.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/logging/TransactionId.java index ba76c0b..75623fd 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/logging/TransactionId.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/logging/TransactionId.java @@ -21,25 +21,24 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.logging; /** * An implementation of the iaik.logging.TransactionId interface. - * + * * @author Patrick Peck * @version $Id$ */ public class TransactionId implements iaik.logging.TransactionId { - + /** The String representation for logging the transaction ID. */ - private String logID; - + private final String logID; + /** * Create a TransactionId object. - * + * * @param logID The transaction id as it should be presented to the logging - * subsystem. + * subsystem. */ public TransactionId(String logID) { this.logID = logID; @@ -48,13 +47,15 @@ public class TransactionId implements iaik.logging.TransactionId { /** * @see iaik.logging.TransactionId#getLogID() */ + @Override public String getLogID() { return logID; } - + /** * @see java.lang.Object#toString() */ + @Override public String toString() { return getLogID(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/monitoring/ServiceStatusContainer.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/monitoring/ServiceStatusContainer.java index 3d100a4..9c5bef3 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/monitoring/ServiceStatusContainer.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/monitoring/ServiceStatusContainer.java @@ -7,37 +7,38 @@ import at.gv.egovernment.moa.spss.tsl.TSLServiceFactory; public class ServiceStatusContainer { - public static final String STATUS_NOT_SET = "no status message"; - public static final String STATUS_OK = "ok"; - - private static boolean TSLStatusValid = false; - private static String TSLStatusMsg = STATUS_NOT_SET; - private static List tslDetailStatus = null; - - public static boolean getStatus() { - return TSLStatusValid; - - } - - public static String getStatusMsg() { - return TSLStatusMsg; - - } - - public static List getTslDetailStatus() { - return tslDetailStatus; - } - - public static void setStatus(boolean currentStatus) { - TSLStatusValid = currentStatus; - - if (TSLServiceFactory.isInitialized()) - tslDetailStatus = TSLServiceFactory.getTSLServiceClient().getCurrentTSLClientStatus(); - - } - - public static void setStatusMsg(String msg) { - TSLStatusMsg = msg; - } - + public static final String STATUS_NOT_SET = "no status message"; + public static final String STATUS_OK = "ok"; + + private static boolean TSLStatusValid = false; + private static String TSLStatusMsg = STATUS_NOT_SET; + private static List tslDetailStatus = null; + + public static boolean getStatus() { + return TSLStatusValid; + + } + + public static String getStatusMsg() { + return TSLStatusMsg; + + } + + public static List getTslDetailStatus() { + return tslDetailStatus; + } + + public static void setStatus(boolean currentStatus) { + TSLStatusValid = currentStatus; + + if (TSLServiceFactory.isInitialized()) { + tslDetailStatus = TSLServiceFactory.getTSLServiceClient().getCurrentTSLClientStatus(); + } + + } + + public static void setStatusMsg(String msg) { + TSLStatusMsg = msg; + } + } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/service/RevocationArchiveCleaner.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/service/RevocationArchiveCleaner.java index d3a930c..1d85d66 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/service/RevocationArchiveCleaner.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/service/RevocationArchiveCleaner.java @@ -21,13 +21,8 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.service; -import iaik.pki.revocation.RevocationSourceTypes; -import iaik.pki.store.revocation.archive.Archive; -import iaik.pki.store.revocation.archive.ArchiveFactory; - import java.util.Date; import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; @@ -35,64 +30,67 @@ import at.gv.egovernment.moa.spss.server.logging.TransactionId; import at.gv.egovernment.moa.spss.util.MessageProvider; import at.gv.egovernment.moaspss.logging.LogMsg; import at.gv.egovernment.moaspss.logging.Logger; +import iaik.pki.revocation.RevocationSourceTypes; +import iaik.pki.store.revocation.archive.Archive; +import iaik.pki.store.revocation.archive.ArchiveFactory; /** - * A Runnable for periodically cleaning up the revocation archive. + * A Runnable for periodically cleaning up the revocation archive. + * * @author Patrick Peck * @version $Id$ */ public class RevocationArchiveCleaner implements Runnable { /** The inverval between two clean-ups of the revocation archive. */ - private long archiveCleanupInterval; + private final long archiveCleanupInterval; /** * Create a new RevocationArchiveCleaner. - * + * * @param archiveCleanupInterval The interval between two clean-ups of the - * revocation archive. + * revocation archive. */ public RevocationArchiveCleaner(long archiveCleanupInterval) { this.archiveCleanupInterval = archiveCleanupInterval; } /** - * Run the RevocationArchiveCleaner in its own - * Thread. + * Run the RevocationArchiveCleaner in its own Thread. */ + @Override public void run() { while (true) { try { - ConfigurationProvider config = ConfigurationProvider.getInstance(); - boolean enableArchiving = config.getEnableRevocationArchiving(); + final ConfigurationProvider config = ConfigurationProvider.getInstance(); + final boolean enableArchiving = config.getEnableRevocationArchiving(); - if (enableArchiving) - { - Archive archive = ArchiveFactory.getInstance().getArchive(); - long archiveDurationMillis = - (long) config.getCRLArchiveDuration() * 86400000; + if (enableArchiving) { + final Archive archive = ArchiveFactory.getInstance().getArchive(); + final long archiveDurationMillis = + (long) config.getCRLArchiveDuration() * 86400000; // delete old archive data if (archiveDurationMillis > 0) { - Date olderThan = - new Date(System.currentTimeMillis() - archiveDurationMillis); + final Date olderThan = + new Date(System.currentTimeMillis() - archiveDurationMillis); archive.deleteOldArchiveEntries( - RevocationSourceTypes.CRL, - olderThan, - new TransactionId("RevocationArchiveCleaner")); + RevocationSourceTypes.CRL, + olderThan, + new TransactionId("RevocationArchiveCleaner")); } } - } catch (Exception e) { - MessageProvider msg = MessageProvider.getInstance(); + } catch (final Exception e) { + final MessageProvider msg = MessageProvider.getInstance(); Logger.error(new LogMsg(msg.getMessage("init.02", null)), e); } - // sleep + // sleep try { Thread.sleep(archiveCleanupInterval * 1000); - } catch (InterruptedException e) { + } catch (final InterruptedException e) { // ok to do nothing here } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/transaction/DeleteableDataSource.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/transaction/DeleteableDataSource.java index a5ea592..335bf68 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/transaction/DeleteableDataSource.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/transaction/DeleteableDataSource.java @@ -3,5 +3,5 @@ package at.gv.egovernment.moa.spss.server.transaction; import javax.activation.DataSource; public interface DeleteableDataSource extends DataSource { - public void delete(); + void delete(); } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/transaction/TransactionContext.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/transaction/TransactionContext.java index 4e0d9f6..5746657 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/transaction/TransactionContext.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/transaction/TransactionContext.java @@ -21,11 +21,8 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.transaction; -import iaik.xml.crypto.utils.URI; - import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; @@ -33,23 +30,23 @@ import java.io.InputStream; import java.security.cert.X509Certificate; import java.util.HashMap; import java.util.Iterator; +import java.util.Map.Entry; import java.util.Vector; import javax.activation.DataSource; -import java.util.Map.Entry; - import org.w3c.dom.Element; import at.gv.egovernment.moa.spss.MOAApplicationException; import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; import at.gv.egovernment.moaspss.logging.Logger; +import iaik.xml.crypto.utils.URI; /** * Contains information about the current request. - * + * * @author Stefan Knirsch - * @author Patrick Peck + * @author Patrick Peck */ public class TransactionContext { @@ -69,18 +66,19 @@ public class TransactionContext { private HashMap resolvedEntities = null; /** The configuration to use throughout the request. */ private ConfigurationProvider configuration = null; - + /** * Create a TransactionContext object. - * - * @param transactionID A unique ID for this TransactionContext. + * + * @param transactionID A unique ID for this + * TransactionContext. * @param clientCertificate The client certificate chain. - * @param configuration The MOA configuration to use for this transaction. + * @param configuration The MOA configuration to use for this transaction. */ public TransactionContext( - String transactionID, - X509Certificate[] clientCertificate, - ConfigurationProvider configuration) { + String transactionID, + X509Certificate[] clientCertificate, + ConfigurationProvider configuration) { this.transactionID = transactionID; this.clientCertificate = clientCertificate; @@ -89,18 +87,19 @@ public class TransactionContext { /** * Create a TransactionContext object. - * - * @param transactionID A unique ID for this TransactionContext. + * + * @param transactionID A unique ID for this + * TransactionContext. * @param clientCertificate The client certificate chain. - * @param configuration The MOA configuration to use for this transaction. - * @param attachments to use for this transaction. + * @param configuration The MOA configuration to use for this transaction. + * @param attachments to use for this transaction. */ public TransactionContext( - String transactionID, - X509Certificate[] clientCertificate, - ConfigurationProvider configuration, - Element request, - HashMap attachments) { + String transactionID, + X509Certificate[] clientCertificate, + ConfigurationProvider configuration, + Element request, + HashMap attachments) { this.transactionID = transactionID; this.clientCertificate = clientCertificate; @@ -108,14 +107,14 @@ public class TransactionContext { this.request = request; this.attachments = attachments; } - + /** * Returns the client certificate. - * + * * @return The client certificate chain, if SSL client authentication has been - * configured in the web server and has been used by the client. The 0th - * element of the array contains the client certificate. null - * otherwise. + * configured in the web server and has been used by the client. The 0th + * element of the array contains the client certificate. + * null otherwise. */ public X509Certificate[] getClientCertificate() { return clientCertificate; @@ -123,7 +122,7 @@ public class TransactionContext { /** * Returns the unique transaction ID. - * + * * @return The transaction ID. */ public String getTransactionID() { @@ -132,7 +131,7 @@ public class TransactionContext { /** * Returns the name of the request. - * + * * @return The name of the request. */ public String getRequestName() { @@ -141,7 +140,7 @@ public class TransactionContext { /** * Sets the name of the request. - * + * * @param requestName The request name to set. */ public void setRequestName(String requestName) { @@ -150,7 +149,7 @@ public class TransactionContext { /** * Sets the the request. - * + * * @param request The request to set. */ public void setRequest(Element request) { @@ -159,7 +158,7 @@ public class TransactionContext { /** * Returns the request. - * + * * @return The request. */ public Element getRequest() { @@ -168,7 +167,7 @@ public class TransactionContext { /** * Sets the the response. - * + * * @param response The response to set. */ public void setResponse(Element response) { @@ -177,23 +176,26 @@ public class TransactionContext { /** * Returns the response. - * + * * @return The response. */ public Element getResponse() { return response; } - + /** * Adds an attachment to the transactions list of SOAP attachments. - * + * * @param referenceId Identification value for the SOAP attachment. * @param contentType MIME type of the SOAP attachment. - * @param is Handle to the ManagedMemoryDataSource of the SOAP attachment. + * @param is Handle to the ManagedMemoryDataSource of the SOAP + * attachment. */ public void addAttachment(String referenceId, String contentType, DataSource is) { - if (this.attachments == null) this.attachments = new HashMap(); - Vector entry = new Vector(2); + if (this.attachments == null) { + this.attachments = new HashMap(); + } + final Vector entry = new Vector(2); entry.add(contentType); entry.add(is); this.attachments.put(referenceId, entry); @@ -201,185 +203,198 @@ public class TransactionContext { /** * Adds an attachment to the transactions list of SOAP attachments. - * + * * @param referenceId Identification value for the SOAP attachment. * @param contentType MIME type of the SOAP attachment. - * @param is Handle to the InputStream of the SOAP attachment. - * @param filename Filename of the temporary file the InputStream belongs to + * @param is Handle to the InputStream of the SOAP attachment. + * @param filename Filename of the temporary file the InputStream belongs to */ public void addAttachment(String referenceId, String contentType, InputStream is, String filename) { - if (this.attachments == null) this.attachments = new HashMap(); - Vector entry = new Vector(3); + if (this.attachments == null) { + this.attachments = new HashMap(); + } + final Vector entry = new Vector(3); entry.add(contentType); entry.add(is); entry.add(filename); this.attachments.put(referenceId, entry); } - + /** - * Returns the ManagedMemoryDataSource to a specific SOAP attachment identified by referenceId. - * + * Returns the ManagedMemoryDataSource to a specific SOAP attachment identified + * by referenceId. + * * @param referenceId Identification value for the SOAP attachment. */ public DataSource getAttachment(String referenceId) { - if (attachments==null) { + if (attachments == null) { return null; } - Vector entry = (Vector) attachments.get(referenceId); - if (entry==null) { + final Vector entry = (Vector) attachments.get(referenceId); + if (entry == null) { return null; } - Object object = entry.get(1); + final Object object = entry.get(1); if (object instanceof DataSource) { - return (DataSource) object; + return (DataSource) object; } else { - return null; + return null; } } - + /** * Returns the InputStream to a specific SOAP attachment identified by uri. - * + * * @param uri Identification value for the SOAP attachment. */ public InputStream getAttachmentInputStream(URI uri) throws MOAApplicationException { - if (attachments==null) { + if (attachments == null) { return null; } - String referenceId = uri.getPath(); - Vector entry = (Vector) attachments.get(referenceId); - if (entry==null) { + final String referenceId = uri.getPath(); + final Vector entry = (Vector) attachments.get(referenceId); + if (entry == null) { return null; } InputStream attachmentIs = null; - Object object = entry.get(1); - + final Object object = entry.get(1); + if (object instanceof DataSource) { - try { - attachmentIs = (InputStream) ( ((DataSource)object).getInputStream()); - } catch (IOException e) { - throw new MOAApplicationException("2208", new Object[] { uri }, e); - } + try { + attachmentIs = ((DataSource) object).getInputStream(); + } catch (final IOException e) { + throw new MOAApplicationException("2208", new Object[] { uri }, e); + } } else { - attachmentIs = (InputStream) object; + attachmentIs = (InputStream) object; } return attachmentIs; - //If we would return the whole mmds: return (ManagedMemoryDataSource) entry.get(1); + // If we would return the whole mmds: return (ManagedMemoryDataSource) + // entry.get(1); } - + /** - * Returns the content type to a specific SOAP attachment identified by referenceId. - * + * Returns the content type to a specific SOAP attachment identified by + * referenceId. + * * @param referenceId Identification value for the SOAP attachment. */ public String getAttachmentContentType(String referenceId) { - Vector entry = (Vector) attachments.get(referenceId); - if (entry==null) { + final Vector entry = (Vector) attachments.get(referenceId); + if (entry == null) { return null; } return (String) entry.get(0); } - + /** * Delete the temporary attachment files. */ -public void cleanAttachmentCache() { - if (null==attachments) { + public void cleanAttachmentCache() { + if (null == attachments) { return; } - Iterator iterator = attachments.entrySet().iterator(); + final Iterator iterator = attachments.entrySet().iterator(); while (iterator.hasNext()) { - Entry hmEntry = (Entry) iterator.next(); - Vector entry = (Vector)hmEntry.getValue(); - Object object = entry.get(1); + final Entry hmEntry = (Entry) iterator.next(); + final Vector entry = (Vector) hmEntry.getValue(); + final Object object = entry.get(1); if (object instanceof DataSource) { - DataSource mmds = (DataSource)object; - try { - if (mmds!=null) { - InputStream is = mmds.getInputStream(); - if (is!=null) is.close(); -// not available in Axis 1.0 to 1.1 + final DataSource mmds = (DataSource) object; + try { + if (mmds != null) { + final InputStream is = mmds.getInputStream(); + if (is != null) { + is.close(); + } +// not available in Axis 1.0 to 1.1 // File f = mmds.getDiskCacheFile(); // if (f!=null) f.delete(); - if(mmds instanceof DeleteableDataSource) { - ((DeleteableDataSource)mmds).delete(); - } - //mmds..delete(); - } - } catch (IOException e) { - // ok to do nothing here - } + if (mmds instanceof DeleteableDataSource) { + ((DeleteableDataSource) mmds).delete(); + } + // mmds..delete(); + } + } catch (final IOException e) { + // ok to do nothing here + } } else if (object instanceof InputStream) { - InputStream is = (InputStream)object; - try { - if (is!=null) is.close(); - String tempFile = (String) entry.get(2); - if (tempFile!=null){ - File f = new File(tempFile); - f.delete(); - } - } catch (IOException e) { - // ok to do nothing here - } + final InputStream is = (InputStream) object; + try { + if (is != null) { + is.close(); + } + final String tempFile = (String) entry.get(2); + if (tempFile != null) { + final File f = new File(tempFile); + f.delete(); + } + } catch (final IOException e) { + // ok to do nothing here + } } } } - + /** * Returns the ConfigurationProvider associated with this * transaction. - * - * @return The ConfigurationProvider associated with this transaction. + * + * @return The ConfigurationProvider associated with this transaction. */ public ConfigurationProvider getConfiguration() { return configuration; } - + /** * Search an uri content in cashed map. - * + * * @param uri The value to look for. * @return If found the cached entity, null otherwise. */ public Vector FindResolvedEntity(String uri) { - if (resolvedEntities==null) return null; - return (Vector) resolvedEntities.get(uri); + if (resolvedEntities == null) { + return null; + } + return (Vector) resolvedEntities.get(uri); } - + /** * Get a new InputStream of a cached entity. - * + * * @param uri The value to look for. * @return A new InputStream of the cached entity. */ public InputStream ResolveURI(String uri) { - InputStream is = null; - Vector entity = FindResolvedEntity(uri); - if (entity!=null) { - byte[] contentBytes = (byte[]) entity.get(0); - if (contentBytes!=null) { - is = new ByteArrayInputStream(contentBytes); - } - } - return is; + InputStream is = null; + final Vector entity = FindResolvedEntity(uri); + if (entity != null) { + final byte[] contentBytes = (byte[]) entity.get(0); + if (contentBytes != null) { + is = new ByteArrayInputStream(contentBytes); + } + } + return is; } /** - * Put a read entity (supplement, detached content, data object) on - * transactions entity cash, to prevent repeated reading on slower channels. - * - * @param uri A transaction-wide unique URI used as key of the entity cash - * table. + * Put a read entity (supplement, detached content, data object) on transactions + * entity cash, to prevent repeated reading on slower channels. + * + * @param uri A transaction-wide unique URI used as key of the entity + * cash table. * @param contentBytes The cached content belonging to the uri. - * @param contentType If known, the MIME-type of the cashed content. + * @param contentType If known, the MIME-type of the cashed content. */ public void PutResolvedEntity(String uri, byte[] contentBytes, String contentType) { - Logger.trace(" storing uri content of uri \"" + uri + "\" for future references"); - if (resolvedEntities==null) resolvedEntities = new HashMap(); - Vector entity = new Vector(); - entity.add(contentBytes); - entity.add(contentType); - resolvedEntities.put(uri, entity); + Logger.trace(" storing uri content of uri \"" + uri + "\" for future references"); + if (resolvedEntities == null) { + resolvedEntities = new HashMap(); + } + final Vector entity = new Vector(); + entity.add(contentBytes); + entity.add(contentType); + resolvedEntities.put(uri, entity); } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/transaction/TransactionContextManager.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/transaction/TransactionContextManager.java index 8a45ddf..080f801 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/transaction/TransactionContextManager.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/transaction/TransactionContextManager.java @@ -21,30 +21,29 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.transaction; /** * Provides each thread with an instance of TransactionContext. - * + * * The single instance of the TransactionContextManager should be * used to access contextual information for each web service transaction, e.g. * the transaction ID, MOA configuration, client certificate, etc. - * + * * @author Stefan Knirsch * @author Patrick Peck */ public class TransactionContextManager { - /** The single instance of TransactionContextManager */ + /** The single instance of TransactionContextManager */ private static TransactionContextManager instance = null; - + /** Contains a single TransactionContext for each thread. */ private ThreadLocal context = null; /** * Get the single instance of TransactionContextManager. - * + * * @return The single instanc of TransactionContextManager. */ public static synchronized TransactionContextManager getInstance() { @@ -56,7 +55,7 @@ public class TransactionContextManager { /** * Creates a new TransactionContextManager. - * + * * Protected to disallow direct instantiation. */ protected TransactionContextManager() { @@ -65,7 +64,7 @@ public class TransactionContextManager { /** * Set the TransactionContext for the current thread. - * + * * @param txContext The TransactionContext for this thread. */ public void setTransactionContext(TransactionContext txContext) { @@ -74,10 +73,10 @@ public class TransactionContextManager { /** * Get the TransactionContext for the current thread. - * + * * @return The TransactionContext for the current thread or - * null, if none has been set (or if this method is being invoked - * outside the bounds of a transaction). + * null, if none has been set (or if this method is being + * invoked outside the bounds of a transaction). */ public TransactionContext getTransactionContext() { return (TransactionContext) context.get(); diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/transaction/TransactionIDGenerator.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/transaction/TransactionIDGenerator.java index b173308..463785b 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/transaction/TransactionIDGenerator.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/transaction/TransactionIDGenerator.java @@ -21,27 +21,28 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.transaction; - /** * A generator for unique transaction IDs. - * - *

The transaction IDs are of the form "-", where: - *

    + * + *

    + * The transaction IDs are of the form "-", where: + *

      *
    • base is initialized with the system time when this class is * being loaded
    • *
    • counter is incremented sequentially on each call to * nextID()
    • *
    *

    - * - *

    Assuming that it is highly unlikely that MOA servers are started at - * exactly the same time instant, the mechanism provided by this class should - * guarantee unique transaction IDs across multiple restarts and/or instances of - * the server.

    - * + * + *

    + * Assuming that it is highly unlikely that MOA servers are started at exactly + * the same time instant, the mechanism provided by this class should guarantee + * unique transaction IDs across multiple restarts and/or instances of the + * server. + *

    + * * @author Patrick Peck * @author Stefan Knirsch */ @@ -63,13 +64,13 @@ public class TransactionIDGenerator { /** * Returns the next transaction ID. - * + * * @return The next transaction ID. */ public static synchronized String nextID() { counter++; - return (base + "-" + counter); + return base + "-" + counter; } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/util/IdGenerator.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/util/IdGenerator.java index a8d9e1b..a6bc653 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/util/IdGenerator.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/server/util/IdGenerator.java @@ -21,65 +21,66 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.util; import java.util.Set; /** * Generate unique ID values for various objects in the response. - * + * * @author Patrick Peck * @version $Id$ */ public class IdGenerator { /** The base value to append the counter to. */ - private String base; + private final String base; /** The Set of reserved ID values. */ - private Set reserved; + private final Set reserved; /** The sequence number. */ private int count; - + /** * Create a new IdGenerator. - * - * @param base A base value to append the IDs to. The creator of this object - * should provide a base value, so that appending the counter leads to unique - * IDs. - * @param reserved The Set of reserved IDs. A call to - * uniqueId() will respect the reserved IDs. + * + * @param base A base value to append the IDs to. The creator of this object + * should provide a base value, so that appending the counter + * leads to unique IDs. + * @param reserved The Set of reserved IDs. A call to + * uniqueId() will respect the reserved IDs. */ public IdGenerator(String base, Set reserved) { this.base = base; this.reserved = reserved; count = 1; } - + /** * Create the next ID value in the sequence. - * + * * @return The next ID value in the sequence. */ protected String nextId() { return base + "-" + count++; } - + /** * Create the next unique ID value which is unique in the reserved ID set. - * + * * The created ID is added to the set of reserved IDs. - * + * * @return The next ID value. */ public String uniqueId() { String nextId; - while (reserved.contains(nextId = nextId())); - + while (reserved.contains(nextId = nextId())) { + ; + } + reserved.add(nextId); - + return nextId; - + } - + } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/TSLServiceFactory.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/TSLServiceFactory.java index bc902f2..d75240e 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/TSLServiceFactory.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/TSLServiceFactory.java @@ -13,55 +13,59 @@ import iaik.pki.store.truststore.TrustStoreFactory; public class TSLServiceFactory { - private static ITslService tslClient = null; - private static TslConfigurationImpl interalConfig; - - public static void initialize(TslConfigurationImpl config) { - if (tslClient == null) { - try { - interalConfig = config; - tslClient = TslClientFactory.buildTslService(interalConfig); - - TrustStoreFactory.addTrustStoreHandler(new ChainingTrustStoreHandler()); - - //set global TSL client status - ServiceStatusContainer.setStatus(true); - ServiceStatusContainer.setStatusMsg(ServiceStatusContainer.STATUS_OK); - - } catch (TslException e) { - Logger.fatal(new LogMsg(MessageProvider.getInstance().getMessage("init.05", new Object[]{e.getMessage()})), e); - - //set global TSL client status - ServiceStatusContainer.setStatus(false); - ServiceStatusContainer.setStatusMsg( - new LogMsg(MessageProvider.getInstance().getMessage("init.05", new Object[]{e.getMessage()})).toString()); - - } - - } else { - Logger.error("TSL-Service client can only be initialized once."); - throw new IllegalStateException("TSL-Service client can only be initialized once."); - - } - - } - - public static boolean isInitialized() { - if (tslClient == null) - return false; - else - return true; - - } - - public static ITslService getTSLServiceClient() { - if (!isInitialized()) { - Logger.warn("TSL client is not initialized but config is available. Starting new initialization process ..."); - initialize(interalConfig); - } - - return tslClient; - - } - + private static ITslService tslClient = null; + private static TslConfigurationImpl interalConfig; + + public static void initialize(TslConfigurationImpl config) { + if (tslClient == null) { + try { + interalConfig = config; + tslClient = TslClientFactory.buildTslService(interalConfig); + + TrustStoreFactory.addTrustStoreHandler(new ChainingTrustStoreHandler()); + + // set global TSL client status + ServiceStatusContainer.setStatus(true); + ServiceStatusContainer.setStatusMsg(ServiceStatusContainer.STATUS_OK); + + } catch (final TslException e) { + Logger.fatal(new LogMsg(MessageProvider.getInstance().getMessage("init.05", new Object[] { e + .getMessage() })), e); + + // set global TSL client status + ServiceStatusContainer.setStatus(false); + ServiceStatusContainer.setStatusMsg( + new LogMsg(MessageProvider.getInstance().getMessage("init.05", new Object[] { e.getMessage() })) + .toString()); + + } + + } else { + Logger.error("TSL-Service client can only be initialized once."); + throw new IllegalStateException("TSL-Service client can only be initialized once."); + + } + + } + + public static boolean isInitialized() { + if (tslClient == null) { + return false; + } else { + return true; + } + + } + + public static ITslService getTSLServiceClient() { + if (!isInitialized()) { + Logger.warn( + "TSL client is not initialized but config is available. Starting new initialization process ..."); + initialize(interalConfig); + } + + return tslClient; + + } + } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/timer/TSLUpdaterTimerTask.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/timer/TSLUpdaterTimerTask.java index b5a7a8c..1a377b6 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/timer/TSLUpdaterTimerTask.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/timer/TSLUpdaterTimerTask.java @@ -1,77 +1,49 @@ package at.gv.egovernment.moa.spss.tsl.timer; -import iaik.asn1.ObjectID; -import iaik.pki.store.certstore.CertStoreException; -import iaik.pki.store.certstore.CertStoreParameters; -import iaik.pki.store.truststore.TrustStoreException; -import iaik.pki.store.truststore.TrustStoreProfile; -import iaik.pki.store.utils.StoreUpdater; -import iaik.server.ConfigurationData; -import iaik.x509.X509Certificate; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.security.cert.CertificateException; -import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; -import java.util.Map; import java.util.TimerTask; import at.gv.egovernment.moa.sig.tsl.exception.TslException; import at.gv.egovernment.moa.sig.tsl.exception.TslUpdateException; -import at.gv.egovernment.moa.spss.MOAApplicationException; -import at.gv.egovernment.moa.spss.api.common.TSLConfiguration; -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.config.TrustProfile; -import at.gv.egovernment.moa.spss.server.iaik.config.IaikConfigurator; -import at.gv.egovernment.moa.spss.server.iaik.pki.store.truststore.TrustStoreProfileImpl; -import at.gv.egovernment.moa.spss.server.logging.TransactionId; import at.gv.egovernment.moa.spss.server.monitoring.ServiceStatusContainer; import at.gv.egovernment.moa.spss.tsl.TSLServiceFactory; import at.gv.egovernment.moa.spss.util.MessageProvider; import at.gv.egovernment.moaspss.logging.LogMsg; import at.gv.egovernment.moaspss.logging.Logger; -import at.gv.egovernment.moaspss.util.StringUtils; - public class TSLUpdaterTimerTask extends TimerTask { - - @Override - public void run() { - - try { - Logger.info("Start TSL Update"); - TSLServiceFactory.getTSLServiceClient().updateTSLInformation(); - Logger.info("Finished TSL Update"); - - //set global TSL client status - ServiceStatusContainer.setStatus(true); - ServiceStatusContainer.setStatusMsg(ServiceStatusContainer.STATUS_OK); - - } catch (TslUpdateException e) { - MessageProvider msg = MessageProvider.getInstance(); - Logger.error(new LogMsg(msg.getMessage("tsl.00", null)), e); - - //set global TSL client status - ServiceStatusContainer.setStatus(false); - ServiceStatusContainer.setStatusMsg( - new LogMsg(msg.getMessage("tsl.00", null)).toString()); - - } catch (TslException e) { - MessageProvider msg = MessageProvider.getInstance(); - Logger.error(new LogMsg(msg.getMessage("tsl.00", null)), e); - - //set global TSL client status - ServiceStatusContainer.setStatus(false); - ServiceStatusContainer.setStatusMsg( - new LogMsg(msg.getMessage("tsl.00", null)).toString()); - - } - } + @Override + public void run() { + + try { + Logger.info("Start TSL Update"); + TSLServiceFactory.getTSLServiceClient().updateTSLInformation(); + Logger.info("Finished TSL Update"); + + // set global TSL client status + ServiceStatusContainer.setStatus(true); + ServiceStatusContainer.setStatusMsg(ServiceStatusContainer.STATUS_OK); + + } catch (final TslUpdateException e) { + final MessageProvider msg = MessageProvider.getInstance(); + Logger.error(new LogMsg(msg.getMessage("tsl.00", null)), e); + + // set global TSL client status + ServiceStatusContainer.setStatus(false); + ServiceStatusContainer.setStatusMsg( + new LogMsg(msg.getMessage("tsl.00", null)).toString()); + + } catch (final TslException e) { + final MessageProvider msg = MessageProvider.getInstance(); + Logger.error(new LogMsg(msg.getMessage("tsl.00", null)), e); + + // set global TSL client status + ServiceStatusContainer.setStatus(false); + ServiceStatusContainer.setStatusMsg( + new LogMsg(msg.getMessage("tsl.00", null)).toString()); + + } + + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/utils/CertificateReader.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/utils/CertificateReader.java index 763382a..eeff27c 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/utils/CertificateReader.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/tsl/utils/CertificateReader.java @@ -1,10 +1,4 @@ package at.gv.egovernment.moa.spss.tsl.utils; -import iaik.pkcs.PKCS7CertList; -import iaik.pkcs.PKCSParsingException; -import iaik.security.provider.IAIK; -import iaik.utils.Util; -import iaik.x509.X509Certificate; -import iaik.xml.crypto.EccProviderAdapter; import java.io.BufferedInputStream; import java.io.File; @@ -18,6 +12,13 @@ import java.util.Arrays; import java.util.Iterator; import java.util.List; +import iaik.pkcs.PKCS7CertList; +import iaik.pkcs.PKCSParsingException; +import iaik.security.provider.IAIK; +import iaik.utils.Util; +import iaik.x509.X509Certificate; +import iaik.xml.crypto.EccProviderAdapter; + // Copyright (C) 2011 IAIK // http://jce.iaik.at // @@ -49,107 +50,106 @@ import java.util.List; public class CertificateReader { + /** + * Filter for reading certificate files from a directory. The filter accepts a + * file if its name ends with ".cer", ".der", + * ".crt" or ".pem". + * + * @author Harald Bratko + * @author Konrad Lanz + */ + static class CertificateFileFilter implements FileFilter { + /** - * Filter for reading certificate files from a directory. - * The filter accepts a file if its name ends with - * ".cer", ".der", ".crt" - * or ".pem". + * Accepts a file if it is not a directory and its name ends with + * ".cer", ".der", ".crt" or ".pem". * - * @author Harald Bratko - * @author Konrad Lanz + * @see java.io.FileFilter#accept(java.io.File) */ - static class CertificateFileFilter implements FileFilter { - - /** - * Accepts a file if it is not a directory and its name ends with - * ".cer", ".der", ".crt" or ".pem". - * - * @see java.io.FileFilter#accept(java.io.File) - */ - public boolean accept(File file) { - String name = file.getName(); - if (name.endsWith(".der") || + @Override + public boolean accept(File file) { + final String name = file.getName(); + if (name.endsWith(".der") || name.endsWith(".cer") || name.endsWith(".crt") || - name.endsWith(".pem")) - { - return true; - } else { - return false; - } + name.endsWith(".pem")) { + return true; + } else { + return false; } } - - - - /** - * Reads the certificates from the given directory and - * returns the certificates as sorted list (end user certificate first). - * @param directory - * @return - * @throws IOException - * @throws FileNotFoundException - * @throws CertificateException - * @throws Exception - */ - public static X509Certificate[] readCertificatesIntoArray(String directory) throws CertificateException, FileNotFoundException, IOException{ - File file = new File(directory); - File[] certificateFiles = file.listFiles(new CertificateFileFilter()); - int l = certificateFiles.length; - X509Certificate[] certs = new X509Certificate[l]; - for (int i=0; i readCertificates(String directory) throws CertificateException, FileNotFoundException, IOException{ - - return Arrays.asList(readCertificatesIntoArray(directory)); - } - - public static void main(String[] args) { - try { - - IAIK.addAsJDK14Provider(); - //IAIK.addAsProvider(); - //Security.addProvider(new IAIK()); - - // install ECC provider - Security.addProvider(EccProviderAdapter.getEccProvider()); - - String dir = "spec/examples/EU/AT/certs/on-tsl/chain/"; - List l = readCertificates(dir); - Iterator it = l.iterator(); - while (it.hasNext()) { - System.out.println(((X509Certificate)it.next()).getSubjectDN().getName()); - } - } catch (Exception e) { - e.printStackTrace(); - System.exit(1); + return Util.arrangeCertificateChain(certs, false); + } + + /** + * Reads the certificates from the given directory and returns the certificates + * as sorted list (end user certificate first). + * + * @param directory + * @return + * @throws IOException + * @throws FileNotFoundException + * @throws CertificateException + * @throws Exception + */ + public static List readCertificates(String directory) throws CertificateException, + FileNotFoundException, IOException { + + return Arrays.asList(readCertificatesIntoArray(directory)); + } + + public static void main(String[] args) { + try { + + IAIK.addAsJDK14Provider(); + // IAIK.addAsProvider(); + // Security.addProvider(new IAIK()); + + // install ECC provider + Security.addProvider(EccProviderAdapter.getEccProvider()); + + final String dir = "spec/examples/EU/AT/certs/on-tsl/chain/"; + final List l = readCertificates(dir); + final Iterator it = l.iterator(); + while (it.hasNext()) { + System.out.println(it.next().getSubjectDN().getName()); } - + } catch (final Exception e) { + e.printStackTrace(); + System.exit(1); } - public static X509Certificate[] p7read(File path) throws PKCSParsingException, FileNotFoundException, IOException { - PKCS7CertList p7certList = new PKCS7CertList( - new BufferedInputStream( - new FileInputStream( - path - ) - ) - ); - return p7certList.getCertificateList(); - } - } \ No newline at end of file + } + + public static X509Certificate[] p7read(File path) throws PKCSParsingException, FileNotFoundException, + IOException { + final PKCS7CertList p7certList = new PKCS7CertList( + new BufferedInputStream( + new FileInputStream( + path))); + return p7certList.getCertificateList(); + } +} \ No newline at end of file diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/AdESResultUtils.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/AdESResultUtils.java index 738801c..23570cc 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/AdESResultUtils.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/AdESResultUtils.java @@ -4,7 +4,6 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import at.gv.egovernment.moa.sig.tsl.utils.MiscUtil; import at.gv.egovernment.moa.spss.api.common.ExtendedCertificateCheckResult; import at.gv.egovernment.moa.spss.api.impl.AdESFormResultsImpl; import at.gv.egovernment.moa.spss.api.impl.ExtendedCertificateCheckResultImpl; @@ -22,229 +21,228 @@ import iaik.server.modules.resultcodes.ResultCodeValid; public class AdESResultUtils { - private static final int MAJORRESULTCODESKIPPED = new Integer(3); - private static final int MAJORRESULTCODEERROR = new Integer(4); - - public static Integer getResultCode(Integer adesCode) { - return adesCode; - } - - public static ExtendedCertificateCheckResult getExtendedResult(iaik.server.modules.resultcodes.ResultCode resultCode) { - ExtendedCertificateCheckResult check = null; - - int majorCode = -1; - String majorInfo = ""; - int minorCode = -1; - String minorInfo = ""; - - Logger.debug("Generating extendend validation result: " + resultCode.toString()); - - if (resultCode instanceof ResultCodeValid) { - majorCode = SignatureVerificationResult.VALID; - majorInfo = "VALID"; - - } else if (resultCode instanceof ResultCodeInvalid) { - majorCode = SignatureVerificationResult.INVALID; - majorInfo = "INVALID"; - - } else if (resultCode instanceof ResultCodeSkipped) { - majorCode = MAJORRESULTCODESKIPPED; - majorInfo = "SKIPPED"; - - } else if (resultCode instanceof ResultCodeError) { - majorCode = MAJORRESULTCODEERROR; - majorInfo = "ERROR"; - - } else { - majorCode = SignatureVerificationResult.INDETERMINATE; - majorInfo = "INDETERMINATE"; - } - - if (resultCode.getCode() != null) { - minorCode = resultCode.getCode(); - if (resultCode.getCode().equals(ResultCode.CODE_CHAIN_CONSTRAINTS_FAILURE)) { - minorInfo = "CHAIN_CONSTRAINTS_FAILURE"; - } else if (resultCode.getCode().equals(ResultCode.CODE_CRYPTO_CONSTRAINTS_FAILURE)) { - minorInfo = "CRYPTO_CONSTRAINTS_FAILURE"; - } else if (resultCode.getCode().equals(ResultCode.CODE_CRYPTO_CONSTRAINTS_FAILURE_NO_POE)) { - minorInfo = "CRYPTO_CONSTRAINTS_FAILURE_NO_POE"; - } else if (resultCode.getCode().equals(ResultCode.CODE_EXPIRED)) { - minorInfo = "EXPIRED"; - } else if (resultCode.getCode().equals(ResultCode.CODE_FORMAT_FAILURE)) { - minorInfo = "FORMAT_FAILURE"; - } else if (resultCode.getCode().equals(ResultCode.CODE_GENERIC)) { - minorInfo = "GENERIC"; - } else if (resultCode.getCode().equals(ResultCode.CODE_HASH_FAILURE)) { - minorInfo = "HASH_FAILURE"; - } else if (resultCode.getCode().equals(ResultCode.CODE_NO_CERTIFICATE_CHAIN_FOUND)) { - minorInfo = "NO_CERTIFICATE_CHAIN_FOUND"; - } else if (resultCode.getCode().equals(ResultCode.CODE_NO_POE)) { - minorInfo = "NO_POE"; - } else if (resultCode.getCode().equals(ResultCode.CODE_NO_POLICY)) { - minorInfo = "NO_POLICY"; - } else if (resultCode.getCode().equals(ResultCode.CODE_NOT_YET_VALID)) { - minorInfo = "NOT_YET_VALID"; - } else if (resultCode.getCode().equals(ResultCode.CODE_OUT_OF_BOUNDS_NO_POE)) { - minorInfo = "OUT_OF_BOUNDS_NO_POE"; - } else if (resultCode.getCode().equals(ResultCode.CODE_POLICY_PROCESSING_ERROR)) { - minorInfo = "POLICY_PROCESSING_ERROR"; - } else if (resultCode.getCode().equals(ResultCode.CODE_REVOKED)) { - minorInfo = "REVOKED"; - } else if (resultCode.getCode().equals(ResultCode.CODE_REVOKED_CA_NO_POE)) { - minorInfo = "REVOKED_CA_NO_POE"; - } else if (resultCode.getCode().equals(ResultCode.CODE_REVOKED_NO_POE)) { - minorInfo = "REVOKED_NO_POE"; - } else if (resultCode.getCode().equals(ResultCode.CODE_SIG_CONSTRAINTS_FAILURE)) { - minorInfo = "SIG_CONSTRAINTS_FAILURE"; - } else if (resultCode.getCode().equals(ResultCode.CODE_SIG_CRYPTO_FAILURE)) { - minorInfo = "SIG_CRYPTO_FAILURE"; - } else if (resultCode.getCode().equals(ResultCode.CODE_SIGNED_DATA_NOT_FOUND)) { - minorInfo = "SIGNED_DATA_NOT_FOUND"; - } else if (resultCode.getCode().equals(ResultCode.CODE_TIMESTAMP_ORDER_FAILURE)) { - minorInfo = "TIMESTAMP_ORDER_FAILURE"; - } else if (resultCode.getCode().equals(ResultCode.CODE_TRY_LATER)) { - minorInfo = "TRY_LATER"; - } else if (resultCode.getCode().equals(ResultCode.CODE_UNKNOWN_COMMITMENT_TYPE)) { - minorInfo = "UNKNOWN_COMMITMENT_TYPE"; - } else if (resultCode.getCode().equals(ResultCode.SUCCESS)) { - minorInfo = "SUCCESS"; - } else if (resultCode.getCode().equals(ResultCode.ERROR)) { - minorInfo = "ERROR"; - } else if (resultCode.getCode().equals(ResultCode.UNKNOWN_SUBFILTER)) { - minorInfo = "UNKNOWN_SUBFILTER"; - - //pdf-as 3.x detection is removed from MOA-SP since 3.1.2 - } else if (resultCode.getCode().equals(ResultCode.PDF_AS_SIGNATURE)) { - //minorInfo = "PDF_AS_SIGNATURE"; - minorInfo = "UNKNOWN_SUBFILTER"; - minorCode = ResultCode.UNKNOWN_SUBFILTER; - } - - } - - check = new ExtendedCertificateCheckResultImpl(majorCode, majorInfo, minorCode, - minorInfo); - - return check; - - } - - public static List getAdESResult(iaik.server.modules.AdESFormVerificationResult adesFormVerification) { - if (adesFormVerification == null) { - // no form information - return null; - } - - List adesList = new ArrayList(); - - //add only the completed form result to response - String completedForm = adesFormVerification.getCompleteForm(); - Logger.info("Find complete Form: " + completedForm); - - - /* - * This code only returns the result of the completed form - */ + private static final int MAJORRESULTCODESKIPPED = new Integer(3); + private static final int MAJORRESULTCODEERROR = new Integer(4); + + public static Integer getResultCode(Integer adesCode) { + return adesCode; + } + + public static ExtendedCertificateCheckResult getExtendedResult( + iaik.server.modules.resultcodes.ResultCode resultCode) { + ExtendedCertificateCheckResult check = null; + + int majorCode = -1; + String majorInfo = ""; + int minorCode = -1; + String minorInfo = ""; + + Logger.debug("Generating extendend validation result: " + resultCode.toString()); + + if (resultCode instanceof ResultCodeValid) { + majorCode = SignatureVerificationResult.VALID; + majorInfo = "VALID"; + + } else if (resultCode instanceof ResultCodeInvalid) { + majorCode = SignatureVerificationResult.INVALID; + majorInfo = "INVALID"; + + } else if (resultCode instanceof ResultCodeSkipped) { + majorCode = MAJORRESULTCODESKIPPED; + majorInfo = "SKIPPED"; + + } else if (resultCode instanceof ResultCodeError) { + majorCode = MAJORRESULTCODEERROR; + majorInfo = "ERROR"; + + } else { + majorCode = SignatureVerificationResult.INDETERMINATE; + majorInfo = "INDETERMINATE"; + } + + if (resultCode.getCode() != null) { + minorCode = resultCode.getCode(); + if (resultCode.getCode().equals(ResultCode.CODE_CHAIN_CONSTRAINTS_FAILURE)) { + minorInfo = "CHAIN_CONSTRAINTS_FAILURE"; + } else if (resultCode.getCode().equals(ResultCode.CODE_CRYPTO_CONSTRAINTS_FAILURE)) { + minorInfo = "CRYPTO_CONSTRAINTS_FAILURE"; + } else if (resultCode.getCode().equals(ResultCode.CODE_CRYPTO_CONSTRAINTS_FAILURE_NO_POE)) { + minorInfo = "CRYPTO_CONSTRAINTS_FAILURE_NO_POE"; + } else if (resultCode.getCode().equals(ResultCode.CODE_EXPIRED)) { + minorInfo = "EXPIRED"; + } else if (resultCode.getCode().equals(ResultCode.CODE_FORMAT_FAILURE)) { + minorInfo = "FORMAT_FAILURE"; + } else if (resultCode.getCode().equals(ResultCode.CODE_GENERIC)) { + minorInfo = "GENERIC"; + } else if (resultCode.getCode().equals(ResultCode.CODE_HASH_FAILURE)) { + minorInfo = "HASH_FAILURE"; + } else if (resultCode.getCode().equals(ResultCode.CODE_NO_CERTIFICATE_CHAIN_FOUND)) { + minorInfo = "NO_CERTIFICATE_CHAIN_FOUND"; + } else if (resultCode.getCode().equals(ResultCode.CODE_NO_POE)) { + minorInfo = "NO_POE"; + } else if (resultCode.getCode().equals(ResultCode.CODE_NO_POLICY)) { + minorInfo = "NO_POLICY"; + } else if (resultCode.getCode().equals(ResultCode.CODE_NOT_YET_VALID)) { + minorInfo = "NOT_YET_VALID"; + } else if (resultCode.getCode().equals(ResultCode.CODE_OUT_OF_BOUNDS_NO_POE)) { + minorInfo = "OUT_OF_BOUNDS_NO_POE"; + } else if (resultCode.getCode().equals(ResultCode.CODE_POLICY_PROCESSING_ERROR)) { + minorInfo = "POLICY_PROCESSING_ERROR"; + } else if (resultCode.getCode().equals(ResultCode.CODE_REVOKED)) { + minorInfo = "REVOKED"; + } else if (resultCode.getCode().equals(ResultCode.CODE_REVOKED_CA_NO_POE)) { + minorInfo = "REVOKED_CA_NO_POE"; + } else if (resultCode.getCode().equals(ResultCode.CODE_REVOKED_NO_POE)) { + minorInfo = "REVOKED_NO_POE"; + } else if (resultCode.getCode().equals(ResultCode.CODE_SIG_CONSTRAINTS_FAILURE)) { + minorInfo = "SIG_CONSTRAINTS_FAILURE"; + } else if (resultCode.getCode().equals(ResultCode.CODE_SIG_CRYPTO_FAILURE)) { + minorInfo = "SIG_CRYPTO_FAILURE"; + } else if (resultCode.getCode().equals(ResultCode.CODE_SIGNED_DATA_NOT_FOUND)) { + minorInfo = "SIGNED_DATA_NOT_FOUND"; + } else if (resultCode.getCode().equals(ResultCode.CODE_TIMESTAMP_ORDER_FAILURE)) { + minorInfo = "TIMESTAMP_ORDER_FAILURE"; + } else if (resultCode.getCode().equals(ResultCode.CODE_TRY_LATER)) { + minorInfo = "TRY_LATER"; + } else if (resultCode.getCode().equals(ResultCode.CODE_UNKNOWN_COMMITMENT_TYPE)) { + minorInfo = "UNKNOWN_COMMITMENT_TYPE"; + } else if (resultCode.getCode().equals(ResultCode.SUCCESS)) { + minorInfo = "SUCCESS"; + } else if (resultCode.getCode().equals(ResultCode.ERROR)) { + minorInfo = "ERROR"; + } else if (resultCode.getCode().equals(ResultCode.UNKNOWN_SUBFILTER)) { + minorInfo = "UNKNOWN_SUBFILTER"; + + // pdf-as 3.x detection is removed from MOA-SP since 3.1.2 + } else if (resultCode.getCode().equals(ResultCode.PDF_AS_SIGNATURE)) { + // minorInfo = "PDF_AS_SIGNATURE"; + minorInfo = "UNKNOWN_SUBFILTER"; + minorCode = ResultCode.UNKNOWN_SUBFILTER; + } + + } + + check = new ExtendedCertificateCheckResultImpl(majorCode, majorInfo, minorCode, + minorInfo); + + return check; + + } + + public static List getAdESResult(iaik.server.modules.AdESFormVerificationResult adesFormVerification) { + if (adesFormVerification == null) { + // no form information + return null; + } + + final List adesList = new ArrayList(); + + // add only the completed form result to response + final String completedForm = adesFormVerification.getCompleteForm(); + Logger.info("Find complete Form: " + completedForm); + + /* + * This code only returns the result of the completed form + */ // if (MiscUtil.isNotEmpty(completedForm)) { // Logger.info("Form-validation found completed form: " + completedForm); // AdESVerificationResult subResult = adesFormVerification.getSubResult(completedForm); // checkSubResult(subResult, completedForm, adesList); // if (Logger.isDebugEnabled()) // Logger.debug("Detailed Result: \n" + subResult.getInfo()); -// -// } else +// +// } else // Logger.info("Form-valdition found NO completed form."); -// +// // if (Logger.isDebugEnabled()) // Logger.debug("Full form-validation result: \n" + adesFormVerification.getInfo()); - - - /* - * This code returns the result for all forms - */ - //add results for all form types to response - checkSubResult(adesFormVerification.getSubResult(SignatureVerificationProfile.LEVEL_LTA), - SignatureVerificationProfile.LEVEL_LTA, adesList); - checkSubResult(adesFormVerification.getSubResult(SignatureVerificationProfile.LEVEL_LT), - SignatureVerificationProfile.LEVEL_LT, adesList); - checkSubResult(adesFormVerification.getSubResult(SignatureVerificationProfile.LEVEL_T), - SignatureVerificationProfile.LEVEL_T, adesList); - checkSubResult(adesFormVerification.getSubResult(SignatureVerificationProfile.LEVEL_B), - SignatureVerificationProfile.LEVEL_B, adesList); - - return adesList; - } - - public static void buildResult(ValidationReport report, List adesList) { - - if (report == null) { - return; - } - - AdESFormResultsImpl adESFormResultsImpl = new AdESFormResultsImpl(); - adESFormResultsImpl.setCode(report.getStatus().ordinal()); - adESFormResultsImpl.setInfo(report.getLongText()); - adESFormResultsImpl.setName(report.getValidationName()); - - adesList.add(adESFormResultsImpl); - - if (report.getSubValidationReports() != null && !report.getSubValidationReports().isEmpty()) { - Iterator reportIt = report.getSubValidationReports().iterator(); - while (reportIt.hasNext()) { - buildResult(reportIt.next(), adesList); - } - } - - } - - public static void checkSubResult(AdESVerificationResult subResult, String level, List adesList) { - if (subResult != null) { - Logger.debug("Checking Level: " + level); - try { - - AdESFormResultsImpl adESFormResultsImpl = new AdESFormResultsImpl(); - adESFormResultsImpl.setCode(subResult.getResultCode()); - Logger.debug("RESULT: " + String.valueOf(subResult.getResultCode())); - adESFormResultsImpl.setInfo(subResult.getInfo()); - adESFormResultsImpl.setName(level); - - adesList.add(adESFormResultsImpl); - } catch (NullPointerException e) { - Logger.warn("Catching NullPointer Exception, of invalid Form Results", e); - - } - } else { - Logger.info("Subresult Level: " + level + " not available"); - - } - } - - public static void checkSubResult(SignatureVerificationResult subResult, String level, List adesList) - throws ConfigurationException { - if (subResult != null) { - Logger.debug("Checking Level: " + level); - try { - - AdESFormResultsImpl adESFormResultsImpl = new AdESFormResultsImpl(); - iaik.server.modules.resultcodes.ResultCode resultCode = subResult.getResultCode(); - if (resultCode instanceof ResultCodeValid) { - adESFormResultsImpl.setCode(SignatureVerificationResult.VALID);// .getResultCode().getCode())); - } else if (resultCode instanceof ResultCodeInvalid) { - adESFormResultsImpl.setCode(SignatureVerificationResult.INVALID); - } else { - adESFormResultsImpl.setCode(SignatureVerificationResult.INDETERMINATE); - } - Logger.debug("RESULT: " + resultCode.toString()); - adESFormResultsImpl.setInfo(subResult.getInfo()); - adESFormResultsImpl.setName(level); - - adesList.add(adESFormResultsImpl); - } catch (NullPointerException e) { - Logger.warn("Catching NullPointer Exception, of invalid? Form Results", e); - } - } else { - Logger.info("Subresult Level: " + level + " not available"); - } - } + + /* + * This code returns the result for all forms + */ + // add results for all form types to response + checkSubResult(adesFormVerification.getSubResult(SignatureVerificationProfile.LEVEL_LTA), + SignatureVerificationProfile.LEVEL_LTA, adesList); + checkSubResult(adesFormVerification.getSubResult(SignatureVerificationProfile.LEVEL_LT), + SignatureVerificationProfile.LEVEL_LT, adesList); + checkSubResult(adesFormVerification.getSubResult(SignatureVerificationProfile.LEVEL_T), + SignatureVerificationProfile.LEVEL_T, adesList); + checkSubResult(adesFormVerification.getSubResult(SignatureVerificationProfile.LEVEL_B), + SignatureVerificationProfile.LEVEL_B, adesList); + + return adesList; + } + + public static void buildResult(ValidationReport report, List adesList) { + + if (report == null) { + return; + } + + final AdESFormResultsImpl adESFormResultsImpl = new AdESFormResultsImpl(); + adESFormResultsImpl.setCode(report.getStatus().ordinal()); + adESFormResultsImpl.setInfo(report.getLongText()); + adESFormResultsImpl.setName(report.getValidationName()); + + adesList.add(adESFormResultsImpl); + + if (report.getSubValidationReports() != null && !report.getSubValidationReports().isEmpty()) { + final Iterator reportIt = report.getSubValidationReports().iterator(); + while (reportIt.hasNext()) { + buildResult(reportIt.next(), adesList); + } + } + + } + + public static void checkSubResult(AdESVerificationResult subResult, String level, List adesList) { + if (subResult != null) { + Logger.debug("Checking Level: " + level); + try { + + final AdESFormResultsImpl adESFormResultsImpl = new AdESFormResultsImpl(); + adESFormResultsImpl.setCode(subResult.getResultCode()); + Logger.debug("RESULT: " + String.valueOf(subResult.getResultCode())); + adESFormResultsImpl.setInfo(subResult.getInfo()); + adESFormResultsImpl.setName(level); + + adesList.add(adESFormResultsImpl); + } catch (final NullPointerException e) { + Logger.warn("Catching NullPointer Exception, of invalid Form Results", e); + + } + } else { + Logger.info("Subresult Level: " + level + " not available"); + + } + } + + public static void checkSubResult(SignatureVerificationResult subResult, String level, List adesList) + throws ConfigurationException { + if (subResult != null) { + Logger.debug("Checking Level: " + level); + try { + + final AdESFormResultsImpl adESFormResultsImpl = new AdESFormResultsImpl(); + final iaik.server.modules.resultcodes.ResultCode resultCode = subResult.getResultCode(); + if (resultCode instanceof ResultCodeValid) { + adESFormResultsImpl.setCode(SignatureVerificationResult.VALID);// .getResultCode().getCode())); + } else if (resultCode instanceof ResultCodeInvalid) { + adESFormResultsImpl.setCode(SignatureVerificationResult.INVALID); + } else { + adESFormResultsImpl.setCode(SignatureVerificationResult.INDETERMINATE); + } + Logger.debug("RESULT: " + resultCode.toString()); + adESFormResultsImpl.setInfo(subResult.getInfo()); + adESFormResultsImpl.setName(level); + + adesList.add(adESFormResultsImpl); + } catch (final NullPointerException e) { + Logger.warn("Catching NullPointer Exception, of invalid? Form Results", e); + } + } else { + Logger.info("Subresult Level: " + level + " not available"); + } + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/CertStoreConverter.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/CertStoreConverter.java index d3d82f2..59db5db 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/CertStoreConverter.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/CertStoreConverter.java @@ -14,96 +14,96 @@ import iaik.pki.store.certstore.utils.DirectoryCertStoreConverter; public class CertStoreConverter { - private static final Logger logger = LoggerFactory.getLogger(CertStoreConverter.class); - - public static boolean convert(String certStoreRoot, TransactionId transId) { - String certStoreSubjectDN = certStoreRoot + File.separator + "subjectdn"; - - logger.info("checking for new cert store format {} -> {}", certStoreRoot, certStoreSubjectDN); - - File certStoreDirectory = new File(certStoreRoot); - if (certStoreDirectory.isDirectory() && certStoreDirectory.exists()) { - - File file = new File(certStoreSubjectDN); - - if (file.isDirectory() && file.exists()) { - // Is new Format! - logger.debug("Cert store is allready new format!"); - return false; - } else { - try { - logger.info( - "###########################################################################################"); - logger.info( - "###########################################################################################"); - logger.info("The certificate store @ {} will now be converted into the new format!", - certStoreDirectory.getAbsolutePath()); - - String backup = certStoreRoot; - - if (certStoreRoot.endsWith(File.separator)) { - backup = certStoreRoot.substring(0, certStoreRoot.length() - File.separator.length()); - } - - String timestamp = String.valueOf(System.currentTimeMillis()); - backup = backup + "_" + timestamp; - - logger.info("Creating a backup of the certstore @ {}", backup); - - File backupDirectory = new File(backup); - try { - FileUtils.copyDirectory(certStoreDirectory, backupDirectory); - } catch (IOException e) { - logger.error("Failed to create certstore backup!", e); - throw new RuntimeException("Failed to create certstore backup!", e); - } - - logger.info("deleting original certstore @ {}", certStoreRoot); - - try { - FileUtils.deleteDirectory(certStoreDirectory); - } catch (IOException e1) { - logger.error("Failed to delete old certstore!", e1); - throw new RuntimeException("Failed to delete old certstore!", e1); - } - certStoreDirectory.mkdir(); - - DirectoryCertStoreConverter directoryCertStoreConverter = new DirectoryCertStoreConverter(); - - try { - logger.info("running conversion of certstore @ {}", certStoreRoot); - directoryCertStoreConverter.convert(backupDirectory.getAbsolutePath(), - certStoreDirectory.getAbsolutePath(), true, false, - new IaikLog("DirectoryCertStoreConverter"), transId); - } catch (DirectoryStoreException e) { - logger.error("Failed to run conversion of old certstore!", e); - - try { - FileUtils.copyDirectory(backupDirectory, certStoreDirectory); - } catch (IOException e1) { - logger.error("!!!!Failed to restore original certstore!!!! CHECK LOGS", e1); - throw new RuntimeException("!!!!Failed to restore original certstore!!!! CHECK LOGS", e); - - } - throw new RuntimeException("Failed to run conversion of old certstore!", e); - } - - logger.info("Conversion of certstore succseeded"); - logger.info("Certstore in new format is located @ {}", certStoreDirectory.getAbsolutePath()); - logger.info("Backup of Certstore in old format is located @ {}", - certStoreDirectory.getAbsolutePath()); - } finally { - logger.info( - "###########################################################################################"); - logger.info( - "###########################################################################################"); - } - return true; - } - } else { - logger.error("Certstore does not exist yet"); - } - return false; - } - + private static final Logger logger = LoggerFactory.getLogger(CertStoreConverter.class); + + public static boolean convert(String certStoreRoot, TransactionId transId) { + final String certStoreSubjectDN = certStoreRoot + File.separator + "subjectdn"; + + logger.info("checking for new cert store format {} -> {}", certStoreRoot, certStoreSubjectDN); + + final File certStoreDirectory = new File(certStoreRoot); + if (certStoreDirectory.isDirectory() && certStoreDirectory.exists()) { + + final File file = new File(certStoreSubjectDN); + + if (file.isDirectory() && file.exists()) { + // Is new Format! + logger.debug("Cert store is allready new format!"); + return false; + } else { + try { + logger.info( + "###########################################################################################"); + logger.info( + "###########################################################################################"); + logger.info("The certificate store @ {} will now be converted into the new format!", + certStoreDirectory.getAbsolutePath()); + + String backup = certStoreRoot; + + if (certStoreRoot.endsWith(File.separator)) { + backup = certStoreRoot.substring(0, certStoreRoot.length() - File.separator.length()); + } + + final String timestamp = String.valueOf(System.currentTimeMillis()); + backup = backup + "_" + timestamp; + + logger.info("Creating a backup of the certstore @ {}", backup); + + final File backupDirectory = new File(backup); + try { + FileUtils.copyDirectory(certStoreDirectory, backupDirectory); + } catch (final IOException e) { + logger.error("Failed to create certstore backup!", e); + throw new RuntimeException("Failed to create certstore backup!", e); + } + + logger.info("deleting original certstore @ {}", certStoreRoot); + + try { + FileUtils.deleteDirectory(certStoreDirectory); + } catch (final IOException e1) { + logger.error("Failed to delete old certstore!", e1); + throw new RuntimeException("Failed to delete old certstore!", e1); + } + certStoreDirectory.mkdir(); + + final DirectoryCertStoreConverter directoryCertStoreConverter = new DirectoryCertStoreConverter(); + + try { + logger.info("running conversion of certstore @ {}", certStoreRoot); + directoryCertStoreConverter.convert(backupDirectory.getAbsolutePath(), + certStoreDirectory.getAbsolutePath(), true, false, + new IaikLog("DirectoryCertStoreConverter"), transId); + } catch (final DirectoryStoreException e) { + logger.error("Failed to run conversion of old certstore!", e); + + try { + FileUtils.copyDirectory(backupDirectory, certStoreDirectory); + } catch (final IOException e1) { + logger.error("!!!!Failed to restore original certstore!!!! CHECK LOGS", e1); + throw new RuntimeException("!!!!Failed to restore original certstore!!!! CHECK LOGS", e); + + } + throw new RuntimeException("Failed to run conversion of old certstore!", e); + } + + logger.info("Conversion of certstore succseeded"); + logger.info("Certstore in new format is located @ {}", certStoreDirectory.getAbsolutePath()); + logger.info("Backup of Certstore in old format is located @ {}", + certStoreDirectory.getAbsolutePath()); + } finally { + logger.info( + "###########################################################################################"); + logger.info( + "###########################################################################################"); + } + return true; + } + } else { + logger.error("Certstore does not exist yet"); + } + return false; + } + } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/CertificateUtils.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/CertificateUtils.java index ae7fef7..b7580ac 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/CertificateUtils.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/CertificateUtils.java @@ -1,18 +1,5 @@ package at.gv.egovernment.moa.spss.util; -import iaik.asn1.ObjectID; -import iaik.asn1.structures.Name; -import iaik.asn1.structures.PolicyInformation; -import iaik.utils.RFC2253NameParser; -import iaik.utils.RFC2253NameParserException; -import iaik.x509.X509Certificate; -import iaik.x509.X509ExtensionInitException; -import iaik.x509.extensions.CertificatePolicies; -import iaik.x509.extensions.qualified.QCStatements; -import iaik.x509.extensions.qualified.structures.QCStatement; -import iaik.x509.extensions.qualified.structures.etsi.QcEuCompliance; -import iaik.x509.extensions.qualified.structures.etsi.QcEuSSCD; - import java.net.URI; import java.security.Principal; import java.util.Arrays; @@ -22,370 +9,387 @@ import java.util.List; import at.gv.egovernment.moa.sig.tsl.TslConstants; import at.gv.egovernment.moa.sig.tsl.engine.data.ITslEndEntityResult; import at.gv.egovernment.moa.sig.tsl.exception.TslException; -import at.gv.egovernment.moa.sig.tsl.utils.MiscUtil; import at.gv.egovernment.moa.spss.api.common.TslInfos; import at.gv.egovernment.moa.spss.api.impl.TslInfosImpl; import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; import at.gv.egovernment.moa.spss.tsl.TSLServiceFactory; import at.gv.egovernment.moaspss.logging.LogMsg; import at.gv.egovernment.moaspss.logging.Logger; +import iaik.asn1.ObjectID; +import iaik.asn1.structures.Name; +import iaik.asn1.structures.PolicyInformation; +import iaik.utils.RFC2253NameParser; +import iaik.utils.RFC2253NameParserException; +import iaik.x509.X509Certificate; +import iaik.x509.X509ExtensionInitException; +import iaik.x509.extensions.CertificatePolicies; +import iaik.x509.extensions.qualified.QCStatements; +import iaik.x509.extensions.qualified.structures.QCStatement; +import iaik.x509.extensions.qualified.structures.etsi.QcEuCompliance; +import iaik.x509.extensions.qualified.structures.etsi.QcEuSSCD; public class CertificateUtils { - - - /** - * Verifies if the given certificate contains QCP+ statement - * @param cert X509Certificate - * @return true if the given certificate contains QCP+ statement, else false - */ - private static boolean checkQCPPlus(X509Certificate cert) { - Logger.debug("Checking QCP+ extension"); - String OID_QCPPlus = "0.4.0.1456.1.1"; - try { - CertificatePolicies certPol = (CertificatePolicies) cert.getExtension(CertificatePolicies.oid); - if (certPol == null) { - Logger.debug("No CertificatePolicies extension found"); - return false; - } - - PolicyInformation[] polInfo = certPol.getPolicyInformation(); - if (polInfo == null) { - Logger.debug("No policy information found"); - return false; - } - - for (int i = 0; i < polInfo.length; i++) { - ObjectID oid = polInfo[i].getPolicyIdentifier(); - String oidStr = oid.getID(); - if (oidStr.compareToIgnoreCase(OID_QCPPlus) == 0) { - Logger.debug("QCP+ extension found"); - return true; - } - } - - Logger.debug("No QCP+ extension found"); - - return false; - } catch (X509ExtensionInitException e) { - Logger.debug("No QCP+ extension found"); - - return false; - } - - } - - /** - * Verifies if the given certificate contains QCP statement - * @param cert X509Certificate - * @return true if the given certificate contains QCP statement, else false - */ - private static boolean checkQCP(X509Certificate cert) { - Logger.debug("Checking QCP extension"); - String OID_QCP = "0.4.0.1456.1.2"; - try { - CertificatePolicies certPol = (CertificatePolicies) cert.getExtension(CertificatePolicies.oid); - if (certPol == null) { - Logger.debug("No CertificatePolicies extension found"); - return false; - } - - PolicyInformation[] polInfo = certPol.getPolicyInformation(); - if (polInfo == null) { - Logger.debug("No policy information found"); - return false; - } - - for (int i = 0; i < polInfo.length; i++) { - ObjectID oid = polInfo[i].getPolicyIdentifier(); - String oidStr = oid.getID(); - if (oidStr.compareToIgnoreCase(OID_QCP) == 0) { - Logger.debug("QCP extension found"); - return true; - } - - } - - Logger.debug("No QCP extension found"); - return false; - - } catch (X509ExtensionInitException e) { - Logger.debug("No QCP extension found"); - return false; - } - - } - - /** - * Verifies if the given certificate contains QcEuCompliance statement - * @param cert X509Certificate - * @return true if the given certificate contains QcEuCompliance statement, else false - */ - private static boolean checkQcEuCompliance(X509Certificate cert) { - Logger.debug("Checking QcEUCompliance extension"); - try { - QCStatements qcStatements = (QCStatements) cert.getExtension(QCStatements.oid); - - if (qcStatements == null) { - Logger.debug("No QcStatements extension found"); - return false; - } - - QCStatement qcEuCompliance = qcStatements.getQCStatements(QcEuCompliance.statementID); - - if (qcEuCompliance != null) { - Logger.debug("QcEuCompliance extension found"); - return true; - } - - Logger.debug("No QcEuCompliance extension found"); - return false; - - } catch (X509ExtensionInitException e) { - Logger.debug("No QcEuCompliance extension found"); - return false; - } - - } - - /** - * Verifies if the given certificate contains QcEuSSCD statement - * @param cert X509Certificate - * @return true if the given certificate contains QcEuSSCD statement, else false - */ - private static boolean checkQcEuSSCD(X509Certificate cert) { - Logger.debug("Checking QcEuSSCD extension"); - try { - QCStatements qcStatements = (QCStatements) cert.getExtension(QCStatements.oid); - if (qcStatements == null) { - Logger.debug("No QcStatements extension found"); - return false; - } - - QCStatement qcEuSSCD = qcStatements.getQCStatements(QcEuSSCD.statementID); - - if (qcEuSSCD != null) { - Logger.debug("QcEuSSCD extension found"); - return true; - } - - Logger.debug("No QcEuSSCD extension found"); - return false; - - } catch (X509ExtensionInitException e) { - Logger.debug("No QcEuSSCD extension found"); - return false; - } - - } - - public static QCSSCDResult checkQCSSCD(X509Certificate[] chain, Date signingTime, boolean isTSLenabledTrustprofile, ConfigurationProvider config) { - - try { - if (isTSLenabledTrustprofile) { - if (signingTime == null) { - signingTime = new Date(); - Logger.debug("TSL check without signingTime --> use current time for evaluation"); - - } - - ITslEndEntityResult tslCheckResult = - TSLServiceFactory.getTSLServiceClient().evaluate( - Arrays.asList(chain), - signingTime, - TslConstants.PKIX_MODEL); - - if (tslCheckResult != null) { - URI tslServiceTypeIdentifier = tslCheckResult.getEvaluatedServiceTypeIdentifier(); - List tslCertificateQualifier = tslCheckResult.getEvaluatedQualifier(); - - // QC evaluation flags - boolean qc = false; - boolean qcSourceTSL = false; - boolean qcDisallowedFromTSL = false; - - // SSCD/QSCD evaluation flags - boolean sscd = false; - boolean sscdSourceTSL = false; - - - //check QC - List allowedQCQualifier = config.getTSLConfiguration().getQualifierForQC(); - for (URI el : allowedQCQualifier) { - if (el.equals(tslServiceTypeIdentifier)) { - qcSourceTSL = true; - qc = true; - - } - - } - - //check SSCD/QSCD qualifiers and mark result acording this check - List allowedSSCDQualifier = config.getTSLConfiguration().getQualifierForSSCD(); - if (tslCertificateQualifier != null && allowedSSCDQualifier != null) { - for (URI allowedSSCD : allowedSSCDQualifier) { - for (URI certSSCD : tslCertificateQualifier) { - if (allowedSSCD.equals(certSSCD)) { - sscdSourceTSL = true; - sscd = true; - - } - } - } - } - - //check additional flags in TSP qualifiers for this certificate - if (tslCertificateQualifier != null) { - for (URI qEl : tslCertificateQualifier) { - //check if SSCD/QSCD status must be used from cert - if (qEl.equals( - TslConstants.SSCD_QUALIFIER_SORT_TO_URI.get( - TslConstants.SSCD_QUALIFIER_SHORT.QCQSCDStatusAsInCert)) - || qEl.equals(TslConstants.SSCD_QUALIFIER_SORT_TO_URI.get( - TslConstants.SSCD_QUALIFIER_SHORT.QCSSCDStatusAsInCert))) { - - sscdSourceTSL = false; - sscd = false; - - //check if extentsion includes a NotQualified flag - } else if (qEl.equals( - TslConstants.SSCD_QUALIFIER_SORT_TO_URI.get( - TslConstants.SSCD_QUALIFIER_SHORT.NotQualified))) { - qc = false; - qcSourceTSL = false; - qcDisallowedFromTSL = true; - Logger.info("TSL mark this certificate explicitly as 'NotQualified'!"); - - } - } - } - - /* - * This block is removes with MOA-SP 3.1 because if TSL support is enabled for the requested TrustProfile - * QC evaluation is ONLY allowed from TSL information!!! Because with eIDAS regulation and July 01. 2016 - * the Trust-Status List is constitutive. - */ -// //evaluate QC statement according previous selected information -// if (qcSourceTSL) + + /** + * Verifies if the given certificate contains QCP+ statement + * + * @param cert X509Certificate + * @return true if the given certificate contains QCP+ statement, else false + */ + private static boolean checkQCPPlus(X509Certificate cert) { + Logger.debug("Checking QCP+ extension"); + final String OID_QCPPlus = "0.4.0.1456.1.1"; + try { + final CertificatePolicies certPol = (CertificatePolicies) cert.getExtension(CertificatePolicies.oid); + if (certPol == null) { + Logger.debug("No CertificatePolicies extension found"); + return false; + } + + final PolicyInformation[] polInfo = certPol.getPolicyInformation(); + if (polInfo == null) { + Logger.debug("No policy information found"); + return false; + } + + for (final PolicyInformation element : polInfo) { + final ObjectID oid = element.getPolicyIdentifier(); + final String oidStr = oid.getID(); + if (oidStr.compareToIgnoreCase(OID_QCPPlus) == 0) { + Logger.debug("QCP+ extension found"); + return true; + } + } + + Logger.debug("No QCP+ extension found"); + + return false; + } catch (final X509ExtensionInitException e) { + Logger.debug("No QCP+ extension found"); + + return false; + } + + } + + /** + * Verifies if the given certificate contains QCP statement + * + * @param cert X509Certificate + * @return true if the given certificate contains QCP statement, else false + */ + private static boolean checkQCP(X509Certificate cert) { + Logger.debug("Checking QCP extension"); + final String OID_QCP = "0.4.0.1456.1.2"; + try { + final CertificatePolicies certPol = (CertificatePolicies) cert.getExtension(CertificatePolicies.oid); + if (certPol == null) { + Logger.debug("No CertificatePolicies extension found"); + return false; + } + + final PolicyInformation[] polInfo = certPol.getPolicyInformation(); + if (polInfo == null) { + Logger.debug("No policy information found"); + return false; + } + + for (final PolicyInformation element : polInfo) { + final ObjectID oid = element.getPolicyIdentifier(); + final String oidStr = oid.getID(); + if (oidStr.compareToIgnoreCase(OID_QCP) == 0) { + Logger.debug("QCP extension found"); + return true; + } + + } + + Logger.debug("No QCP extension found"); + return false; + + } catch (final X509ExtensionInitException e) { + Logger.debug("No QCP extension found"); + return false; + } + + } + + /** + * Verifies if the given certificate contains QcEuCompliance statement + * + * @param cert X509Certificate + * @return true if the given certificate contains QcEuCompliance statement, else + * false + */ + private static boolean checkQcEuCompliance(X509Certificate cert) { + Logger.debug("Checking QcEUCompliance extension"); + try { + final QCStatements qcStatements = (QCStatements) cert.getExtension(QCStatements.oid); + + if (qcStatements == null) { + Logger.debug("No QcStatements extension found"); + return false; + } + + final QCStatement qcEuCompliance = qcStatements.getQCStatements(QcEuCompliance.statementID); + + if (qcEuCompliance != null) { + Logger.debug("QcEuCompliance extension found"); + return true; + } + + Logger.debug("No QcEuCompliance extension found"); + return false; + + } catch (final X509ExtensionInitException e) { + Logger.debug("No QcEuCompliance extension found"); + return false; + } + + } + + /** + * Verifies if the given certificate contains QcEuSSCD statement + * + * @param cert X509Certificate + * @return true if the given certificate contains QcEuSSCD statement, else false + */ + private static boolean checkQcEuSSCD(X509Certificate cert) { + Logger.debug("Checking QcEuSSCD extension"); + try { + final QCStatements qcStatements = (QCStatements) cert.getExtension(QCStatements.oid); + if (qcStatements == null) { + Logger.debug("No QcStatements extension found"); + return false; + } + + final QCStatement qcEuSSCD = qcStatements.getQCStatements(QcEuSSCD.statementID); + + if (qcEuSSCD != null) { + Logger.debug("QcEuSSCD extension found"); + return true; + } + + Logger.debug("No QcEuSSCD extension found"); + return false; + + } catch (final X509ExtensionInitException e) { + Logger.debug("No QcEuSSCD extension found"); + return false; + } + + } + + public static QCSSCDResult checkQCSSCD(X509Certificate[] chain, Date signingTime, + boolean isTSLenabledTrustprofile, ConfigurationProvider config) { + + try { + if (isTSLenabledTrustprofile) { + if (signingTime == null) { + signingTime = new Date(); + Logger.debug("TSL check without signingTime --> use current time for evaluation"); + + } + + final ITslEndEntityResult tslCheckResult = + TSLServiceFactory.getTSLServiceClient().evaluate( + Arrays.asList(chain), + signingTime, + TslConstants.PKIX_MODEL); + + if (tslCheckResult != null) { + final URI tslServiceTypeIdentifier = tslCheckResult.getEvaluatedServiceTypeIdentifier(); + final List tslCertificateQualifier = tslCheckResult.getEvaluatedQualifier(); + + // QC evaluation flags + boolean qc = false; + boolean qcSourceTSL = false; + boolean qcDisallowedFromTSL = false; + + // SSCD/QSCD evaluation flags + boolean sscd = false; + boolean sscdSourceTSL = false; + + // check QC + final List allowedQCQualifier = config.getTSLConfiguration().getQualifierForQC(); + for (final URI el : allowedQCQualifier) { + if (el.equals(tslServiceTypeIdentifier)) { + qcSourceTSL = true; + qc = true; + + } + + } + + // check SSCD/QSCD qualifiers and mark result acording this check + final List allowedSSCDQualifier = config.getTSLConfiguration().getQualifierForSSCD(); + if (tslCertificateQualifier != null && allowedSSCDQualifier != null) { + for (final URI allowedSSCD : allowedSSCDQualifier) { + for (final URI certSSCD : tslCertificateQualifier) { + if (allowedSSCD.equals(certSSCD)) { + sscdSourceTSL = true; + sscd = true; + + } + } + } + } + + // check additional flags in TSP qualifiers for this certificate + if (tslCertificateQualifier != null) { + for (final URI qEl : tslCertificateQualifier) { + // check if SSCD/QSCD status must be used from cert + if (qEl.equals( + TslConstants.SSCD_QUALIFIER_SORT_TO_URI.get( + TslConstants.SSCD_QUALIFIER_SHORT.QCQSCDStatusAsInCert)) + || qEl.equals(TslConstants.SSCD_QUALIFIER_SORT_TO_URI.get( + TslConstants.SSCD_QUALIFIER_SHORT.QCSSCDStatusAsInCert))) { + + sscdSourceTSL = false; + sscd = false; + + // check if extentsion includes a NotQualified flag + } else if (qEl.equals( + TslConstants.SSCD_QUALIFIER_SORT_TO_URI.get( + TslConstants.SSCD_QUALIFIER_SHORT.NotQualified))) { + qc = false; + qcSourceTSL = false; + qcDisallowedFromTSL = true; + Logger.info("TSL mark this certificate explicitly as 'NotQualified'!"); + + } + } + } + + /* + * This block is removes with MOA-SP 3.1 because if TSL support is enabled for + * the requested TrustProfile QC evaluation is ONLY allowed from TSL + * information!!! Because with eIDAS regulation and July 01. 2016 the + * Trust-Status List is constitutive. + */ +// //evaluate QC statement according previous selected information +// if (qcSourceTSL) // Logger.debug("Certificate is QC (Source: TSL)"); -// +// // else { -// -// +// +// // // if TSL return no service-type identifier us information from certificate -// if (tslServiceTypeIdentifier == null || +// if (tslServiceTypeIdentifier == null || // MiscUtil.isEmpty(tslServiceTypeIdentifier.toString())) { // // try certificate extensions QCP and QcEuCompliance // Logger.debug("QC check via TSL returned false - checking certificate extensions"); // boolean checkQCP = CertificateUtils.checkQCP(chain[0]); // boolean checkQcEuCompliance = CertificateUtils.checkQcEuCompliance(chain[0]); -// +// // if ((checkQCP || checkQcEuCompliance) && !qcDisallowedFromTSL) { // Logger.debug("Certificate is QC (Source: Certificate)"); // qc = true; -// +// // } -// } +// } // } - - - //evaluate SSCD/QSCD results according previous selected information - if (sscdSourceTSL) - Logger.debug("Certificate is SSCD (Source: TSL)"); - - else { - // if SSCD check via TSL returns false - // try certificate extensions QCP+ and QcEuSSCD - Logger.debug("SSCD check via TSL returned false - checking certificate extensions"); - boolean checkQCPPlus = CertificateUtils.checkQCPPlus(chain[0]); - boolean checkQcEuSSCD = CertificateUtils.checkQcEuSSCD(chain[0]); - - if (checkQCPPlus || checkQcEuSSCD) { - Logger.debug("Certificate is SSCD (Source: Certificate)"); - sscd = true; - } - } - - //build basic result - QCSSCDResult result = new QCSSCDResult(qc, qcSourceTSL, sscd, sscdSourceTSL); - - //add additinal information - TslInfos extTslInfos = new TslInfosImpl( - tslCheckResult.getTerritory(), - tslCheckResult.getTspStatus(), - tslServiceTypeIdentifier.toString(), - tslCertificateQualifier, - tslCheckResult.getAdditionalServiceInformation()); - result.setTslInfos(extTslInfos); - - return result; - - } else { - Logger.debug("Qualifier check via TSL return null - checking certificate extensions without QC evaluation"); - return parseInfosFromCertificate(chain, false); - - } - - } else - Logger.info("TSL support is not enabled - checking certificate extensions with QC evaluation "); - return parseInfosFromCertificate(chain, true); - } - catch (TslException e) { - MessageProvider msg = MessageProvider.getInstance(); - Logger.error(new LogMsg(msg.getMessage("tsl.01", null)), e); - - return new QCSSCDResult(); - } - - } - - private static QCSSCDResult parseInfosFromCertificate(X509Certificate[] chain, boolean performQCEvaluation) { - boolean qc = false; - boolean sscd = false; - - // Trustprofile is not TSL enabled - use certificate extensions only - - if (performQCEvaluation) { - // perform QC check - // try certificate extensions QCP and QcEuCompliance - boolean checkQCP = CertificateUtils.checkQCP(chain[0]); - boolean checkQcEuCompliance = CertificateUtils.checkQcEuCompliance(chain[0]); - - if (checkQCP || checkQcEuCompliance) - qc = true; - - } - - // perform SSCD check - // try certificate extensions QCP+ and QcEuSSCD - boolean checkQCPPlus = CertificateUtils.checkQCPPlus(chain[0]); - boolean checkQcEuSSCD = CertificateUtils.checkQcEuSSCD(chain[0]); - - if (checkQCPPlus || checkQcEuSSCD) - sscd = true; - - return new QCSSCDResult(qc, false, sscd, false); - - } - - - /** - * Gets the country from the certificate issuer - * @param cert X509 certificate - * @return Country code from the certificate issuer - */ - public static String getIssuerCountry(X509Certificate cert) { - String country = null; - Principal issuerdn = cert.getIssuerX500Principal(); - RFC2253NameParser nameParser = new RFC2253NameParser(issuerdn.getName()); - - try { - Name name = nameParser.parse(); - country = name.getRDN(ObjectID.country); - } catch (RFC2253NameParserException e) { - Logger.warn("Could not get country code from issuer."); - } - - - return country; - } + + // evaluate SSCD/QSCD results according previous selected information + if (sscdSourceTSL) { + Logger.debug("Certificate is SSCD (Source: TSL)"); + } else { + // if SSCD check via TSL returns false + // try certificate extensions QCP+ and QcEuSSCD + Logger.debug("SSCD check via TSL returned false - checking certificate extensions"); + final boolean checkQCPPlus = CertificateUtils.checkQCPPlus(chain[0]); + final boolean checkQcEuSSCD = CertificateUtils.checkQcEuSSCD(chain[0]); + + if (checkQCPPlus || checkQcEuSSCD) { + Logger.debug("Certificate is SSCD (Source: Certificate)"); + sscd = true; + } + } + + // build basic result + final QCSSCDResult result = new QCSSCDResult(qc, qcSourceTSL, sscd, sscdSourceTSL); + + // add additinal information + final TslInfos extTslInfos = new TslInfosImpl( + tslCheckResult.getTerritory(), + tslCheckResult.getTspStatus(), + tslServiceTypeIdentifier.toString(), + tslCertificateQualifier, + tslCheckResult.getAdditionalServiceInformation()); + result.setTslInfos(extTslInfos); + + return result; + + } else { + Logger.debug( + "Qualifier check via TSL return null - checking certificate extensions without QC evaluation"); + return parseInfosFromCertificate(chain, false); + + } + + } else { + Logger.info("TSL support is not enabled - checking certificate extensions with QC evaluation "); + } + return parseInfosFromCertificate(chain, true); + } catch (final TslException e) { + final MessageProvider msg = MessageProvider.getInstance(); + Logger.error(new LogMsg(msg.getMessage("tsl.01", null)), e); + + return new QCSSCDResult(); + } + + } + + private static QCSSCDResult parseInfosFromCertificate(X509Certificate[] chain, + boolean performQCEvaluation) { + boolean qc = false; + boolean sscd = false; + + // Trustprofile is not TSL enabled - use certificate extensions only + + if (performQCEvaluation) { + // perform QC check + // try certificate extensions QCP and QcEuCompliance + final boolean checkQCP = CertificateUtils.checkQCP(chain[0]); + final boolean checkQcEuCompliance = CertificateUtils.checkQcEuCompliance(chain[0]); + + if (checkQCP || checkQcEuCompliance) { + qc = true; + } + + } + + // perform SSCD check + // try certificate extensions QCP+ and QcEuSSCD + final boolean checkQCPPlus = CertificateUtils.checkQCPPlus(chain[0]); + final boolean checkQcEuSSCD = CertificateUtils.checkQcEuSSCD(chain[0]); + + if (checkQCPPlus || checkQcEuSSCD) { + sscd = true; + } + + return new QCSSCDResult(qc, false, sscd, false); + + } + + /** + * Gets the country from the certificate issuer + * + * @param cert X509 certificate + * @return Country code from the certificate issuer + */ + public static String getIssuerCountry(X509Certificate cert) { + String country = null; + final Principal issuerdn = cert.getIssuerX500Principal(); + final RFC2253NameParser nameParser = new RFC2253NameParser(issuerdn.getName()); + + try { + final Name name = nameParser.parse(); + country = name.getRDN(ObjectID.country); + } catch (final RFC2253NameParserException e) { + Logger.warn("Could not get country code from issuer."); + } + + return country; + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/ExternalURIVerifier.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/ExternalURIVerifier.java index 859e7e9..be40a9e 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/ExternalURIVerifier.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/ExternalURIVerifier.java @@ -12,103 +12,103 @@ import at.gv.egovernment.moaspss.logging.LogMsg; import at.gv.egovernment.moaspss.logging.Logger; public class ExternalURIVerifier { - - public static void verify(String host, int port) throws MOAApplicationException { - - - if (host == null) - return; - if (host.equalsIgnoreCase("")) - return; - - try { - ConfigurationProvider config = ConfigurationProvider.getInstance(); - - boolean allowExternalUris = config.getAllowExternalUris(); - List blacklist = config.getBlackListedUris(); - List whitelist = config.getWhiteListedUris(); - - InetAddress hostInetAddress = InetAddress.getByName(host); - String ip = hostInetAddress.getHostAddress(); - - - if (allowExternalUris) { - // external URIs are allowed - check blacklist - Iterator it = blacklist.iterator(); - while (it.hasNext()) { - String[] array = (String[])it.next(); - String bhost = array[0]; - String bport = array[1]; - if (bport == null || port == -1) { - // check only host - if (ip.startsWith(bhost)) { - Logger.debug(new LogMsg("Blacklist check: " + host + " (" + ip + ") blacklisted")); - throw new MOAApplicationException("4002", new Object[]{host + "(" + ip + ")"}); - } - } - else { - // check host and port - int iport = new Integer(bport).intValue(); - if (ip.startsWith(bhost) && (iport == port)) { - Logger.debug(new LogMsg("Blacklist check: " + host + ":" + port + " (" + ip + ":" + port + " blacklisted")); - throw new MOAApplicationException("4002", new Object[]{host + ":" + port + " (" + ip + ":" + port + ")"}); - } - - } - } - } - else { - // external uris are forbidden - check whitelist - Iterator it = whitelist.iterator(); - boolean allowed = false; - while (it.hasNext()) { - String[] array = (String[])it.next(); - String bhost = array[0]; - String bport = array[1]; - if (bport == null || port == -1) { - // check only host - if (ip.startsWith(bhost)) { - Logger.debug(new LogMsg("Whitelist check: " + host + " (" + ip + ") whitelisted")); - allowed = true; - //throw new MOAApplicationException("4002", new Object[]{host + "(" + ip + ")"}); - } - } - else { - // check host and port - int iport = new Integer(bport).intValue(); - if (ip.startsWith(bhost) && (iport == port)) { - Logger.debug(new LogMsg("Whitelist check: " + host + ":" + port + " (" + ip + ":" + port + " whitelisted")); - //throw new MOAApplicationException("4002", new Object[]{host + ":" + port + " (" + ip + ":" + port + ")"}); - allowed = true; - } - - } - } - - if (!allowed) { - if (port != -1) { - Logger.debug(new LogMsg("No external URIs allowed (" + host + ")")); - throw new MOAApplicationException("4001", new Object[]{host + "(" + ip + ")"}); - } - else { - Logger.debug(new LogMsg("No external URIs allowed (" + host + ":" + port + ")")); - throw new MOAApplicationException("4001", new Object[]{host + ":" + port + " (" + ip + ":" + port + ")"}); - } - - } - - } - - Logger.debug(new LogMsg("URI allowed: " + ip + ":" + port)); - - } catch (ConfigurationException e) { - throw new MOAApplicationException("config.10", null); - } catch (UnknownHostException e) { - throw new MOAApplicationException("4003", new Object[]{host}); - } - - - - } + + public static void verify(String host, int port) throws MOAApplicationException { + + if (host == null) { + return; + } + if (host.equalsIgnoreCase("")) { + return; + } + + try { + final ConfigurationProvider config = ConfigurationProvider.getInstance(); + + final boolean allowExternalUris = config.getAllowExternalUris(); + final List blacklist = config.getBlackListedUris(); + final List whitelist = config.getWhiteListedUris(); + + final InetAddress hostInetAddress = InetAddress.getByName(host); + final String ip = hostInetAddress.getHostAddress(); + + if (allowExternalUris) { + // external URIs are allowed - check blacklist + final Iterator it = blacklist.iterator(); + while (it.hasNext()) { + final String[] array = (String[]) it.next(); + final String bhost = array[0]; + final String bport = array[1]; + if (bport == null || port == -1) { + // check only host + if (ip.startsWith(bhost)) { + Logger.debug(new LogMsg("Blacklist check: " + host + " (" + ip + ") blacklisted")); + throw new MOAApplicationException("4002", new Object[] { host + "(" + ip + ")" }); + } + } else { + // check host and port + final int iport = new Integer(bport).intValue(); + if (ip.startsWith(bhost) && iport == port) { + Logger.debug(new LogMsg("Blacklist check: " + host + ":" + port + " (" + ip + ":" + port + + " blacklisted")); + throw new MOAApplicationException("4002", new Object[] { host + ":" + port + " (" + ip + ":" + + port + ")" }); + } + + } + } + } else { + // external uris are forbidden - check whitelist + final Iterator it = whitelist.iterator(); + boolean allowed = false; + while (it.hasNext()) { + final String[] array = (String[]) it.next(); + final String bhost = array[0]; + final String bport = array[1]; + if (bport == null || port == -1) { + // check only host + if (ip.startsWith(bhost)) { + Logger.debug(new LogMsg("Whitelist check: " + host + " (" + ip + ") whitelisted")); + allowed = true; + // throw new MOAApplicationException("4002", new Object[]{host + "(" + ip + + // ")"}); + } + } else { + // check host and port + final int iport = new Integer(bport).intValue(); + if (ip.startsWith(bhost) && iport == port) { + Logger.debug(new LogMsg("Whitelist check: " + host + ":" + port + " (" + ip + ":" + port + + " whitelisted")); + // throw new MOAApplicationException("4002", new Object[]{host + ":" + port + " + // (" + ip + ":" + port + ")"}); + allowed = true; + } + + } + } + + if (!allowed) { + if (port != -1) { + Logger.debug(new LogMsg("No external URIs allowed (" + host + ")")); + throw new MOAApplicationException("4001", new Object[] { host + "(" + ip + ")" }); + } else { + Logger.debug(new LogMsg("No external URIs allowed (" + host + ":" + port + ")")); + throw new MOAApplicationException("4001", new Object[] { host + ":" + port + " (" + ip + ":" + + port + ")" }); + } + + } + + } + + Logger.debug(new LogMsg("URI allowed: " + ip + ":" + port)); + + } catch (final ConfigurationException e) { + throw new MOAApplicationException("config.10", null); + } catch (final UnknownHostException e) { + throw new MOAApplicationException("4003", new Object[] { host }); + } + + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/FilteredOutputStream.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/FilteredOutputStream.java index 3a9fe51..4f33617 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/FilteredOutputStream.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/FilteredOutputStream.java @@ -6,71 +6,73 @@ import java.io.OutputStream; import java.math.BigDecimal; public class FilteredOutputStream extends BufferedOutputStream { - private BigDecimal from = null; - private BigDecimal to = null; - private BigDecimal counter = new BigDecimal("0"); - BigDecimal one = new BigDecimal("1"); - - public FilteredOutputStream(OutputStream innerStream, - int bufferSize, BigDecimal from, - BigDecimal to) { - super(innerStream, bufferSize); - this.from = from; - this.to = to; - } + private BigDecimal from = null; + private BigDecimal to = null; + private BigDecimal counter = new BigDecimal("0"); + BigDecimal one = new BigDecimal("1"); - @Override - public synchronized void write(int b) throws IOException { - if(!inRange(counter)) { - super.write(b); - } - counter = counter.add(one); - } + public FilteredOutputStream(OutputStream innerStream, + int bufferSize, BigDecimal from, + BigDecimal to) { + super(innerStream, bufferSize); + this.from = from; + this.to = to; + } - @Override - public synchronized void write(byte[] b, int off, int len) throws IOException { - this.filteredWrite(b, off, len); - } + @Override + public synchronized void write(int b) throws IOException { + if (!inRange(counter)) { + super.write(b); + } + counter = counter.add(one); + } - @Override - public synchronized void flush() throws IOException { - super.flush(); - } + @Override + public synchronized void write(byte[] b, int off, int len) throws IOException { + this.filteredWrite(b, off, len); + } - @Override - public void write(byte[] b) throws IOException { - if(b != null) { - this.filteredWrite(b, 0, b.length); - } - } + @Override + public synchronized void flush() throws IOException { + super.flush(); + } - @Override - public void close() throws IOException { - super.close(); - } - - private synchronized void filteredWrite(byte[] b, int off, int len) throws IOException { - for(int i = 0; i < len; i++) { - if(!inRange(counter)) { - super.write(b[off+i]); - } - counter = counter.add(one); - } - } - - private boolean inRange(BigDecimal counter) { - if ( (from == null) || (to == null)) - return false; - - int compare = counter.compareTo(from); - if (compare == -1) - return false; - else { - compare = counter.compareTo(to); - if (compare == 1) - return false; - else - return true; - } - } + @Override + public void write(byte[] b) throws IOException { + if (b != null) { + this.filteredWrite(b, 0, b.length); + } + } + + @Override + public void close() throws IOException { + super.close(); + } + + private synchronized void filteredWrite(byte[] b, int off, int len) throws IOException { + for (int i = 0; i < len; i++) { + if (!inRange(counter)) { + super.write(b[off + i]); + } + counter = counter.add(one); + } + } + + private boolean inRange(BigDecimal counter) { + if (from == null || to == null) { + return false; + } + + int compare = counter.compareTo(from); + if (compare == -1) { + return false; + } else { + compare = counter.compareTo(to); + if (compare == 1) { + return false; + } else { + return true; + } + } + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/MOASPSSEntityResolver.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/MOASPSSEntityResolver.java index ee6fe0a..047c2bf 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/MOASPSSEntityResolver.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/MOASPSSEntityResolver.java @@ -36,20 +36,21 @@ import at.gv.egovernment.moaspss.logging.LogMsg; import at.gv.egovernment.moaspss.logging.Logger; import at.gv.egovernment.moaspss.util.Constants; - /** - * An EntityResolver that looks up entities stored as - * local resources. - * - *

    The following DTDs are mapped to local resources: + * 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, + *

    + * For all other resources, an attempt is made to resolve them as resources, * either absolute or relative to Constants.SCHEMA_ROOT. - * + * * @author Patrick Peck * @author Sven Aigner */ @@ -57,65 +58,66 @@ public class MOASPSSEntityResolver implements EntityResolver { /** * 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 + * 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) + * null, if the entity could not be found. + * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, + * java.lang.String) */ + @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException { InputStream stream; int slashPos; - + if (Logger.isDebugEnabled()) { Logger.debug( - new LogMsg("resolveEntity: p=" + publicId + " s=" + systemId)); + new LogMsg("resolveEntity: p=" + publicId + " s=" + systemId)); } 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( - Constants.SCHEMA_ROOT + "XMLSchema.dtd")); + getClass().getResourceAsStream( + Constants.SCHEMA_ROOT + "XMLSchema.dtd")); } else if (publicId.equalsIgnoreCase("datatypes")) { return new InputSource( - getClass().getResourceAsStream( - Constants.SCHEMA_ROOT + "datatypes.dtd")); + getClass().getResourceAsStream( + Constants.SCHEMA_ROOT + "datatypes.dtd")); } } else if (systemId != null) { // get the URI path try { - URI uri = new URI(systemId); + final URI uri = new URI(systemId); systemId = uri.getPath(); - + if ("".equals(systemId.trim())) { return null; } - + // if (!"file".equals(uri.getScheme()) || "".equals(systemId.trim())) { // return null; // } ExternalURIVerifier.verify(uri.getHost(), uri.getPort()); - - } catch (MalformedURIException e) { + + } catch (final MalformedURIException e) { return null; - } - catch (MOAApplicationException e) { - throw new SAXException(e); + } catch (final MOAApplicationException e) { + throw new SAXException(e); } - + // try to get the resource from the full path stream = getClass().getResourceAsStream(systemId); if (stream != null) { - InputSource source = new InputSource(stream); + final InputSource source = new InputSource(stream); source.setSystemId(systemId); return source; @@ -126,9 +128,9 @@ public class MOASPSSEntityResolver implements EntityResolver { if (slashPos >= 0 && systemId.length() > slashPos) { systemId = systemId.substring(slashPos + 1, systemId.length()); stream = - getClass().getResourceAsStream(Constants.SCHEMA_ROOT + systemId); + getClass().getResourceAsStream(Constants.SCHEMA_ROOT + systemId); if (stream != null) { - InputSource source = new InputSource(stream); + final InputSource source = new InputSource(stream); source.setSystemId(systemId); return source; diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/MessageProvider.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/MessageProvider.java index 47b8d36..cb83b3a 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/MessageProvider.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/MessageProvider.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.util; import java.util.Locale; @@ -30,45 +29,45 @@ import at.gv.egovernment.moaspss.util.Messages; /** * Singleton wrapper around a Messages object. - * + * * @author Patrick Peck * @version $Id$ */ public class MessageProvider { - - /** The resource names of the messages to load. */ + + /** The resource names of the messages to load. */ private static final String[] DEFAULT_MESSAGE_RESOURCES = - { "resources/properties/spss_messages" }; + { "resources/properties/spss_messages" }; /** The corresponding message locales. */ private static final Locale[] DEFAULT_MESSAGE_LOCALES = - new Locale[] { new Locale("de", "AT") }; + new Locale[] { new Locale("de", "AT") }; /** The single instance of this class. */ private static MessageProvider instance; - + /** The messages provided by the MessageProvider. */ - private Messages messages; - + private final Messages messages; + /** * Return the single instance of the MessageProvider. - * + * * Intialilizes the MessageProvider with the default message * locations: /resources/properties/spss_messages. - * + * * @return The single MessageProvider. */ public static synchronized MessageProvider getInstance() { if (instance == null) { instance = - new MessageProvider(DEFAULT_MESSAGE_RESOURCES, DEFAULT_MESSAGE_LOCALES); + new MessageProvider(DEFAULT_MESSAGE_RESOURCES, DEFAULT_MESSAGE_LOCALES); } return instance; } /** * Create a MessageProvider. - * + * * @param resourceNames The names of the resources containing the messages. - * @param locales The corresponding locales. + * @param locales The corresponding locales. */ protected MessageProvider(String[] resourceNames, Locale[] locales) { this.messages = new Messages(resourceNames, locales); @@ -77,13 +76,12 @@ public class MessageProvider { /** * Get the message corresponding to a given message ID. * - * @param messageId The ID of the message. + * @param messageId The ID of the message. * @param parameters The parameters to fill in into the message arguments. - * @return The formatted message. + * @return The formatted message. */ public String getMessage(String messageId, Object[] parameters) { return messages.getMessage(messageId, parameters); } - } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/NodeListToNodeSetDataAdapter.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/NodeListToNodeSetDataAdapter.java index e9b1f7d..9c684b1 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/NodeListToNodeSetDataAdapter.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/NodeListToNodeSetDataAdapter.java @@ -10,17 +10,17 @@ import org.w3c.dom.NodeList; public class NodeListToNodeSetDataAdapter implements NodeSetData { - private List list = new ArrayList(); - - public NodeListToNodeSetDataAdapter(NodeList list) { - for(int i = 0; i < list.getLength(); i++) { - this.list.add(list.item(i)); - } - } - - @Override - public Iterator iterator() { - return this.list.iterator(); - } + private final List list = new ArrayList(); + + public NodeListToNodeSetDataAdapter(NodeList list) { + for (int i = 0; i < list.getLength(); i++) { + this.list.add(list.item(i)); + } + } + + @Override + public Iterator iterator() { + return this.list.iterator(); + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/QCSSCDResult.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/QCSSCDResult.java index c00225d..3e8a7fd 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/QCSSCDResult.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/QCSSCDResult.java @@ -4,50 +4,50 @@ import at.gv.egovernment.moa.spss.api.common.TslInfos; public class QCSSCDResult { - private boolean qc; - private boolean qcSourceTSL; - - private boolean sscd; - private boolean sscdSourceTSL; - - private TslInfos tslInfos; - - - - public QCSSCDResult() { - this.qc = false; - this.qcSourceTSL = false; - this.sscd = false; - this.sscdSourceTSL = false; - } - - public QCSSCDResult(boolean qc, boolean qcSourceTSL, boolean sscd, boolean sscdSourceTSL) { - this.qc = qc; - this.qcSourceTSL = qcSourceTSL; - this.sscd = sscd; - this.sscdSourceTSL = sscdSourceTSL; - } - - public boolean isQC() { - return this.qc; - } - public boolean isQCSourceTSL() { - return this.qcSourceTSL; - } - public boolean isSSCD() { - return this.sscd; - } - public boolean isSSCDSourceTSL() { - return this.sscdSourceTSL; - } - - public TslInfos getTslInfos() { - return tslInfos; - } - - public void setTslInfos(TslInfos tslInfos) { - this.tslInfos = tslInfos; - } - - + private final boolean qc; + private final boolean qcSourceTSL; + + private final boolean sscd; + private final boolean sscdSourceTSL; + + private TslInfos tslInfos; + + public QCSSCDResult() { + this.qc = false; + this.qcSourceTSL = false; + this.sscd = false; + this.sscdSourceTSL = false; + } + + public QCSSCDResult(boolean qc, boolean qcSourceTSL, boolean sscd, boolean sscdSourceTSL) { + this.qc = qc; + this.qcSourceTSL = qcSourceTSL; + this.sscd = sscd; + this.sscdSourceTSL = sscdSourceTSL; + } + + public boolean isQC() { + return this.qc; + } + + public boolean isQCSourceTSL() { + return this.qcSourceTSL; + } + + public boolean isSSCD() { + return this.sscd; + } + + public boolean isSSCDSourceTSL() { + return this.sscdSourceTSL; + } + + public TslInfos getTslInfos() { + return tslInfos; + } + + public void setTslInfos(TslInfos tslInfos) { + this.tslInfos = tslInfos; + } + } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/ResetableInputStreamWrapper.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/ResetableInputStreamWrapper.java index 243cd5d..f0e5326 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/ResetableInputStreamWrapper.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/ResetableInputStreamWrapper.java @@ -6,54 +6,54 @@ import java.io.InputStream; public class ResetableInputStreamWrapper extends InputStream { - private ByteArrayInputStream bais; - - public ResetableInputStreamWrapper(ByteArrayInputStream bais) { - this.bais = bais; - } - - @Override - public int read() throws IOException { - return this.bais.read(); - } - - @Override - public int read(byte[] b) throws IOException { - return this.bais.read(b); - } - - @Override - public int read(byte[] b, int off, int len) throws IOException { - return this.bais.read(b, off, len); - } - - @Override - public long skip(long n) throws IOException { - return this.bais.skip(n); - } - - @Override - public int available() throws IOException { - return this.bais.available(); - } - - @Override - public void close() throws IOException { - this.bais.close(); - } - - @Override - public synchronized void mark(int readlimit) { - this.bais.mark(readlimit); - } - - @Override - public synchronized void reset() throws IOException { - this.bais.reset(); - } - - @Override - public boolean markSupported() { - return this.bais.markSupported(); - } + private final ByteArrayInputStream bais; + + public ResetableInputStreamWrapper(ByteArrayInputStream bais) { + this.bais = bais; + } + + @Override + public int read() throws IOException { + return this.bais.read(); + } + + @Override + public int read(byte[] b) throws IOException { + return this.bais.read(b); + } + + @Override + public int read(byte[] b, int off, int len) throws IOException { + return this.bais.read(b, off, len); + } + + @Override + public long skip(long n) throws IOException { + return this.bais.skip(n); + } + + @Override + public int available() throws IOException { + return this.bais.available(); + } + + @Override + public void close() throws IOException { + this.bais.close(); + } + + @Override + public synchronized void mark(int readlimit) { + this.bais.mark(readlimit); + } + + @Override + public synchronized void reset() throws IOException { + this.bais.reset(); + } + + @Override + public boolean markSupported() { + return this.bais.markSupported(); + } } diff --git a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/SecProviderUtils.java b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/SecProviderUtils.java index 30f3688..12e3837 100644 --- a/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/SecProviderUtils.java +++ b/moaSig/moa-sig-lib/src/main/java/at/gv/egovernment/moa/spss/util/SecProviderUtils.java @@ -7,17 +7,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SecProviderUtils { - - private static final Logger logger = LoggerFactory.getLogger(SecProviderUtils.class); - - - public static void dumpSecProviders(String message) { - if (logger.isDebugEnabled()) { - logger.info("Security Providers: {}", message); - for(Provider provider : Security.getProviders()) { - logger.info(" - {} - {}", provider.getName(), provider.getVersion()); - - } - } - } + + private static final Logger logger = LoggerFactory.getLogger(SecProviderUtils.class); + + public static void dumpSecProviders(String message) { + if (logger.isDebugEnabled()) { + logger.info("Security Providers: {}", message); + for (final Provider provider : Security.getProviders()) { + logger.info(" - {} - {}", provider.getName(), provider.getVersion()); + + } + } + } } diff --git a/moaSig/moa-sig/build.gradle b/moaSig/moa-sig/build.gradle index b3574e6..f03d350 100644 --- a/moaSig/moa-sig/build.gradle +++ b/moaSig/moa-sig/build.gradle @@ -17,6 +17,8 @@ dependencies { providedCompile 'javax.servlet:servlet-api:2.4' compile 'commons-discovery:commons-discovery:0.5' compile 'org.slf4j:slf4j-log4j12:1.7.30' + implementation group: 'javax.jws', name: 'javax.jws-api', version: '1.1' + //compile group: 'org.slf4j', name: 'log4j-over-slf4j', version: '1.7.30' //compile 'org.apache.cxf:cxf-rt-frontend-jaxws:3.1.4' diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/initializer/PDFASInitializer.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/initializer/PDFASInitializer.java index fb84293..dfc7bff 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/initializer/PDFASInitializer.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/initializer/PDFASInitializer.java @@ -5,24 +5,23 @@ import org.slf4j.LoggerFactory; import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; import at.gv.egovernment.moa.spss.server.init.ExternalInitializer; -import at.gv.egovernment.moa.spss.server.invoke.PDFASInvoker; public class PDFASInitializer implements ExternalInitializer { - private static final Logger logger = LoggerFactory.getLogger(PDFASInitializer.class); - - @Override - public void initialize(ConfigurationProvider configurationProvider) { - logger.warn("Log4j Config: {}", System.getProperty("log4j.configuration")); - - /*String pdfAsConfiguration = configurationProvider.getPDFASConfiguration(); - - logger.info("Running PDFASInitializer with pdf as cfg: {}", pdfAsConfiguration); - - if(pdfAsConfiguration != null) { - PDFASInvoker - .init(pdfAsConfiguration); - }*/ - } + private static final Logger logger = LoggerFactory.getLogger(PDFASInitializer.class); + + @Override + public void initialize(ConfigurationProvider configurationProvider) { + logger.warn("Log4j Config: {}", System.getProperty("log4j.configuration")); + + /* + * String pdfAsConfiguration = configurationProvider.getPDFASConfiguration(); + * + * logger.info("Running PDFASInitializer with pdf as cfg: {}", + * pdfAsConfiguration); + * + * if(pdfAsConfiguration != null) { PDFASInvoker .init(pdfAsConfiguration); } + */ + } } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/invoke/PDFASInvoker.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/invoke/PDFASInvoker.java index 1f7522b..94c2239 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/invoke/PDFASInvoker.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/invoke/PDFASInvoker.java @@ -1,118 +1,82 @@ package at.gv.egovernment.moa.spss.server.invoke; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.util.Iterator; -import java.util.List; - -import org.apache.commons.io.IOUtils; - -import at.gv.egovernment.moa.spss.MOAApplicationException; -import at.gv.egovernment.moa.spss.MOAException; -import at.gv.egovernment.moa.spss.server.logging.TransactionId; -import at.gv.egovernment.moa.spss.server.pdfas.InternalMoaConnector; -import at.gv.egovernment.moa.spss.server.pdfas.InternalMoaVerifier; -import at.gv.egovernment.moa.spss.server.xmlbind.CreatePDFRequest; -import at.gv.egovernment.moa.spss.server.xmlbind.CreatePDFRespone; -import at.gv.egovernment.moa.spss.server.xmlbind.PDFSignatureInfo; -import at.gv.egovernment.moa.spss.server.xmlbind.SignedPDFInfo; -import at.gv.egovernment.moa.spss.server.xmlbind.VerifyPDFRequest; -import at.gv.egovernment.moa.spss.server.xmlbind.VerifyPDFResponse; -import at.gv.egovernment.moaspss.logging.Logger; - public class PDFASInvoker { - /* - private static PDFASInvoker instance = null; - - private PdfAs pdfAS; - - private PDFASInvoker(File configuration) { - pdfAS = PdfAsFactory.createPdfAs(configuration); - } - - public synchronized static void init(String pdfAsConfiguration) { - instance = new PDFASInvoker(new File(pdfAsConfiguration)); - } - - public synchronized static PDFASInvoker getInstance() { - if (instance == null) { - throw new RuntimeException("PDF PDFASInvoker not initialized"); - } - return instance; - } - - public VerifyPDFResponse verifyPDFSignature(VerifyPDFRequest verifyPDFRequest) throws MOAException { - Configuration pdfConfiguration = this.pdfAS.getConfiguration(); - - VerifyPDFResponse verifyPDFResponse = new VerifyPDFResponse(); - - VerifyParameter verifyParameter = PdfAsFactory.createVerifyParameter(pdfConfiguration, new ByteArrayDataSource( - verifyPDFRequest.getSignedPDF())); - - pdfConfiguration.setValue(InternalMoaVerifier.MOA_TRUSTPROFILE, verifyPDFRequest.getTrustProfileID()); - - try { - List verifyResults = this.pdfAS.verify(verifyParameter); - verifyPDFResponse.setVerificationResults(verifyResults); - } catch (Throwable e) { - Logger.warn("Failed to generate signed PDF document", e); - throw new MOAApplicationException("Failed to generate signed PDF document", null, e); - } - - return verifyPDFResponse; - } - - public CreatePDFRespone createPDFSignature(CreatePDFRequest createPDFRequest, String transactionId) { - Configuration pdfConfiguration = this.pdfAS.getConfiguration(); - - String keyIdentifier = createPDFRequest.getKeyIdentifier(); - - Iterator signatureInfoIterator = createPDFRequest.getSignatureInfoList().iterator(); - - CreatePDFRespone createPDFRespone = new CreatePDFRespone(); - - while (signatureInfoIterator.hasNext()) { - PDFSignatureInfo pdfSignatureInfo = signatureInfoIterator.next(); - SignedPDFInfo signedPDFInfo = new SignedPDFInfo(pdfSignatureInfo.getSignatureID()); - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - SignParameter signParameter = PdfAsFactory.createSignParameter(pdfConfiguration, - new ByteArrayDataSource(pdfSignatureInfo.getPdfDocument()), baos); - - signParameter.setSignaturePosition(pdfSignatureInfo.getSignaturePosition()); - signParameter.setSignatureProfileId(pdfSignatureInfo.getSignatureProfile()); - - IPlainSigner signer = new PAdESSigner( - new InternalMoaConnector(keyIdentifier, new TransactionId(transactionId), null)); - - signParameter.setPlainSigner(signer); - - try { - this.pdfAS.sign(signParameter); - signedPDFInfo.setPdfDocument(baos.toByteArray()); - signedPDFInfo.setResponseType(SignedPDFInfo.SUCCESS_SIGNATURE); - } catch (Throwable e) { - signedPDFInfo.setResponseType(SignedPDFInfo.ERROR_RESPONSE); - - if (e instanceof PDFASError) { - PDFASError pdfAsError = (PDFASError) e; - Logger.warn("Failed to generate signed PDF document", e); - signedPDFInfo.setErrorCode((int) pdfAsError.getCode()); - signedPDFInfo.setErrorInfo(pdfAsError.getInfo()); - } else { - Logger.error("Unknown exception!: ", e); - signedPDFInfo.setErrorCode(9999); - signedPDFInfo.setErrorInfo("Nicht klassifizierter Fehler"); - } - } finally { - IOUtils.closeQuietly(baos); - } - - } finally { - createPDFRespone.getSignatureInfoList().add(signedPDFInfo); - } - - } - return createPDFRespone; - }*/ + /* + * private static PDFASInvoker instance = null; + * + * private PdfAs pdfAS; + * + * private PDFASInvoker(File configuration) { pdfAS = + * PdfAsFactory.createPdfAs(configuration); } + * + * public synchronized static void init(String pdfAsConfiguration) { instance = + * new PDFASInvoker(new File(pdfAsConfiguration)); } + * + * public synchronized static PDFASInvoker getInstance() { if (instance == null) + * { throw new RuntimeException("PDF PDFASInvoker not initialized"); } return + * instance; } + * + * public VerifyPDFResponse verifyPDFSignature(VerifyPDFRequest + * verifyPDFRequest) throws MOAException { Configuration pdfConfiguration = + * this.pdfAS.getConfiguration(); + * + * VerifyPDFResponse verifyPDFResponse = new VerifyPDFResponse(); + * + * VerifyParameter verifyParameter = + * PdfAsFactory.createVerifyParameter(pdfConfiguration, new ByteArrayDataSource( + * verifyPDFRequest.getSignedPDF())); + * + * pdfConfiguration.setValue(InternalMoaVerifier.MOA_TRUSTPROFILE, + * verifyPDFRequest.getTrustProfileID()); + * + * try { List verifyResults = this.pdfAS.verify(verifyParameter); + * verifyPDFResponse.setVerificationResults(verifyResults); } catch (Throwable + * e) { Logger.warn("Failed to generate signed PDF document", e); throw new + * MOAApplicationException("Failed to generate signed PDF document", null, e); } + * + * return verifyPDFResponse; } + * + * public CreatePDFRespone createPDFSignature(CreatePDFRequest createPDFRequest, + * String transactionId) { Configuration pdfConfiguration = + * this.pdfAS.getConfiguration(); + * + * String keyIdentifier = createPDFRequest.getKeyIdentifier(); + * + * Iterator signatureInfoIterator = + * createPDFRequest.getSignatureInfoList().iterator(); + * + * CreatePDFRespone createPDFRespone = new CreatePDFRespone(); + * + * while (signatureInfoIterator.hasNext()) { PDFSignatureInfo pdfSignatureInfo = + * signatureInfoIterator.next(); SignedPDFInfo signedPDFInfo = new + * SignedPDFInfo(pdfSignatureInfo.getSignatureID()); try { ByteArrayOutputStream + * baos = new ByteArrayOutputStream(); SignParameter signParameter = + * PdfAsFactory.createSignParameter(pdfConfiguration, new + * ByteArrayDataSource(pdfSignatureInfo.getPdfDocument()), baos); + * + * signParameter.setSignaturePosition(pdfSignatureInfo.getSignaturePosition()); + * signParameter.setSignatureProfileId(pdfSignatureInfo.getSignatureProfile()); + * + * IPlainSigner signer = new PAdESSigner( new + * InternalMoaConnector(keyIdentifier, new TransactionId(transactionId), null)); + * + * signParameter.setPlainSigner(signer); + * + * try { this.pdfAS.sign(signParameter); + * signedPDFInfo.setPdfDocument(baos.toByteArray()); + * signedPDFInfo.setResponseType(SignedPDFInfo.SUCCESS_SIGNATURE); } catch + * (Throwable e) { signedPDFInfo.setResponseType(SignedPDFInfo.ERROR_RESPONSE); + * + * if (e instanceof PDFASError) { PDFASError pdfAsError = (PDFASError) e; + * Logger.warn("Failed to generate signed PDF document", e); + * signedPDFInfo.setErrorCode((int) pdfAsError.getCode()); + * signedPDFInfo.setErrorInfo(pdfAsError.getInfo()); } else { + * Logger.error("Unknown exception!: ", e); signedPDFInfo.setErrorCode(9999); + * signedPDFInfo.setErrorInfo("Nicht klassifizierter Fehler"); } } finally { + * IOUtils.closeQuietly(baos); } + * + * } finally { createPDFRespone.getSignatureInfoList().add(signedPDFInfo); } + * + * } return createPDFRespone; } + */ } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/pdfas/ExtendedVerifyResult.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/pdfas/ExtendedVerifyResult.java index 705e124..2dbb239 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/pdfas/ExtendedVerifyResult.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/pdfas/ExtendedVerifyResult.java @@ -1,61 +1,45 @@ package at.gv.egovernment.moa.spss.server.pdfas; + /* import at.gv.egiz.pdfas.lib.api.verify.VerifyResult; import at.gv.egiz.pdfas.lib.impl.verify.VerifyResultImpl; */ -public class ExtendedVerifyResult { /*extends VerifyResultImpl implements VerifyResult { - private String qcSource; - private boolean publicAuthority; - private String publicAuthorityID; - private boolean SSCD; - private String sscdSource; - private String issureCountryCode; - - public synchronized String getIssureCountryCode() { - return issureCountryCode; - } - - public synchronized void setIssureCountryCode(String issureCountryCode) { - this.issureCountryCode = issureCountryCode; - } - - public synchronized String getQcSource() { - return qcSource; - } - - public synchronized void setQcSource(String qcSource) { - this.qcSource = qcSource; - } - - public synchronized boolean isPublicAuthority() { - return publicAuthority; - } - - public synchronized void setPublicAuthority(boolean publicAuthority) { - this.publicAuthority = publicAuthority; - } - - public synchronized String getPublicAuthorityID() { - return publicAuthorityID; - } - - public synchronized void setPublicAuthorityID(String publicAuthorityID) { - this.publicAuthorityID = publicAuthorityID; - } - - public synchronized boolean isSSCD() { - return SSCD; - } - - public synchronized void setSSCD(boolean sSCD) { - SSCD = sSCD; - } - - public synchronized String getSscdSource() { - return sscdSource; - } - - public synchronized void setSscdSource(String sscdSource) { - this.sscdSource = sscdSource; - }*/ +public class ExtendedVerifyResult { /* + * extends VerifyResultImpl implements VerifyResult { private String + * qcSource; private boolean publicAuthority; private String + * publicAuthorityID; private boolean SSCD; private String sscdSource; + * private String issureCountryCode; + * + * public synchronized String getIssureCountryCode() { return + * issureCountryCode; } + * + * public synchronized void setIssureCountryCode(String issureCountryCode) + * { this.issureCountryCode = issureCountryCode; } + * + * public synchronized String getQcSource() { return qcSource; } + * + * public synchronized void setQcSource(String qcSource) { this.qcSource = + * qcSource; } + * + * public synchronized boolean isPublicAuthority() { return + * publicAuthority; } + * + * public synchronized void setPublicAuthority(boolean publicAuthority) { + * this.publicAuthority = publicAuthority; } + * + * public synchronized String getPublicAuthorityID() { return + * publicAuthorityID; } + * + * public synchronized void setPublicAuthorityID(String publicAuthorityID) + * { this.publicAuthorityID = publicAuthorityID; } + * + * public synchronized boolean isSSCD() { return SSCD; } + * + * public synchronized void setSSCD(boolean sSCD) { SSCD = sSCD; } + * + * public synchronized String getSscdSource() { return sscdSource; } + * + * public synchronized void setSscdSource(String sscdSource) { + * this.sscdSource = sscdSource; } + */ } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/pdfas/InternalMoaConnector.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/pdfas/InternalMoaConnector.java index 0344346..efcd2ce 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/pdfas/InternalMoaConnector.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/pdfas/InternalMoaConnector.java @@ -1,227 +1,170 @@ package at.gv.egovernment.moa.spss.server.pdfas; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.security.Principal; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import at.gv.egovernment.moa.spss.MOAException; -import at.gv.egovernment.moa.spss.api.cmssign.CMSSignatureResponse; -import at.gv.egovernment.moa.spss.api.cmssign.CreateCMSSignatureResponse; -import at.gv.egovernment.moa.spss.api.cmssign.CreateCMSSignatureResponseElement; -import at.gv.egovernment.moa.spss.api.impl.CMSContentExplicitImpl; -import at.gv.egovernment.moa.spss.api.impl.CMSDataObjectImpl; -import at.gv.egovernment.moa.spss.api.impl.CreateCMSSignatureRequestImpl; -import at.gv.egovernment.moa.spss.api.impl.DataObjectInfoCMSImpl; -import at.gv.egovernment.moa.spss.api.impl.MetaInfoImpl; -import at.gv.egovernment.moa.spss.api.impl.SingleSignatureInfoCMSImpl; -import at.gv.egovernment.moa.spss.api.xmlsign.ErrorResponse; -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.config.KeyGroupEntry; -import at.gv.egovernment.moa.spss.server.invoke.CMSSignatureCreationInvoker; -import at.gv.egovernment.moaspss.logging.Logger; -import at.gv.egovernment.moaspss.util.Base64Utils; -import iaik.logging.TransactionId; -import iaik.server.modules.keys.KeyEntryID; -import iaik.server.modules.keys.KeyModule; -import iaik.server.modules.keys.KeyModuleFactory; -import iaik.server.modules.keys.UnknownKeyException; -import iaik.x509.X509Certificate; - -public class InternalMoaConnector { /*implements ISignatureConnector { - - private String keyIdentifier; - private X509Certificate clientCert; - private TransactionId transactionId; - - public InternalMoaConnector(String keyIdentifier, TransactionId transactionId, X509Certificate clientCert) { - this.keyIdentifier = keyIdentifier; - this.transactionId = transactionId; - this.clientCert = clientCert; - } - @SuppressWarnings({ "rawtypes", "unchecked" }) - private Set buildKeySet(String keyGroupID, KeyModule module) throws ConfigurationException { - ConfigurationProvider config = ConfigurationProvider.getInstance(); - - Set keyGroupEntries; - - // get the KeyGroup entries from the configuration - if (clientCert != null) { - Principal issuer = clientCert.getIssuerDN(); - BigInteger serialNumber = clientCert.getSerialNumber(); - - keyGroupEntries = config.getKeyGroupEntries(issuer, serialNumber, keyGroupID); - } else { - keyGroupEntries = config.getKeyGroupEntries(null, null, keyGroupID); - } - - // map the KeyGroup entries to a set of KeyEntryIDs - if (keyGroupEntries == null) { - return Collections.EMPTY_SET; - } else if (keyGroupEntries.size() == 0) { - return Collections.EMPTY_SET; - } else { - - Set keyEntryIDs = module.getPrivateKeyEntryIDs(); - Set keySet = new HashSet(); - Iterator iter; - - // filter out the keys that do not exist in the IAIK configuration - // by walking through the key entries and checking if the exist in - // the - // keyGroupEntries - for (iter = keyEntryIDs.iterator(); iter.hasNext();) { - KeyEntryID entryID = (KeyEntryID) iter.next(); - KeyGroupEntry entry = new KeyGroupEntry(entryID.getModuleID(), entryID.getCertificateIssuer(), - entryID.getCertificateSerialNumber()); - if (keyGroupEntries.contains(entry)) { - keySet.add(entryID); - } - } - return keySet; - } - } - - @Override - @SuppressWarnings("rawtypes") - public X509Certificate getCertificate(SignParameter parameter) throws PdfAsException { - KeyModule module = KeyModuleFactory.getInstance(this.transactionId); - - Set keySet = null; - try { - keySet = buildKeySet(this.keyIdentifier, module); - } catch (ConfigurationException e2) { - Logger.warn("MOA not correctly configured!", e2); - throw new PdfAsException("MOA not correctly configured!"); - } - - if (keySet == null || keySet.isEmpty()) { - Logger.warn("No keys available for Key Identifier " + this.keyIdentifier + " and given authentication."); - throw new PdfAsException("Invalid Key Identifier: " + this.keyIdentifier); - } - - if (keySet.size() != 1) { - Logger.warn( - "Too many keys available for Key Identifier " + this.keyIdentifier + " and given authentication."); - throw new PdfAsException("Too many keys available for Key Identifier: " + this.keyIdentifier); - } - - Iterator iter; - - // filter out the keys that do not exist in the IAIK configuration - // by walking through the key entries and checking if the exist in - // the - // keyGroupEntries - for (iter = keySet.iterator(); iter.hasNext();) { - KeyEntryID entryID = (KeyEntryID) iter.next(); - - List certChain = null; - try { - certChain = module.getPrivateKeyEntry(entryID).getCertificateChain(); - } catch (UnknownKeyException e1) { - Logger.warn("Unknown KeyIdentifier found!", e1); - throw new PdfAsException("Unknown Key Identifier: " + this.keyIdentifier); - } - - if (certChain != null && !certChain.isEmpty()) { - Logger.trace("Returning Certificate!"); - Certificate keyCert = ((Certificate) certChain.get(0)); - if (keyCert instanceof X509Certificate) { - return (X509Certificate) keyCert; - } else { - try { - return new X509Certificate(keyCert.getEncoded()); - } catch (CertificateEncodingException e) { - Logger.warn("Invalid certificate found!", e); - throw new PdfAsException("Invalid certificate for Key Identifier: " + this.keyIdentifier); - } catch (CertificateException e) { - Logger.warn("Invalid certificate found!", e); - throw new PdfAsException("Invalid certificate for Key Identifier: " + this.keyIdentifier); - } - } - } - - break; - } - - // No Certificate could be found! - Logger.warn("Failed to find keys available for Key Identifier " + this.keyIdentifier - + " and given authentication."); - throw new PdfAsException("Failed to find keys available for Key Identifier: " + this.keyIdentifier); - } - - @SuppressWarnings("unchecked") - @Override - public byte[] sign(byte[] input, int[] byteRange, SignParameter parameter, RequestedSignature requestedSignature) - throws PdfAsException { - - CreateCMSSignatureRequestImpl createCMSSignatureRequest = new CreateCMSSignatureRequestImpl(); - createCMSSignatureRequest.setKeyIdentifier(this.keyIdentifier); - SingleSignatureInfoCMSImpl singleSignatureInfos = new SingleSignatureInfoCMSImpl(); - - DataObjectInfoCMSImpl dataObjectInfoCMSImpl = new DataObjectInfoCMSImpl(); - - dataObjectInfoCMSImpl.setStructure(DataObjectInfoCMSImpl.STRUCTURE_DETACHED); - - CMSDataObjectImpl cmsDataObjectImpl = new CMSDataObjectImpl(); - - CMSContentExplicitImpl cmsContent = new CMSContentExplicitImpl(); - cmsContent.setBinaryContent(new ByteArrayInputStream(input)); - - cmsDataObjectImpl.setContent(cmsContent); - - MetaInfoImpl metaInfoImpl = new MetaInfoImpl(); - - metaInfoImpl.setMimeType("application/pdf"); - - cmsDataObjectImpl.setMetaInfo(metaInfoImpl); - - dataObjectInfoCMSImpl.setDataObject(cmsDataObjectImpl); - - singleSignatureInfos.setDataObjectInfo(dataObjectInfoCMSImpl); - - createCMSSignatureRequest.getSingleSignatureInfos().add(singleSignatureInfos); - - try { - CreateCMSSignatureResponse createCMSSignatureResponse = CMSSignatureCreationInvoker.getInstance() - .createCMSSignature(createCMSSignatureRequest, Collections.EMPTY_SET); - - if (createCMSSignatureResponse.getResponseElements().isEmpty()) { - Logger.error("MOA CMS Signature response is empty!"); - throw new PdfAsException("MOA CMS Signature response is empty"); - } - - CreateCMSSignatureResponseElement createCMSSignatureResponseElement = (CreateCMSSignatureResponseElement) createCMSSignatureResponse - .getResponseElements().get(0); - - if(createCMSSignatureResponseElement.getResponseType() - == CreateCMSSignatureResponseElement.ERROR_RESPONSE) { - ErrorResponse errorResponse = (ErrorResponse) createCMSSignatureResponseElement; - Logger.error("Failed to create signature " + errorResponse.getErrorCode() + " " + errorResponse.getInfo()); - throw new PdfAsErrorCarrier(new PDFASError(errorResponse.getErrorCode(), errorResponse.getInfo())); - } else if(createCMSSignatureResponseElement.getResponseType() - == CreateCMSSignatureResponseElement.CMS_SIGNATURE ) { - CMSSignatureResponse cmsSignatureResponse = (CMSSignatureResponse) createCMSSignatureResponseElement; - return Base64Utils.decode(cmsSignatureResponse.getCMSSignature(), true); - } - } catch (MOAException e) { - Logger.error("Failed to create signature!", e); - throw new PdfAsException("Failed to create signature!", e); - } catch (IOException e) { - Logger.error("Failed to create signature!", e); - throw new PdfAsException("Failed to create signature!", e); - } - - return null; - } - */ +public class InternalMoaConnector { /* + * implements ISignatureConnector { + * + * private String keyIdentifier; private X509Certificate clientCert; + * private TransactionId transactionId; + * + * public InternalMoaConnector(String keyIdentifier, TransactionId + * transactionId, X509Certificate clientCert) { this.keyIdentifier = + * keyIdentifier; this.transactionId = transactionId; this.clientCert = + * clientCert; } + * + * @SuppressWarnings({ "rawtypes", "unchecked" }) private Set + * buildKeySet(String keyGroupID, KeyModule module) throws + * ConfigurationException { ConfigurationProvider config = + * ConfigurationProvider.getInstance(); + * + * Set keyGroupEntries; + * + * // get the KeyGroup entries from the configuration if (clientCert != + * null) { Principal issuer = clientCert.getIssuerDN(); BigInteger + * serialNumber = clientCert.getSerialNumber(); + * + * keyGroupEntries = config.getKeyGroupEntries(issuer, serialNumber, + * keyGroupID); } else { keyGroupEntries = config.getKeyGroupEntries(null, + * null, keyGroupID); } + * + * // map the KeyGroup entries to a set of KeyEntryIDs if (keyGroupEntries + * == null) { return Collections.EMPTY_SET; } else if + * (keyGroupEntries.size() == 0) { return Collections.EMPTY_SET; } else { + * + * Set keyEntryIDs = module.getPrivateKeyEntryIDs(); Set keySet = new + * HashSet(); Iterator iter; + * + * // filter out the keys that do not exist in the IAIK configuration // + * by walking through the key entries and checking if the exist in // the + * // keyGroupEntries for (iter = keyEntryIDs.iterator(); iter.hasNext();) + * { KeyEntryID entryID = (KeyEntryID) iter.next(); KeyGroupEntry entry = + * new KeyGroupEntry(entryID.getModuleID(), + * entryID.getCertificateIssuer(), entryID.getCertificateSerialNumber()); + * if (keyGroupEntries.contains(entry)) { keySet.add(entryID); } } return + * keySet; } } + * + * @Override + * + * @SuppressWarnings("rawtypes") public X509Certificate + * getCertificate(SignParameter parameter) throws PdfAsException { + * KeyModule module = KeyModuleFactory.getInstance(this.transactionId); + * + * Set keySet = null; try { keySet = buildKeySet(this.keyIdentifier, + * module); } catch (ConfigurationException e2) { + * Logger.warn("MOA not correctly configured!", e2); throw new + * PdfAsException("MOA not correctly configured!"); } + * + * if (keySet == null || keySet.isEmpty()) { + * Logger.warn("No keys available for Key Identifier " + + * this.keyIdentifier + " and given authentication."); throw new + * PdfAsException("Invalid Key Identifier: " + this.keyIdentifier); } + * + * if (keySet.size() != 1) { Logger.warn( + * "Too many keys available for Key Identifier " + this.keyIdentifier + + * " and given authentication."); throw new + * PdfAsException("Too many keys available for Key Identifier: " + + * this.keyIdentifier); } + * + * Iterator iter; + * + * // filter out the keys that do not exist in the IAIK configuration // + * by walking through the key entries and checking if the exist in // the + * // keyGroupEntries for (iter = keySet.iterator(); iter.hasNext();) { + * KeyEntryID entryID = (KeyEntryID) iter.next(); + * + * List certChain = null; try { certChain = + * module.getPrivateKeyEntry(entryID).getCertificateChain(); } catch + * (UnknownKeyException e1) { Logger.warn("Unknown KeyIdentifier found!", + * e1); throw new PdfAsException("Unknown Key Identifier: " + + * this.keyIdentifier); } + * + * if (certChain != null && !certChain.isEmpty()) { + * Logger.trace("Returning Certificate!"); Certificate keyCert = + * ((Certificate) certChain.get(0)); if (keyCert instanceof + * X509Certificate) { return (X509Certificate) keyCert; } else { try { + * return new X509Certificate(keyCert.getEncoded()); } catch + * (CertificateEncodingException e) { + * Logger.warn("Invalid certificate found!", e); throw new + * PdfAsException("Invalid certificate for Key Identifier: " + + * this.keyIdentifier); } catch (CertificateException e) { + * Logger.warn("Invalid certificate found!", e); throw new + * PdfAsException("Invalid certificate for Key Identifier: " + + * this.keyIdentifier); } } } + * + * break; } + * + * // No Certificate could be found! + * Logger.warn("Failed to find keys available for Key Identifier " + + * this.keyIdentifier + " and given authentication."); throw new + * PdfAsException("Failed to find keys available for Key Identifier: " + + * this.keyIdentifier); } + * + * @SuppressWarnings("unchecked") + * + * @Override public byte[] sign(byte[] input, int[] byteRange, + * SignParameter parameter, RequestedSignature requestedSignature) throws + * PdfAsException { + * + * CreateCMSSignatureRequestImpl createCMSSignatureRequest = new + * CreateCMSSignatureRequestImpl(); + * createCMSSignatureRequest.setKeyIdentifier(this.keyIdentifier); + * SingleSignatureInfoCMSImpl singleSignatureInfos = new + * SingleSignatureInfoCMSImpl(); + * + * DataObjectInfoCMSImpl dataObjectInfoCMSImpl = new + * DataObjectInfoCMSImpl(); + * + * dataObjectInfoCMSImpl.setStructure(DataObjectInfoCMSImpl. + * STRUCTURE_DETACHED); + * + * CMSDataObjectImpl cmsDataObjectImpl = new CMSDataObjectImpl(); + * + * CMSContentExplicitImpl cmsContent = new CMSContentExplicitImpl(); + * cmsContent.setBinaryContent(new ByteArrayInputStream(input)); + * + * cmsDataObjectImpl.setContent(cmsContent); + * + * MetaInfoImpl metaInfoImpl = new MetaInfoImpl(); + * + * metaInfoImpl.setMimeType("application/pdf"); + * + * cmsDataObjectImpl.setMetaInfo(metaInfoImpl); + * + * dataObjectInfoCMSImpl.setDataObject(cmsDataObjectImpl); + * + * singleSignatureInfos.setDataObjectInfo(dataObjectInfoCMSImpl); + * + * createCMSSignatureRequest.getSingleSignatureInfos().add( + * singleSignatureInfos); + * + * try { CreateCMSSignatureResponse createCMSSignatureResponse = + * CMSSignatureCreationInvoker.getInstance() + * .createCMSSignature(createCMSSignatureRequest, Collections.EMPTY_SET); + * + * if (createCMSSignatureResponse.getResponseElements().isEmpty()) { + * Logger.error("MOA CMS Signature response is empty!"); throw new + * PdfAsException("MOA CMS Signature response is empty"); } + * + * CreateCMSSignatureResponseElement createCMSSignatureResponseElement = + * (CreateCMSSignatureResponseElement) createCMSSignatureResponse + * .getResponseElements().get(0); + * + * if(createCMSSignatureResponseElement.getResponseType() == + * CreateCMSSignatureResponseElement.ERROR_RESPONSE) { ErrorResponse + * errorResponse = (ErrorResponse) createCMSSignatureResponseElement; + * Logger.error("Failed to create signature " + + * errorResponse.getErrorCode() + " " + errorResponse.getInfo()); throw + * new PdfAsErrorCarrier(new PDFASError(errorResponse.getErrorCode(), + * errorResponse.getInfo())); } else + * if(createCMSSignatureResponseElement.getResponseType() == + * CreateCMSSignatureResponseElement.CMS_SIGNATURE ) { + * CMSSignatureResponse cmsSignatureResponse = (CMSSignatureResponse) + * createCMSSignatureResponseElement; return + * Base64Utils.decode(cmsSignatureResponse.getCMSSignature(), true); } } + * catch (MOAException e) { Logger.error("Failed to create signature!", + * e); throw new PdfAsException("Failed to create signature!", e); } catch + * (IOException e) { Logger.error("Failed to create signature!", e); throw + * new PdfAsException("Failed to create signature!", e); } + * + * return null; } + */ } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/pdfas/InternalMoaVerifier.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/pdfas/InternalMoaVerifier.java index 8d5a27e..c1d18bf 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/pdfas/InternalMoaVerifier.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/pdfas/InternalMoaVerifier.java @@ -1,129 +1,101 @@ package at.gv.egovernment.moa.spss.server.pdfas; -import java.io.ByteArrayInputStream; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/*import at.gv.egiz.pdfas.common.exceptions.PdfAsException; -import at.gv.egiz.pdfas.lib.api.Configuration; -import at.gv.egiz.pdfas.lib.api.verify.SignatureCheck; -import at.gv.egiz.pdfas.lib.api.verify.VerifyParameter.SignatureVerificationLevel; -import at.gv.egiz.pdfas.lib.api.verify.VerifyResult; -import at.gv.egiz.pdfas.lib.impl.verify.IVerifier; -import at.gv.egiz.pdfas.lib.impl.verify.SignatureCheckImpl; -*/ -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; -import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureResponseElement; -import at.gv.egovernment.moa.spss.api.common.CheckResult; -import at.gv.egovernment.moa.spss.api.impl.CMSContentExplicitImpl; -import at.gv.egovernment.moa.spss.api.impl.CMSDataObjectImpl; -import at.gv.egovernment.moa.spss.api.impl.MetaInfoImpl; -import at.gv.egovernment.moa.spss.api.impl.VerifyCMSSignatureRequestImpl; -import at.gv.egovernment.moa.spss.server.invoke.CMSSignatureVerificationInvoker; -import iaik.x509.X509Certificate; - -public class InternalMoaVerifier { /*implements IVerifier { - - public static final String MOA_TRUSTPROFILE = "internal.moa.trustprofile"; - - private String trustProfile; - - private static final Logger logger = LoggerFactory.getLogger(InternalMoaVerifier.class); - - @Override - public List verify(byte[] signature, byte[] signatureContent, Date verificationTime) - throws PdfAsException { - - List verificationResultList = new ArrayList(); - - VerifyCMSSignatureRequestImpl verifyCMSSignatureRequest = new VerifyCMSSignatureRequestImpl(); - verifyCMSSignatureRequest.setDateTime(verificationTime); - verifyCMSSignatureRequest.setTrustProfileId(this.trustProfile); - verifyCMSSignatureRequest.setCMSSignature(new ByteArrayInputStream(signature)); - - CMSContentExplicitImpl cmsContentExplicitImpl = new CMSContentExplicitImpl(); - cmsContentExplicitImpl.setBinaryContent(new ByteArrayInputStream(signatureContent)); - - CMSDataObjectImpl cmsDataObjectImpl = new CMSDataObjectImpl(); - cmsDataObjectImpl.setContent(cmsContentExplicitImpl); - - MetaInfoImpl metaInfo = new MetaInfoImpl(); - metaInfo.setMimeType("application/pdf"); - metaInfo.setDescription("PDF Document"); - cmsDataObjectImpl.setMetaInfo(metaInfo); - - verifyCMSSignatureRequest.setDataObject(cmsDataObjectImpl); - - verifyCMSSignatureRequest.setSignatories(VerifyCMSSignatureRequest.ALL_SIGNATORIES); - - try { - VerifyCMSSignatureResponse verifyCMSSignatureResponse = CMSSignatureVerificationInvoker.getInstance() - .verifyCMSSignature(verifyCMSSignatureRequest); - @SuppressWarnings("rawtypes") - Iterator iter; - for (iter = verifyCMSSignatureResponse.getResponseElements().iterator(); iter.hasNext();) { - VerifyCMSSignatureResponseElement responseElement = (VerifyCMSSignatureResponseElement) iter.next(); - ExtendedVerifyResult verifyResult = new ExtendedVerifyResult(); - - verifyResult.setCertificateCheck(convertCheck(responseElement.getCertificateCheck())); - verifyResult.setValueCheckCode(convertCheck(responseElement.getSignatureCheck())); - verifyResult.setManifestCheckCode(new SignatureCheckImpl(99, null)); - verifyResult.setQualifiedCertificate(responseElement.getSignerInfo().isQualifiedCertificate()); - verifyResult.setVerificationDone(true); - - if (responseElement.getSignerInfo().getSignerCertificate() instanceof X509Certificate) { - verifyResult.setSignerCertificate( - (X509Certificate) responseElement.getSignerInfo().getSignerCertificate()); - } else { - verifyResult.setSignerCertificate( - new X509Certificate(responseElement.getSignerInfo().getSignerCertificate().getEncoded())); - } - - verifyResult.setQcSource(responseElement.getSignerInfo().getQCSource()); - - verifyResult.setPublicAuthority(responseElement.getSignerInfo().isPublicAuthority()); - verifyResult.setPublicAuthorityID(responseElement.getSignerInfo().getPublicAuhtorityID()); - verifyResult.setSSCD(responseElement.getSignerInfo().isSSCD()); - verifyResult.setSscdSource(responseElement.getSignerInfo().getSSCDSource()); - verifyResult.setIssureCountryCode(responseElement.getSignerInfo().getIssuerCountryCode()); - - verificationResultList.add(verifyResult); - } - } catch (MOAException e) { - logger.error("Failed to verify CMS Signature with MOA", e); - throw new PdfAsException("Failed to verify CMS Signature with MOA", e); - } catch (CertificateEncodingException e) { - logger.error("Failed to verify CMS Signature with MOA", e); - throw new PdfAsException("Failed to verify CMS Signature with MOA", e); - } catch (CertificateException e) { - logger.error("Failed to verify CMS Signature with MOA", e); - throw new PdfAsException("Failed to verify CMS Signature with MOA", e); - } - - return verificationResultList; - } - - private SignatureCheck convertCheck(CheckResult checkResult) { - return new SignatureCheckImpl(checkResult.getCode(), null); - } - - @Override - public void setConfiguration(Configuration config) { - this.trustProfile = config.getValue(MOA_TRUSTPROFILE); - } - - @Override - public SignatureVerificationLevel getLevel() { - return SignatureVerificationLevel.FULL_VERIFICATION; - } - */ +public class InternalMoaVerifier { /* + * implements IVerifier { + * + * public static final String MOA_TRUSTPROFILE = + * "internal.moa.trustprofile"; + * + * private String trustProfile; + * + * private static final Logger logger = + * LoggerFactory.getLogger(InternalMoaVerifier.class); + * + * @Override public List verify(byte[] signature, byte[] + * signatureContent, Date verificationTime) throws PdfAsException { + * + * List verificationResultList = new + * ArrayList(); + * + * VerifyCMSSignatureRequestImpl verifyCMSSignatureRequest = new + * VerifyCMSSignatureRequestImpl(); + * verifyCMSSignatureRequest.setDateTime(verificationTime); + * verifyCMSSignatureRequest.setTrustProfileId(this.trustProfile); + * verifyCMSSignatureRequest.setCMSSignature(new + * ByteArrayInputStream(signature)); + * + * CMSContentExplicitImpl cmsContentExplicitImpl = new + * CMSContentExplicitImpl(); cmsContentExplicitImpl.setBinaryContent(new + * ByteArrayInputStream(signatureContent)); + * + * CMSDataObjectImpl cmsDataObjectImpl = new CMSDataObjectImpl(); + * cmsDataObjectImpl.setContent(cmsContentExplicitImpl); + * + * MetaInfoImpl metaInfo = new MetaInfoImpl(); + * metaInfo.setMimeType("application/pdf"); + * metaInfo.setDescription("PDF Document"); + * cmsDataObjectImpl.setMetaInfo(metaInfo); + * + * verifyCMSSignatureRequest.setDataObject(cmsDataObjectImpl); + * + * verifyCMSSignatureRequest.setSignatories(VerifyCMSSignatureRequest. + * ALL_SIGNATORIES); + * + * try { VerifyCMSSignatureResponse verifyCMSSignatureResponse = + * CMSSignatureVerificationInvoker.getInstance() + * .verifyCMSSignature(verifyCMSSignatureRequest); + * + * @SuppressWarnings("rawtypes") Iterator iter; for (iter = + * verifyCMSSignatureResponse.getResponseElements().iterator(); + * iter.hasNext();) { VerifyCMSSignatureResponseElement responseElement = + * (VerifyCMSSignatureResponseElement) iter.next(); ExtendedVerifyResult + * verifyResult = new ExtendedVerifyResult(); + * + * verifyResult.setCertificateCheck(convertCheck(responseElement. + * getCertificateCheck())); + * verifyResult.setValueCheckCode(convertCheck(responseElement. + * getSignatureCheck())); verifyResult.setManifestCheckCode(new + * SignatureCheckImpl(99, null)); + * verifyResult.setQualifiedCertificate(responseElement.getSignerInfo(). + * isQualifiedCertificate()); verifyResult.setVerificationDone(true); + * + * if (responseElement.getSignerInfo().getSignerCertificate() instanceof + * X509Certificate) { verifyResult.setSignerCertificate( (X509Certificate) + * responseElement.getSignerInfo().getSignerCertificate()); } else { + * verifyResult.setSignerCertificate( new + * X509Certificate(responseElement.getSignerInfo().getSignerCertificate(). + * getEncoded())); } + * + * verifyResult.setQcSource(responseElement.getSignerInfo().getQCSource()); + * + * verifyResult.setPublicAuthority(responseElement.getSignerInfo(). + * isPublicAuthority()); + * verifyResult.setPublicAuthorityID(responseElement.getSignerInfo(). + * getPublicAuhtorityID()); + * verifyResult.setSSCD(responseElement.getSignerInfo().isSSCD()); + * verifyResult.setSscdSource(responseElement.getSignerInfo().getSSCDSource + * ()); verifyResult.setIssureCountryCode(responseElement.getSignerInfo(). + * getIssuerCountryCode()); + * + * verificationResultList.add(verifyResult); } } catch (MOAException e) { + * logger.error("Failed to verify CMS Signature with MOA", e); throw new + * PdfAsException("Failed to verify CMS Signature with MOA", e); } catch + * (CertificateEncodingException e) { + * logger.error("Failed to verify CMS Signature with MOA", e); throw new + * PdfAsException("Failed to verify CMS Signature with MOA", e); } catch + * (CertificateException e) { + * logger.error("Failed to verify CMS Signature with MOA", e); throw new + * PdfAsException("Failed to verify CMS Signature with MOA", e); } + * + * return verificationResultList; } + * + * private SignatureCheck convertCheck(CheckResult checkResult) { return + * new SignatureCheckImpl(checkResult.getCode(), null); } + * + * @Override public void setConfiguration(Configuration config) { + * this.trustProfile = config.getValue(MOA_TRUSTPROFILE); } + * + * @Override public SignatureVerificationLevel getLevel() { return + * SignatureVerificationLevel.FULL_VERIFICATION; } + */ } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/AxisHandler.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/AxisHandler.java index 4ee4e07..804c7ad 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/AxisHandler.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/AxisHandler.java @@ -35,9 +35,7 @@ import java.util.Iterator; import javax.servlet.http.HttpServletRequest; -import org.apache.axis.AxisEngine; import org.apache.axis.AxisFault; -import org.apache.axis.AxisProperties; import org.apache.axis.Message; import org.apache.axis.MessageContext; import org.apache.axis.attachments.AttachmentPart; @@ -49,7 +47,6 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; import at.gv.egovernment.moa.spss.MOASystemException; import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; @@ -66,447 +63,434 @@ import at.gv.egovernment.moaspss.util.DOMUtils; /** * An handler that is invoked on each web service request and performs some * central message handling. - * + * * Mainly sets up the TransactionContext for the current * transaction (i.e. web service request). - * + * * @author Patrick Peck * @author Stefan Knirsch * @version $Id$ */ public class AxisHandler extends BasicHandler { - /** - * - */ - private static final long serialVersionUID = 2520698947819506866L; - - /** The resource names of the messages to load. */ - private static final String MOA_SPSS_WSDL_RESOURCE_ = "/resources/wsdl/MOA-SPSS-2.0.0.wsdl"; - - /** The property name for accessing the HTTP request. */ - private static final String REQUEST_PROPERTY = HTTPConstants.MC_HTTP_SERVLETREQUEST; - - /** The property name for accessing the X509 client certificate chain. */ - private static final String X509_CERTIFICATE_PROPERTY = "javax.servlet.request.X509Certificate"; - - /** The property name for accessing the SOAP action header. */ - private static final String SOAP_ACTION_HEADER = "soapaction"; - - /** URI of the SOAP XML namespace. */ - public static final String SOAP_NS_URI = "http://schemas.xmlsoap.org/soap/envelope/"; - - /** Prefix used for the SOAP XML namespace */ - public static final String SOAP_PREFIX = "soapenv"; - - /** Simple string contains the front part of the enveloping SOAP wrapping */ - private static final String SOAP_PART_PRE = ""; - - /** Simple string contains the post part of the enveloping SOAP wrapping */ - private static final String SOAP_PART_POST = ""; - - /** - * Handle an invocation of this handler. - * - * @param msgContext - * Information about this request/response. - * @throws AxisFault - * An error occurred during processing of the request. - * @see org.apache.axis.Handler#invoke(MessageContext) - */ - public void invoke(MessageContext msgContext) throws AxisFault { - if (!msgContext.getPastPivot()) { - handleRequest(msgContext); - } else { - handleResponse(msgContext); - } - } - - /** - * This method is called by invoke to handle incoming requests. - * - * @param msgContext - * The context as provided to invoke. - * @throws AxisFault - * An error occurred during processing of the request. - */ - private void handleRequest(MessageContext msgContext) throws AxisFault { - Message soapMessage = null; - try { - Logger.trace("---- Entering Axishandler"); - // generate a unique transaction id and build the TransactionContext - // for this request - HttpServletRequest request = (HttpServletRequest) msgContext.getProperty(REQUEST_PROPERTY); - - X509Certificate[] clientCert = (X509Certificate[]) request.getAttribute(X509_CERTIFICATE_PROPERTY); - - if (Logger.isTraceEnabled()) { - Enumeration allHeaders = request.getHeaderNames(); - if (allHeaders != null) { - while(allHeaders.hasMoreElements()) { - String header = allHeaders.nextElement(); - Logger.trace("Header: " + header + " : " + request.getHeader(header)); - - } - } - } - - // Configure Axis - // AxisProperties.setProperty(AxisEngine.PROP_ENABLE_NAMESPACE_PREFIX_OPTIMIZATION,"false"); - // AxisProperties.setProperty(AxisEngine.PROP_DOMULTIREFS,"false"); - // AxisProperties.setProperty(AxisEngine.PROP_SEND_XSI,"true"); - // msgContext.setProperty(org.apache.axis.SOAPPart.ALLOW_FORM_OPTIMIZATION, - // Boolean.FALSE); - // msgContext.setProperty(org.apache.axis. - // AxisEngine.PROP_ENABLE_NAMESPACE_PREFIX_OPTIMIZATION,"false"); - //AxisProperties.setProperty(AxisEngine.PROP_ATTACHMENT_IMPLEMENTATION, AxisEngine.DEFAULT_ATTACHMENT_IMPL); - soapMessage = msgContext.getCurrentMessage(); - - ConfigurationProvider configuration = ConfigurationProvider.getInstance(); - new String(soapMessage.getSOAPPartAsBytes()); - Element xmlRequest = null; - // log.info(soapMessage.getSOAPPartAsString()); - Element soapPart = DOMUtils - .parseDocument(new ByteArrayInputStream(soapMessage.getSOAPPartAsBytes()), false, null, null) - .getDocumentElement(); - if (soapPart != null) { - // TODO: check if DOM Version is intolerant when white spaces - // are between tags (preceding normalization would be necessary) - NodeList soapBodies = soapPart.getElementsByTagNameNS(SOAP_NS_URI, "Body"); - if (soapBodies != null && soapBodies.getLength() > 0) { - xmlRequest = DOMUtils.getElementFromNodeList(soapBodies.item(0).getChildNodes()); - } - // oder TODO: Evaluierung ob XPATH schneller - /* - * HashMap nSMap = new HashMap(); nSMap.put((String)SOAP_PREFIX, - * SOAP_NS_URI); Element soapBody = (Element) - * XPathUtils.selectSingleNode(soapPart, nSMap, - * "/"+SOAP_PREFIX+":Envelope/"+SOAP_PREFIX+":Body"); if - * (soapBody!=null) { xmlRequest = - * DOMUtils.getElementFromNodeList(soapBody.getChildNodes()); } - */ - } - - TransactionContext context = new TransactionContext(TransactionIDGenerator.nextID(), clientCert, - configuration, xmlRequest, null); - - String soapAction = (String) request.getHeader(SOAP_ACTION_HEADER); - if ("\"\"".equals(soapAction)) { - // if http soap action header is empty - soapAction = msgContext.getTargetService(); - } - context.setRequestName(soapAction); - - if (soapMessage.getAttachmentsImpl() != null) { - Logger.info("Attachments is NOT null!"); - Logger.trace(">>> Get AttachmentCount"); - int attachmentCount = soapMessage.getAttachmentsImpl().getAttachmentCount(); - Logger.trace("<<< Finished Get AttachmentCount"); - if (attachmentCount > 0) { - - // add SOAP attachments to transaction context - @SuppressWarnings("rawtypes") - Iterator iterator = soapMessage.getAttachments(); - while (iterator.hasNext()) { - AttachmentPart attachment = (AttachmentPart) iterator.next(); - String id = attachment.getContentId(); - String type = attachment.getContentType(); - - // Now get the InputStream (note: we could also get the - // content with Object content = - // attachment.getContent();) - InputStream is = null; - javax.activation.DataHandler datahandler = attachment.getDataHandler(); - - int TYPE = 2; - switch (TYPE) { - case 1: { - org.apache.axis.attachments.ManagedMemoryDataSource mmds = (org.apache.axis.attachments.ManagedMemoryDataSource) datahandler - .getDataSource(); - context.addAttachment(id, type, mmds); - break; - } - case 2: { - is = datahandler.getDataSource().getInputStream(); - context.addAttachment(id, type, is, datahandler.getDataSource().getName()); - break; - } - } - debug("handler.06", new Object[] { id, type }); - } - } - } else { - Logger.info("Attachments is null!"); - } - - setUpContexts(context); - - // log some information about the request - info("handler.00", new Object[] { context.getTransactionID(), msgContext.getTargetService() }); - info("handler.01", new Object[] { request.getRemoteAddr() }); - if (clientCert != null) { - info("handler.02", new Object[] { clientCert[0].getSubjectDN(), clientCert[0].getSerialNumber(), - clientCert[0].getIssuerDN() }); - - } else { - info("handler.03", null); - } - if (Logger.isTraceEnabled()) { - // OutputFormat format = new OutputFormat((Document) - // xmlRequest.getOwnerDocument()); - // format.setLineSeparator("\n"); - // format.setIndenting(false); - // format.setPreserveSpace(true); - // format.setOmitXMLDeclaration(false); - // format.setEncoding("UTF-8"); - // ByteArrayOutputStream baos = new ByteArrayOutputStream(); - // XMLSerializer conSerializer = new XMLSerializer(baos, - // format); - // conSerializer.serialize(xmlRequest); - // Logger.debug(new LogMsg("Request:" + baos.toString())); - - String msg = soapMessage.getSOAPPartAsString(); - Logger.trace(new LogMsg(msg)); - } - } catch (MOASystemException e) { - MOASystemException se = new MOASystemException("2900", null, e); - AxisFault fault = AxisFault.makeFault(se); - fault.setFaultDetail(new Element[] { se.toErrorResponse() }); - throw fault; - - } catch (SAXException t ) { - if (soapMessage != null && soapMessage.getSOAPPartAsBytes() != null) { - try { - Logger.debug("Req: " + new String(soapMessage.getSOAPPartAsBytes(), "UTF-8")); - } catch (UnsupportedEncodingException e1) { - e1.printStackTrace(); - } - - } - - t.printStackTrace(); - Logger.info(new LogMsg(t.getStackTrace())); - MOASystemException e = new MOASystemException("2900", null, t); - AxisFault fault = AxisFault.makeFault(e); - fault.setFaultDetail(new Element[] { e.toErrorResponse() }); - throw fault; - - } catch (Throwable t) { - t.printStackTrace(); - Logger.info(new LogMsg(t.getStackTrace())); - MOASystemException e = new MOASystemException("2900", null, t); - AxisFault fault = AxisFault.makeFault(e); - fault.setFaultDetail(new Element[] { e.toErrorResponse() }); - throw fault; - } - Logger.trace("---- Leaving Axishandler"); - } - - /** - * This method is called by invoke to handle outgoing - * responses. - * - * @param msgContext - * The context as provided to invoke. - * @throws AxisFault - * An error occurred during processing of the response. - */ - private void handleResponse(MessageContext msgContext) throws AxisFault { - String xmlResponseString = null; - String soapResponseString = null; - - TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); - Element xmlResponse = context.getResponse(); - - if (xmlResponse != null) { - try { - xmlResponseString = DOMUtils.serializeNode(xmlResponse, true); - /* - * Soll die Antwort nur \n enthalten, so gibt es 2 - * Möglichkeiten: 1.) Xalan Version und xmlResponseString = - * DOMUtils.serializeNode(xmlResponse, true, "\n"); 2.) - * OutputFormat serializerFormat = new OutputFormat((Document) - * xmlResponse.getOwnerDocument()); - * serializerFormat.setLineSeparator("\n"); - * serializerFormat.setIndenting(false); - * serializerFormat.setPreserveSpace(true); - * serializerFormat.setOmitXMLDeclaration(true); - * serializerFormat.setEncoding("UTF-8"); ByteArrayOutputStream - * serializedBytes = new ByteArrayOutputStream(); XMLSerializer - * serializer = new XMLSerializer(serializedBytes, - * serializerFormat); serializer.serialize(xmlResponse); - * serializedBytes.close(); xmlResponseString = - * serializedBytes.toString("UTF-8"); - */ - if (Logger.isTraceEnabled()) { - Logger.trace(new LogMsg(xmlResponseString)); - } - soapResponseString = SOAP_PART_PRE + xmlResponseString + SOAP_PART_POST; - // override axis response-message - msgContext.setResponseMessage(new Message(soapResponseString)); - } catch (Throwable t) { - t.printStackTrace(); - Logger.info(new LogMsg(t.getStackTrace())); - MOASystemException e = new MOASystemException("2900", null, t); - AxisFault fault = AxisFault.makeFault(e); - fault.setFaultDetail(new Element[] { e.toErrorResponse() }); - throw fault; - } - - } else { - // Fallback: if functions do not set the resulting response in the - // transaction, the original one from axis will be used - soapResponseString = msgContext.getCurrentMessage().getSOAPPartAsString(); - } - - info("handler.04", null); - if (Logger.isDebugEnabled()) { - Logger.debug(new LogMsg(soapResponseString)); - } - tearDownContexts(); - } - - /** - * Called, when the processing of the web service fails. - * - * @param msgContext - * Information about the current request. - * @see org.apache.axis.Handler#onFault(org.apache.axis.MessageContext) - */ - public void onFault(MessageContext msgContext) { - info("handler.05", null); - tearDownContexts(); - } - - /** - * Set up the thread-local contexts (TransactionContext and - * LoggingContext). - * - * @param context - * The TransactionContext to set for the current - * request. - */ - private void setUpContexts(TransactionContext context) { - // set the transaction context in the TransactionContextManager - TransactionContextManager tcm = TransactionContextManager.getInstance(); - tcm.setTransactionContext(context); - - // set the logging context in the LoggingContextManager - LoggingContextManager lcm = LoggingContextManager.getInstance(); - LoggingContext lc = new LoggingContext(context.getTransactionID()); - lcm.setLoggingContext(lc); - } - - /** - * Tear down the thread-local contexts. - */ - private void tearDownContexts() { - TransactionContextManager tcm = TransactionContextManager.getInstance(); - - // delete temporary files - TransactionContext context = tcm.getTransactionContext(); - context.cleanAttachmentCache(); - - // unset the transaction context - tcm.setTransactionContext(null); - - // unset the logging context - LoggingContextManager lcm = LoggingContextManager.getInstance(); - lcm.setLoggingContext(null); - } - - /** - * Generate the WSDL into the msgContext. - * - * The code of this method is more or less copied from the - * org.apache.axis.handlers.soap.SOAPService class contained in - * the 1.1 release of Axis to allow for a missing wsdlFile (so - * that a resource by the same name is searched for in the classpath). The - * implementation of this method should be obsolete if Axis 1.1 or higher is - * used. - * - * @param msgContext - * The MessageContext that will contain the WSDL - * description of the current web service. - * @throws AxisFault - * An error occurred producing the WSDL. - */ - public void generateWSDL(MessageContext msgContext) throws AxisFault { - InputStream instream = null; - - try { - String filename = MOA_SPSS_WSDL_RESOURCE_; - - File file = new File(filename); - if (file.exists()) { - // if this resolves to a file, load it - instream = new FileInputStream(filename); - } else { - // else load a named resource in our classloader. - instream = this.getClass().getResourceAsStream(filename); - if (instream == null) { - String errorText = Messages.getMessage("wsdlFileMissing", filename); - throw new AxisFault(errorText); - } - } - Document doc = XMLUtils.newDocument(instream); - msgContext.setProperty("WSDL", doc); - } catch (Exception e) { - throw AxisFault.makeFault(e); - } finally { - if (instream != null) { - try { - instream.close(); - } catch (IOException e) { - // ok to do nothing here - } - } - } - } - - /** - * Utility function to issue an info message to the log. - * - * @param messageId - * The ID of the message to log. - * @param parameters - * Additional message parameters. - */ - private static void info(String messageId, Object[] parameters) { - MessageProvider msg = MessageProvider.getInstance(); - - Logger.info(new LogMsg(msg.getMessage(messageId, parameters))); - } - - /** - * Utility function to issue an debug message to the log. - * - * @param messageId - * The ID of the message to log. - * @param parameters - * Additional message parameters. - */ - private static void debug(String messageId, Object[] parameters) { - MessageProvider msg = MessageProvider.getInstance(); - - Logger.debug(new LogMsg(msg.getMessage(messageId, parameters))); - } - - // private byte[] toByteArray(AttachmentPart attachment) throws - // SOAPException, IOException - // { - // ByteArrayOutputStream outputStream = new - // ByteArrayOutputStream(attachment.getSize()); - // InputStream inputStream = (InputStream) attachment.getContent(); - // int currentByte = -1; - // while ((currentByte = inputStream.read()) != -1) - // outputStream.write(currentByte); - // - // inputStream.close(); - // outputStream.close(); - // - // return outputStream.toByteArray(); - // - // } + /** + * + */ + private static final long serialVersionUID = 2520698947819506866L; + + /** The resource names of the messages to load. */ + private static final String MOA_SPSS_WSDL_RESOURCE_ = "/resources/wsdl/MOA-SPSS-2.0.0.wsdl"; + + /** The property name for accessing the HTTP request. */ + private static final String REQUEST_PROPERTY = HTTPConstants.MC_HTTP_SERVLETREQUEST; + + /** The property name for accessing the X509 client certificate chain. */ + private static final String X509_CERTIFICATE_PROPERTY = "javax.servlet.request.X509Certificate"; + + /** The property name for accessing the SOAP action header. */ + private static final String SOAP_ACTION_HEADER = "soapaction"; + + /** URI of the SOAP XML namespace. */ + public static final String SOAP_NS_URI = "http://schemas.xmlsoap.org/soap/envelope/"; + + /** Prefix used for the SOAP XML namespace */ + public static final String SOAP_PREFIX = "soapenv"; + + /** Simple string contains the front part of the enveloping SOAP wrapping */ + private static final String SOAP_PART_PRE = + ""; + + /** Simple string contains the post part of the enveloping SOAP wrapping */ + private static final String SOAP_PART_POST = ""; + + /** + * Handle an invocation of this handler. + * + * @param msgContext Information about this request/response. + * @throws AxisFault An error occurred during processing of the request. + * @see org.apache.axis.Handler#invoke(MessageContext) + */ + @Override + public void invoke(MessageContext msgContext) throws AxisFault { + if (!msgContext.getPastPivot()) { + handleRequest(msgContext); + } else { + handleResponse(msgContext); + } + } + + /** + * This method is called by invoke to handle incoming requests. + * + * @param msgContext The context as provided to invoke. + * @throws AxisFault An error occurred during processing of the request. + */ + private void handleRequest(MessageContext msgContext) throws AxisFault { + Message soapMessage = null; + try { + Logger.trace("---- Entering Axishandler"); + // generate a unique transaction id and build the TransactionContext + // for this request + final HttpServletRequest request = (HttpServletRequest) msgContext.getProperty(REQUEST_PROPERTY); + + final X509Certificate[] clientCert = (X509Certificate[]) request.getAttribute( + X509_CERTIFICATE_PROPERTY); + + if (Logger.isTraceEnabled()) { + final Enumeration allHeaders = request.getHeaderNames(); + if (allHeaders != null) { + while (allHeaders.hasMoreElements()) { + final String header = allHeaders.nextElement(); + Logger.trace("Header: " + header + " : " + request.getHeader(header)); + + } + } + } + + // Configure Axis + // AxisProperties.setProperty(AxisEngine.PROP_ENABLE_NAMESPACE_PREFIX_OPTIMIZATION,"false"); + // AxisProperties.setProperty(AxisEngine.PROP_DOMULTIREFS,"false"); + // AxisProperties.setProperty(AxisEngine.PROP_SEND_XSI,"true"); + // msgContext.setProperty(org.apache.axis.SOAPPart.ALLOW_FORM_OPTIMIZATION, + // Boolean.FALSE); + // msgContext.setProperty(org.apache.axis. + // AxisEngine.PROP_ENABLE_NAMESPACE_PREFIX_OPTIMIZATION,"false"); + // AxisProperties.setProperty(AxisEngine.PROP_ATTACHMENT_IMPLEMENTATION, + // AxisEngine.DEFAULT_ATTACHMENT_IMPL); + soapMessage = msgContext.getCurrentMessage(); + + final ConfigurationProvider configuration = ConfigurationProvider.getInstance(); + new String(soapMessage.getSOAPPartAsBytes()); + Element xmlRequest = null; + // log.info(soapMessage.getSOAPPartAsString()); + final Element soapPart = DOMUtils + .parseDocument(new ByteArrayInputStream(soapMessage.getSOAPPartAsBytes()), false, null, null) + .getDocumentElement(); + if (soapPart != null) { + // TODO: check if DOM Version is intolerant when white spaces + // are between tags (preceding normalization would be necessary) + final NodeList soapBodies = soapPart.getElementsByTagNameNS(SOAP_NS_URI, "Body"); + if (soapBodies != null && soapBodies.getLength() > 0) { + xmlRequest = DOMUtils.getElementFromNodeList(soapBodies.item(0).getChildNodes()); + } + // oder TODO: Evaluierung ob XPATH schneller + /* + * HashMap nSMap = new HashMap(); nSMap.put((String)SOAP_PREFIX, SOAP_NS_URI); + * Element soapBody = (Element) XPathUtils.selectSingleNode(soapPart, nSMap, + * "/"+SOAP_PREFIX+":Envelope/"+SOAP_PREFIX+":Body"); if (soapBody!=null) { + * xmlRequest = DOMUtils.getElementFromNodeList(soapBody.getChildNodes()); } + */ + } + + final TransactionContext context = new TransactionContext(TransactionIDGenerator.nextID(), clientCert, + configuration, xmlRequest, null); + + String soapAction = request.getHeader(SOAP_ACTION_HEADER); + if ("\"\"".equals(soapAction)) { + // if http soap action header is empty + soapAction = msgContext.getTargetService(); + } + context.setRequestName(soapAction); + + if (soapMessage.getAttachmentsImpl() != null) { + Logger.info("Attachments is NOT null!"); + Logger.trace(">>> Get AttachmentCount"); + final int attachmentCount = soapMessage.getAttachmentsImpl().getAttachmentCount(); + Logger.trace("<<< Finished Get AttachmentCount"); + if (attachmentCount > 0) { + + // add SOAP attachments to transaction context + @SuppressWarnings("rawtypes") + final Iterator iterator = soapMessage.getAttachments(); + while (iterator.hasNext()) { + final AttachmentPart attachment = (AttachmentPart) iterator.next(); + final String id = attachment.getContentId(); + final String type = attachment.getContentType(); + + // Now get the InputStream (note: we could also get the + // content with Object content = + // attachment.getContent();) + InputStream is = null; + final javax.activation.DataHandler datahandler = attachment.getDataHandler(); + + final int TYPE = 2; + switch (TYPE) { + case 1: { + final org.apache.axis.attachments.ManagedMemoryDataSource mmds = + (org.apache.axis.attachments.ManagedMemoryDataSource) datahandler + .getDataSource(); + context.addAttachment(id, type, mmds); + break; + } + case 2: { + is = datahandler.getDataSource().getInputStream(); + context.addAttachment(id, type, is, datahandler.getDataSource().getName()); + break; + } + } + debug("handler.06", new Object[] { id, type }); + } + } + } else { + Logger.info("Attachments is null!"); + } + + setUpContexts(context); + + // log some information about the request + info("handler.00", new Object[] { context.getTransactionID(), msgContext.getTargetService() }); + info("handler.01", new Object[] { request.getRemoteAddr() }); + if (clientCert != null) { + info("handler.02", new Object[] { clientCert[0].getSubjectDN(), clientCert[0].getSerialNumber(), + clientCert[0].getIssuerDN() }); + + } else { + info("handler.03", null); + } + if (Logger.isTraceEnabled()) { + // OutputFormat format = new OutputFormat((Document) + // xmlRequest.getOwnerDocument()); + // format.setLineSeparator("\n"); + // format.setIndenting(false); + // format.setPreserveSpace(true); + // format.setOmitXMLDeclaration(false); + // format.setEncoding("UTF-8"); + // ByteArrayOutputStream baos = new ByteArrayOutputStream(); + // XMLSerializer conSerializer = new XMLSerializer(baos, + // format); + // conSerializer.serialize(xmlRequest); + // Logger.debug(new LogMsg("Request:" + baos.toString())); + + final String msg = soapMessage.getSOAPPartAsString(); + Logger.trace(new LogMsg(msg)); + } + } catch (final MOASystemException e) { + final MOASystemException se = new MOASystemException("2900", null, e); + final AxisFault fault = AxisFault.makeFault(se); + fault.setFaultDetail(new Element[] { se.toErrorResponse() }); + throw fault; + + } catch (final SAXException t) { + if (soapMessage != null && soapMessage.getSOAPPartAsBytes() != null) { + try { + Logger.debug("Req: " + new String(soapMessage.getSOAPPartAsBytes(), "UTF-8")); + } catch (final UnsupportedEncodingException e1) { + e1.printStackTrace(); + } + + } + + t.printStackTrace(); + Logger.info(new LogMsg(t.getStackTrace())); + final MOASystemException e = new MOASystemException("2900", null, t); + final AxisFault fault = AxisFault.makeFault(e); + fault.setFaultDetail(new Element[] { e.toErrorResponse() }); + throw fault; + + } catch (final Throwable t) { + t.printStackTrace(); + Logger.info(new LogMsg(t.getStackTrace())); + final MOASystemException e = new MOASystemException("2900", null, t); + final AxisFault fault = AxisFault.makeFault(e); + fault.setFaultDetail(new Element[] { e.toErrorResponse() }); + throw fault; + } + Logger.trace("---- Leaving Axishandler"); + } + + /** + * This method is called by invoke to handle outgoing responses. + * + * @param msgContext The context as provided to invoke. + * @throws AxisFault An error occurred during processing of the response. + */ + private void handleResponse(MessageContext msgContext) throws AxisFault { + String xmlResponseString = null; + String soapResponseString = null; + + final TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); + final Element xmlResponse = context.getResponse(); + + if (xmlResponse != null) { + try { + xmlResponseString = DOMUtils.serializeNode(xmlResponse, true); + /* + * Soll die Antwort nur \n enthalten, so gibt es 2 Möglichkeiten: 1.) Xalan + * Version und xmlResponseString = DOMUtils.serializeNode(xmlResponse, true, + * "\n"); 2.) OutputFormat serializerFormat = new OutputFormat((Document) + * xmlResponse.getOwnerDocument()); serializerFormat.setLineSeparator("\n"); + * serializerFormat.setIndenting(false); + * serializerFormat.setPreserveSpace(true); + * serializerFormat.setOmitXMLDeclaration(true); + * serializerFormat.setEncoding("UTF-8"); ByteArrayOutputStream serializedBytes + * = new ByteArrayOutputStream(); XMLSerializer serializer = new + * XMLSerializer(serializedBytes, serializerFormat); + * serializer.serialize(xmlResponse); serializedBytes.close(); xmlResponseString + * = serializedBytes.toString("UTF-8"); + */ + if (Logger.isTraceEnabled()) { + Logger.trace(new LogMsg(xmlResponseString)); + } + soapResponseString = SOAP_PART_PRE + xmlResponseString + SOAP_PART_POST; + // override axis response-message + msgContext.setResponseMessage(new Message(soapResponseString)); + } catch (final Throwable t) { + t.printStackTrace(); + Logger.info(new LogMsg(t.getStackTrace())); + final MOASystemException e = new MOASystemException("2900", null, t); + final AxisFault fault = AxisFault.makeFault(e); + fault.setFaultDetail(new Element[] { e.toErrorResponse() }); + throw fault; + } + + } else { + // Fallback: if functions do not set the resulting response in the + // transaction, the original one from axis will be used + soapResponseString = msgContext.getCurrentMessage().getSOAPPartAsString(); + } + + info("handler.04", null); + if (Logger.isDebugEnabled()) { + Logger.debug(new LogMsg(soapResponseString)); + } + tearDownContexts(); + } + + /** + * Called, when the processing of the web service fails. + * + * @param msgContext Information about the current request. + * @see org.apache.axis.Handler#onFault(org.apache.axis.MessageContext) + */ + @Override + public void onFault(MessageContext msgContext) { + info("handler.05", null); + tearDownContexts(); + } + + /** + * Set up the thread-local contexts (TransactionContext and + * LoggingContext). + * + * @param context The TransactionContext to set for the current + * request. + */ + private void setUpContexts(TransactionContext context) { + // set the transaction context in the TransactionContextManager + final TransactionContextManager tcm = TransactionContextManager.getInstance(); + tcm.setTransactionContext(context); + + // set the logging context in the LoggingContextManager + final LoggingContextManager lcm = LoggingContextManager.getInstance(); + final LoggingContext lc = new LoggingContext(context.getTransactionID()); + lcm.setLoggingContext(lc); + } + + /** + * Tear down the thread-local contexts. + */ + private void tearDownContexts() { + final TransactionContextManager tcm = TransactionContextManager.getInstance(); + + // delete temporary files + final TransactionContext context = tcm.getTransactionContext(); + context.cleanAttachmentCache(); + + // unset the transaction context + tcm.setTransactionContext(null); + + // unset the logging context + final LoggingContextManager lcm = LoggingContextManager.getInstance(); + lcm.setLoggingContext(null); + } + + /** + * Generate the WSDL into the msgContext. + * + * The code of this method is more or less copied from the + * org.apache.axis.handlers.soap.SOAPService class contained in the + * 1.1 release of Axis to allow for a missing wsdlFile (so that a + * resource by the same name is searched for in the classpath). The + * implementation of this method should be obsolete if Axis 1.1 or higher is + * used. + * + * @param msgContext The MessageContext that will contain the WSDL + * description of the current web service. + * @throws AxisFault An error occurred producing the WSDL. + */ + @Override + public void generateWSDL(MessageContext msgContext) throws AxisFault { + InputStream instream = null; + + try { + final String filename = MOA_SPSS_WSDL_RESOURCE_; + + final File file = new File(filename); + if (file.exists()) { + // if this resolves to a file, load it + instream = new FileInputStream(filename); + } else { + // else load a named resource in our classloader. + instream = this.getClass().getResourceAsStream(filename); + if (instream == null) { + final String errorText = Messages.getMessage("wsdlFileMissing", filename); + throw new AxisFault(errorText); + } + } + final Document doc = XMLUtils.newDocument(instream); + msgContext.setProperty("WSDL", doc); + } catch (final Exception e) { + throw AxisFault.makeFault(e); + } finally { + if (instream != null) { + try { + instream.close(); + } catch (final IOException e) { + // ok to do nothing here + } + } + } + } + + /** + * Utility function to issue an info message to the log. + * + * @param messageId The ID of the message to log. + * @param parameters Additional message parameters. + */ + private static void info(String messageId, Object[] parameters) { + final MessageProvider msg = MessageProvider.getInstance(); + + Logger.info(new LogMsg(msg.getMessage(messageId, parameters))); + } + + /** + * Utility function to issue an debug message to the log. + * + * @param messageId The ID of the message to log. + * @param parameters Additional message parameters. + */ + private static void debug(String messageId, Object[] parameters) { + final MessageProvider msg = MessageProvider.getInstance(); + + Logger.debug(new LogMsg(msg.getMessage(messageId, parameters))); + } + + // private byte[] toByteArray(AttachmentPart attachment) throws + // SOAPException, IOException + // { + // ByteArrayOutputStream outputStream = new + // ByteArrayOutputStream(attachment.getSize()); + // InputStream inputStream = (InputStream) attachment.getContent(); + // int currentByte = -1; + // while ((currentByte = inputStream.read()) != -1) + // outputStream.write(currentByte); + // + // inputStream.close(); + // outputStream.close(); + // + // return outputStream.toByteArray(); + // + // } } \ No newline at end of file diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/CertificateProviderServlet.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/CertificateProviderServlet.java index 43804a2..bc2c3b6 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/CertificateProviderServlet.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/CertificateProviderServlet.java @@ -1,9 +1,5 @@ package at.gv.egovernment.moa.spss.server.service; -import iaik.server.modules.keys.KeyEntryID; -import iaik.server.modules.keys.KeyModule; -import iaik.server.modules.keys.KeyModuleFactory; - import java.io.IOException; import java.math.BigInteger; import java.security.Principal; @@ -26,155 +22,158 @@ import at.gv.egovernment.moa.spss.server.config.KeyGroupEntry; import at.gv.egovernment.moa.spss.server.logging.TransactionId; import at.gv.egovernment.moa.spss.server.transaction.TransactionIDGenerator; import at.gv.egovernment.moaspss.logging.Logger; +import iaik.server.modules.keys.KeyEntryID; +import iaik.server.modules.keys.KeyModule; +import iaik.server.modules.keys.KeyModuleFactory; /** - * + * * @author Andreas Fitzek * @version $Id$ */ public class CertificateProviderServlet extends HttpServlet { - /** - * - */ - private static final long serialVersionUID = -6907582473072190122L; - - /** The property name for accessing the X509 client certificate chain. */ - private static final String X509_CERTIFICATE_PROPERTY = "javax.servlet.request.X509Certificate"; - - public static final String PARAM_KEYID = "id"; - - /** - * Build the set of KeyEntryIDs available to the given - * keyGroupID. - * - * @param keyGroupID - * The keygroup ID for which the available keys should be - * returned. - * @return The Set of KeyEntryIDs identifying the - * available keys. - * @throws ConfigurationException - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - private Set buildKeySet(String keyGroupID, X509Certificate cert, KeyModule module) - throws ConfigurationException { - ConfigurationProvider config = ConfigurationProvider.getInstance(); - Set keyGroupEntries; - - // get the KeyGroup entries from the configuration - if (cert != null) { - Principal issuer = cert.getIssuerDN(); - BigInteger serialNumber = cert.getSerialNumber(); - - keyGroupEntries = config.getKeyGroupEntries(issuer, serialNumber, - keyGroupID); - } else { - keyGroupEntries = config.getKeyGroupEntries(null, null, keyGroupID); - } - - // map the KeyGroup entries to a set of KeyEntryIDs - if (keyGroupEntries == null) { - return null; - } else if (keyGroupEntries.size() == 0) { - return Collections.EMPTY_SET; - } else { - - Set keyEntryIDs = module.getPrivateKeyEntryIDs(); - Set keySet = new HashSet(); - Iterator iter; - - // filter out the keys that do not exist in the IAIK configuration - // by walking through the key entries and checking if the exist in - // the - // keyGroupEntries - for (iter = keyEntryIDs.iterator(); iter.hasNext();) { - KeyEntryID entryID = (KeyEntryID) iter.next(); - KeyGroupEntry entry = new KeyGroupEntry(entryID.getModuleID(), - entryID.getCertificateIssuer(), - entryID.getCertificateSerialNumber()); - if (keyGroupEntries.contains(entry)) { - keySet.add(entryID); - } - } - return keySet; - } - } - - private X509Certificate getClientCertificate(HttpServletRequest request) { - X509Certificate[] clientCert = (X509Certificate[]) request - .getAttribute(X509_CERTIFICATE_PROPERTY); - if(clientCert != null) { - return clientCert[0]; - } - return null; - } - - @SuppressWarnings("rawtypes") - public void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - try { - X509Certificate cert = getClientCertificate(request); - String keyId = request.getParameter(PARAM_KEYID); - - if(keyId == null) { - Logger.warn(PARAM_KEYID + " not provided in Request. Returning: " + HttpServletResponse.SC_BAD_REQUEST); - response.sendError(HttpServletResponse.SC_BAD_REQUEST); - return; - } - - String transactionId = TransactionIDGenerator.nextID(); - - KeyModule module = KeyModuleFactory.getInstance(new TransactionId( - transactionId)); - - Set keySet = buildKeySet(keyId, cert, module); - - if(keySet == null || keySet.isEmpty()) { - Logger.warn("No keys available for Key Identifier " + keyId + " and given authentication."); - response.sendError(HttpServletResponse.SC_NOT_FOUND); - return; - } - - - if(keySet.size() != 1) { - Logger.warn("Too many keys available for Key Identifier " + keyId + " and given authentication."); - response.sendError(HttpServletResponse.SC_CONFLICT); - return; - } - - Iterator iter; - - // filter out the keys that do not exist in the IAIK configuration - // by walking through the key entries and checking if the exist in - // the - // keyGroupEntries - for (iter = keySet.iterator(); iter.hasNext();) { - KeyEntryID entryID = (KeyEntryID) iter.next(); - - List certChain = module.getPrivateKeyEntry(entryID).getCertificateChain(); - - if(certChain != null && !certChain.isEmpty()) { - Logger.trace("Returning Certificate!"); - Certificate keyCert = ((Certificate)certChain.get(0)); - byte[] certData = keyCert.getEncoded(); - response.setStatus(HttpServletResponse.SC_OK); - response.setContentType("application/pkix-cert"); - response.setHeader("Content-disposition","attachment; filename=\"" + keyId + ".cer\""); - response.getOutputStream().write(certData); - response.getOutputStream().close(); - return; - } - - break; - } - - // No Certificate could be found! - Logger.warn("Failed to find keys available for Key Identifier " + keyId + " and given authentication."); - response.sendError(HttpServletResponse.SC_NOT_FOUND); - return; - } catch(Throwable e) { - Logger.error("Unhandled Exception when providing certificate", e); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } - } + /** + * + */ + private static final long serialVersionUID = -6907582473072190122L; + + /** The property name for accessing the X509 client certificate chain. */ + private static final String X509_CERTIFICATE_PROPERTY = "javax.servlet.request.X509Certificate"; + + public static final String PARAM_KEYID = "id"; + + /** + * Build the set of KeyEntryIDs available to the given + * keyGroupID. + * + * @param keyGroupID The keygroup ID for which the available keys should be + * returned. + * @return The Set of KeyEntryIDs identifying the + * available keys. + * @throws ConfigurationException + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + private Set buildKeySet(String keyGroupID, X509Certificate cert, KeyModule module) + throws ConfigurationException { + final ConfigurationProvider config = ConfigurationProvider.getInstance(); + Set keyGroupEntries; + + // get the KeyGroup entries from the configuration + if (cert != null) { + final Principal issuer = cert.getIssuerDN(); + final BigInteger serialNumber = cert.getSerialNumber(); + + keyGroupEntries = config.getKeyGroupEntries(issuer, serialNumber, + keyGroupID); + } else { + keyGroupEntries = config.getKeyGroupEntries(null, null, keyGroupID); + } + + // map the KeyGroup entries to a set of KeyEntryIDs + if (keyGroupEntries == null) { + return null; + } else if (keyGroupEntries.size() == 0) { + return Collections.EMPTY_SET; + } else { + + final Set keyEntryIDs = module.getPrivateKeyEntryIDs(); + final Set keySet = new HashSet(); + Iterator iter; + + // filter out the keys that do not exist in the IAIK configuration + // by walking through the key entries and checking if the exist in + // the + // keyGroupEntries + for (iter = keyEntryIDs.iterator(); iter.hasNext();) { + final KeyEntryID entryID = (KeyEntryID) iter.next(); + final KeyGroupEntry entry = new KeyGroupEntry(entryID.getModuleID(), + entryID.getCertificateIssuer(), + entryID.getCertificateSerialNumber()); + if (keyGroupEntries.contains(entry)) { + keySet.add(entryID); + } + } + return keySet; + } + } + + private X509Certificate getClientCertificate(HttpServletRequest request) { + final X509Certificate[] clientCert = (X509Certificate[]) request + .getAttribute(X509_CERTIFICATE_PROPERTY); + if (clientCert != null) { + return clientCert[0]; + } + return null; + } + + @Override + @SuppressWarnings("rawtypes") + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + try { + final X509Certificate cert = getClientCertificate(request); + final String keyId = request.getParameter(PARAM_KEYID); + + if (keyId == null) { + Logger.warn(PARAM_KEYID + " not provided in Request. Returning: " + + HttpServletResponse.SC_BAD_REQUEST); + response.sendError(HttpServletResponse.SC_BAD_REQUEST); + return; + } + + final String transactionId = TransactionIDGenerator.nextID(); + + final KeyModule module = KeyModuleFactory.getInstance(new TransactionId( + transactionId)); + + final Set keySet = buildKeySet(keyId, cert, module); + + if (keySet == null || keySet.isEmpty()) { + Logger.warn("No keys available for Key Identifier " + keyId + " and given authentication."); + response.sendError(HttpServletResponse.SC_NOT_FOUND); + return; + } + + if (keySet.size() != 1) { + Logger.warn("Too many keys available for Key Identifier " + keyId + " and given authentication."); + response.sendError(HttpServletResponse.SC_CONFLICT); + return; + } + + Iterator iter; + + // filter out the keys that do not exist in the IAIK configuration + // by walking through the key entries and checking if the exist in + // the + // keyGroupEntries + for (iter = keySet.iterator(); iter.hasNext();) { + final KeyEntryID entryID = (KeyEntryID) iter.next(); + + final List certChain = module.getPrivateKeyEntry(entryID).getCertificateChain(); + + if (certChain != null && !certChain.isEmpty()) { + Logger.trace("Returning Certificate!"); + final Certificate keyCert = (Certificate) certChain.get(0); + final byte[] certData = keyCert.getEncoded(); + response.setStatus(HttpServletResponse.SC_OK); + response.setContentType("application/pkix-cert"); + response.setHeader("Content-disposition", "attachment; filename=\"" + keyId + ".cer\""); + response.getOutputStream().write(certData); + response.getOutputStream().close(); + return; + } + + break; + } + + // No Certificate could be found! + Logger.warn("Failed to find keys available for Key Identifier " + keyId + " and given authentication."); + response.sendError(HttpServletResponse.SC_NOT_FOUND); + return; + } catch (final Throwable e) { + Logger.error("Unhandled Exception when providing certificate", e); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/ConfigurationServlet.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/ConfigurationServlet.java index 6164154..135d652 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/ConfigurationServlet.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/ConfigurationServlet.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.service; import java.io.IOException; @@ -37,7 +36,7 @@ import javax.servlet.http.HttpServletResponse; 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.init.*; +import at.gv.egovernment.moa.spss.server.init.SystemInitializer; import at.gv.egovernment.moa.spss.util.MessageProvider; import at.gv.egovernment.moaspss.logging.LogMsg; import at.gv.egovernment.moaspss.logging.Logger; @@ -46,36 +45,38 @@ import at.gv.egovernment.moaspss.logging.LoggingContextManager; /** * A servlet to initialize and update the MOA configuration. - * + * * @author Fatemeh Philippi * @author Patrick Peck * @version $Id$ */ public class ConfigurationServlet extends HttpServlet { /** - * - */ - private static final long serialVersionUID = 8372961105222028696L; -/** The document type of the HTML to generate. */ + * + */ + private static final long serialVersionUID = 8372961105222028696L; + /** The document type of the HTML to generate. */ private static final String DOC_TYPE = - "\n"; + "\n"; /** - * Handle a HTTP GET request, used to indicated that the MOA - * configuration needs to be updated (reloaded). - * - * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest, HttpServletResponse) + * Handle a HTTP GET request, used to indicated that the MOA configuration needs + * to be updated (reloaded). + * + * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest, + * HttpServletResponse) */ + @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { + throws ServletException, IOException { - MessageProvider msg = MessageProvider.getInstance(); + final MessageProvider msg = MessageProvider.getInstance(); PrintWriter out; // set up a logging context for logging the reconfiguration LoggingContextManager.getInstance().setLoggingContext( - new LoggingContext("configuration update")); + new LoggingContext("configuration update")); response.setContentType("text/html"); out = response.getWriter(); @@ -84,8 +85,8 @@ public class ConfigurationServlet extends HttpServlet { out.println(""); try { // reconfigure the system - ConfigurationProvider config = ConfigurationProvider.reload(); - IaikConfigurator iaikConfigurator = new IaikConfigurator(); + final ConfigurationProvider config = ConfigurationProvider.reload(); + final IaikConfigurator iaikConfigurator = new IaikConfigurator(); iaikConfigurator.configure(config); @@ -95,12 +96,12 @@ public class ConfigurationServlet extends HttpServlet { if (!config.getWarnings().isEmpty()) { // print the warnings - List allWarnings = new ArrayList(); + final List allWarnings = new ArrayList(); Iterator iter; - + allWarnings.addAll(config.getWarnings()); allWarnings.addAll(iaikConfigurator.getWarnings()); - + out.println("

    " + msg.getMessage("config.29", null) + "

    "); for (iter = allWarnings.iterator(); iter.hasNext();) { out.println(iter.next() + "
    "); @@ -108,7 +109,7 @@ public class ConfigurationServlet extends HttpServlet { out.println("

    " + msg.getMessage("config.28", null) + "

    "); } - } catch (Throwable t) { + } catch (final Throwable t) { out.println("

    " + msg.getMessage("config.20", null) + "

    "); out.println("

    " + msg.getMessage("config.28", null) + "

    "); Logger.warn(new LogMsg(msg.getMessage("config.20", null)), t); @@ -117,30 +118,33 @@ public class ConfigurationServlet extends HttpServlet { out.flush(); out.close(); - + // tear down the logging context LoggingContextManager.getInstance().setLoggingContext(null); } /** * Do the same as doGet. - * - * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, HttpServletResponse) + * + * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, + * HttpServletResponse) */ + @Override public void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { + throws ServletException, IOException { doGet(request, response); } /** * Perform some initial initialization tasks for the MOA web services * application. - * + * * Does an initial load of the MOA configuration to test if a working web * service can be provided. - * + * * @see javax.servlet.GenericServlet#init() */ + @Override public void init() throws ServletException { SystemInitializer.init(); } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/DeleteableDataSourceWrapper.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/DeleteableDataSourceWrapper.java index 1d49cd7..f5350af 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/DeleteableDataSourceWrapper.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/DeleteableDataSourceWrapper.java @@ -8,36 +8,35 @@ import at.gv.egovernment.moa.spss.server.transaction.DeleteableDataSource; public class DeleteableDataSourceWrapper implements DeleteableDataSource { - private org.apache.axis.attachments.ManagedMemoryDataSource wrapped; - - public DeleteableDataSourceWrapper(org.apache.axis.attachments.ManagedMemoryDataSource wrapped) { - this.wrapped = wrapped; - } - - @Override - public String getContentType() { - return this.wrapped.getContentType(); - } - - @Override - public InputStream getInputStream() throws IOException { - return this.wrapped.getInputStream(); - } - - @Override - public String getName() { - return this.wrapped.getName(); - } - - @Override - public OutputStream getOutputStream() throws IOException { - return this.wrapped.getOutputStream(); - } - - @Override - public void delete() { - this.wrapped.delete(); - } - - + private final org.apache.axis.attachments.ManagedMemoryDataSource wrapped; + + public DeleteableDataSourceWrapper(org.apache.axis.attachments.ManagedMemoryDataSource wrapped) { + this.wrapped = wrapped; + } + + @Override + public String getContentType() { + return this.wrapped.getContentType(); + } + + @Override + public InputStream getInputStream() throws IOException { + return this.wrapped.getInputStream(); + } + + @Override + public String getName() { + return this.wrapped.getName(); + } + + @Override + public OutputStream getOutputStream() throws IOException { + return this.wrapped.getOutputStream(); + } + + @Override + public void delete() { + this.wrapped.delete(); + } + } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/ServiceUtils.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/ServiceUtils.java index 697c69e..c4ad498 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/ServiceUtils.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/ServiceUtils.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.service; import java.io.ByteArrayInputStream; @@ -37,7 +36,7 @@ import at.gv.egovernment.moaspss.util.MOAErrorHandler; /** * Helper methods for the Service classes. - * + * * @author Patrick Peck * @version $Id$ */ @@ -45,59 +44,59 @@ public class ServiceUtils { /** * Schema-validate a request. - * + * * @param request The request to validate. * @throws MOAApplicationException An error occurred validating the requst. */ public static void validateRequest(Element[] request) - throws MOAApplicationException { + throws MOAApplicationException { // validate the request try { DOMUtils.validateElement( - request[0], - Constants.ALL_SCHEMA_LOCATIONS, - null, - new MOASPSSEntityResolver()); - } catch (Exception e) { + request[0], + Constants.ALL_SCHEMA_LOCATIONS, + null, + new MOASPSSEntityResolver()); + } catch (final Exception e) { throw new MOAApplicationException( - "1100", - new Object[] { e.getMessage()}, - e); + "1100", + new Object[] { e.getMessage() }, + e); } } /** * Reparse the request with schema-validation turned on so that ID references * are resolved. - * + * * @param request The request to reparse. * @return The reparsed request. * @throws MOAApplicationException An error occurred parsing the request. */ public static Element reparseRequest(Element request) - throws MOAApplicationException { + throws MOAApplicationException { try { - byte[] requestBytes = DOMUtils.serializeNode(request, "UTF-8"); - Document validatedRequest = DOMUtils.parseDocument(new ByteArrayInputStream(requestBytes), - true, - Constants.ONLY_MOASIG_SCHEMA_LOCATIONS, - null, - new MOASPSSEntityResolver(), - new MOAErrorHandler()); - + final byte[] requestBytes = DOMUtils.serializeNode(request, "UTF-8"); + final Document validatedRequest = DOMUtils.parseDocument(new ByteArrayInputStream(requestBytes), + true, + Constants.ONLY_MOASIG_SCHEMA_LOCATIONS, + null, + new MOASPSSEntityResolver(), + new MOAErrorHandler()); + // DOMUtils.parseDocument( // new ByteArrayInputStream(requestBytes), // true, // Constants.ALL_SCHEMA_LOCATIONS, // null); return validatedRequest.getDocumentElement(); - } catch (Exception e) { + } catch (final Exception e) { throw new MOAApplicationException( - "1100", - new Object[] { e.getMessage()}, - e); + "1100", + new Object[] { e.getMessage() }, + e); } } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/SignatureCreationService.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/SignatureCreationService.java index 839d8ba..4030883 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/SignatureCreationService.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/SignatureCreationService.java @@ -21,7 +21,6 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.service; import java.util.Collections; @@ -43,7 +42,6 @@ import at.gv.egovernment.moa.spss.api.xmlbind.CreateXMLSignatureResponseBuilder; import at.gv.egovernment.moa.spss.api.xmlsign.CreateXMLSignatureRequest; import at.gv.egovernment.moa.spss.api.xmlsign.CreateXMLSignatureResponse; import at.gv.egovernment.moa.spss.server.invoke.CMSSignatureCreationInvoker; -import at.gv.egovernment.moa.spss.server.invoke.PDFASInvoker; import at.gv.egovernment.moa.spss.server.invoke.XMLSignatureCreationInvoker; import at.gv.egovernment.moa.spss.server.transaction.TransactionContext; import at.gv.egovernment.moa.spss.server.transaction.TransactionContextManager; @@ -57,260 +55,261 @@ import at.gv.egovernment.moaspss.util.StreamUtils; /** * The service endpoint for the SignatureCreation web service. - * + * * @author Patrick Peck * @version $Id$ */ public class SignatureCreationService { - - /** - * Handle a CreatePDFSignatureRequest. - * - * @param request The CreatePDFSignatureRequest to work on - * (contained in the 0th element of the array). - * @return A CreatePDFSignatureResponse as the only element of - * the Element array. - * @throws AxisFault An error occurred during handling of the message. - */ - public Element[] CreatePDFSignatureRequest(Element[] request) - throws AxisFault { - Logger.trace("---- Entering SignatureCreationService"); - //PDFSignatureCreationInvoker invoker = - // PDFSignatureCreationInvoker.getInstance(); - Element[] response = new Element[1]; - - // check that we have a CreateXMLSignatureRequest; if not, create an - // AxisFault, just like the org.apache.axis.providers.java.MsgProvider - if (!Constants.MOA_SPSS_CREATE_PDF_REQUEST.equals(request[0].getLocalName()) || - !Constants.MOA_NS_URI.equals(request[0].getNamespaceURI())) - { - QName qname = - new QName(request[0].getNamespaceURI(), request[0].getLocalName()); - throw new AxisFault( - Messages.getMessage("noOperationForQName", qname.toString())); // TODO GK Operation name does not make it into the error repsonse - } - - // handle the request - try { - - // create a parser and builder for binding API objects to/from XML - CreatePDFSignatureRequestParser requestParser = - new CreatePDFSignatureRequestParser(); - CreatePDFSignatureResponseBuilder responseBuilder = - new CreatePDFSignatureResponseBuilder(); - Element reparsedReq; - CreatePDFRequest requestObj; - CreatePDFRespone responseObj = null; - - //since Axis (1.1 ff) has problem with namespaces we take the raw request stored by the Axishandler. - TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); - - // validate the request - reparsedReq = ServiceUtils.reparseRequest(request[0]);//context.getRequest()); - - // convert to API objects - Logger.trace(">>> preparsing Request"); - requestObj = requestParser.parse(reparsedReq); - Logger.trace("<<< preparsed Request"); - - Logger.trace(">>> creating Signature"); - // invoke the core logic - //responseObj = PDFASInvoker.getInstance().createPDFSignature(requestObj, context.getTransactionID()); - - Logger.trace("<<< created Signature"); - - Logger.trace(">>> building Response"); - // map back to XML - response[0] = responseBuilder.build(responseObj).getDocumentElement(); - Logger.trace("<<< built Response"); - - // save response in transaction - context.setResponse(response[0]); - Logger.trace("---- Leaving SignatureCreationService"); - - //TODO: remove if PDF signatures are supported - throw new MOASystemException("Create PAdES signatures is currently NOT supported by MOA-SIG", null); - - //return response; - - } catch (MOAException e) { - AxisFault fault = AxisFault.makeFault(e); - fault.setFaultDetail(new Element[] { e.toErrorResponse()}); - Logger.debug("Anfrage zur Signaturerstellung wurde nicht erfolgreich beendet:" - + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); - throw fault; - } catch (Throwable t) { - MOASystemException e = new MOASystemException("2900", null, t); - AxisFault fault = AxisFault.makeFault(e); - fault.setFaultDetail(new Element[] { e.toErrorResponse()}); - Logger.debug("Anfrage zur Signaturerstellung wurde nicht erfolgreich beendet:" - + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); - throw fault; - } - - - } - - /** - * Handle a CreateXMLSignatureRequest. - * - * @param request The CreateXMLSignatureRequest to work on - * (contained in the 0th element of the array). - * @return A CreateXMLSignatureResponse as the only element of - * the Element array. - * @throws AxisFault An error occurred during handling of the message. - */ - public Element[] CreateCMSSignatureRequest(Element[] request) - throws AxisFault { - Logger.trace("---- Entering SignatureCreationService"); - CMSSignatureCreationInvoker invoker = - CMSSignatureCreationInvoker.getInstance(); - Element[] response = new Element[1]; - - // check that we have a CreateXMLSignatureRequest; if not, create an - // AxisFault, just like the org.apache.axis.providers.java.MsgProvider - if (!Constants.MOA_SPSS_CREATE_CMS_REQUEST.equals(request[0].getLocalName()) || - !Constants.MOA_NS_URI.equals(request[0].getNamespaceURI())) - { - QName qname = - new QName(request[0].getNamespaceURI(), request[0].getLocalName()); - throw new AxisFault( - Messages.getMessage("noOperationForQName", qname.toString())); // TODO GK Operation name does not make it into the error repsonse - } - - // handle the request - try { - - // create a parser and builder for binding API objects to/from XML - CreateCMSSignatureRequestParser requestParser = - new CreateCMSSignatureRequestParser(); - CreateCMSSignatureResponseBuilder responseBuilder = - new CreateCMSSignatureResponseBuilder(); - Element reparsedReq; - CreateCMSSignatureRequest requestObj; - CreateCMSSignatureResponse responseObj; - - //since Axis (1.1 ff) has problem with namespaces we take the raw request stored by the Axishandler. - TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); - - // validate the request - reparsedReq = ServiceUtils.reparseRequest(request[0]);//context.getRequest()); - - // convert to API objects - Logger.trace(">>> preparsing Request"); - requestObj = requestParser.parse(reparsedReq); - Logger.trace("<<< preparsed Request"); - - Logger.trace(">>> creating Signature"); - // invoke the core logic - responseObj = invoker.createCMSSignature(requestObj, Collections.EMPTY_SET); - Logger.trace("<<< created Signature"); - - Logger.trace(">>> building Response"); - // map back to XML - response[0] = responseBuilder.build(responseObj).getDocumentElement(); - Logger.trace("<<< built Response"); - - // save response in transaction - context.setResponse(response[0]); - Logger.trace("---- Leaving SignatureCreationService"); - - - } catch (MOAException e) { - AxisFault fault = AxisFault.makeFault(e); - fault.setFaultDetail(new Element[] { e.toErrorResponse()}); - Logger.debug("Anfrage zur Signaturerstellung wurde nicht erfolgreich beendet:" - + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); - throw fault; - } catch (Throwable t) { - MOASystemException e = new MOASystemException("2900", null, t); - AxisFault fault = AxisFault.makeFault(e); - fault.setFaultDetail(new Element[] { e.toErrorResponse()}); - Logger.debug("Anfrage zur Signaturerstellung wurde nicht erfolgreich beendet:" - + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); - throw fault; - } - - return response; - } + + /** + * Handle a CreatePDFSignatureRequest. + * + * @param request The CreatePDFSignatureRequest to work on + * (contained in the 0th element of the array). + * @return A CreatePDFSignatureResponse as the only element of the + * Element array. + * @throws AxisFault An error occurred during handling of the message. + */ + public Element[] CreatePDFSignatureRequest(Element[] request) + throws AxisFault { + Logger.trace("---- Entering SignatureCreationService"); + // PDFSignatureCreationInvoker invoker = + // PDFSignatureCreationInvoker.getInstance(); + final Element[] response = new Element[1]; + + // check that we have a CreateXMLSignatureRequest; if not, create an + // AxisFault, just like the org.apache.axis.providers.java.MsgProvider + if (!Constants.MOA_SPSS_CREATE_PDF_REQUEST.equals(request[0].getLocalName()) || + !Constants.MOA_NS_URI.equals(request[0].getNamespaceURI())) { + final QName qname = + new QName(request[0].getNamespaceURI(), request[0].getLocalName()); + throw new AxisFault( + Messages.getMessage("noOperationForQName", qname.toString())); // TODO GK Operation name does not + // make it into the error repsonse + } + + // handle the request + try { + + // create a parser and builder for binding API objects to/from XML + final CreatePDFSignatureRequestParser requestParser = + new CreatePDFSignatureRequestParser(); + final CreatePDFSignatureResponseBuilder responseBuilder = + new CreatePDFSignatureResponseBuilder(); + Element reparsedReq; + CreatePDFRequest requestObj; + final CreatePDFRespone responseObj = null; + + // since Axis (1.1 ff) has problem with namespaces we take the raw request + // stored by the Axishandler. + final TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); + + // validate the request + reparsedReq = ServiceUtils.reparseRequest(request[0]);// context.getRequest()); + + // convert to API objects + Logger.trace(">>> preparsing Request"); + requestObj = requestParser.parse(reparsedReq); + Logger.trace("<<< preparsed Request"); + + Logger.trace(">>> creating Signature"); + // invoke the core logic + // responseObj = PDFASInvoker.getInstance().createPDFSignature(requestObj, + // context.getTransactionID()); + + Logger.trace("<<< created Signature"); + + Logger.trace(">>> building Response"); + // map back to XML + response[0] = responseBuilder.build(responseObj).getDocumentElement(); + Logger.trace("<<< built Response"); + + // save response in transaction + context.setResponse(response[0]); + Logger.trace("---- Leaving SignatureCreationService"); + + // TODO: remove if PDF signatures are supported + throw new MOASystemException("Create PAdES signatures is currently NOT supported by MOA-SIG", null); + + // return response; + + } catch (final MOAException e) { + final AxisFault fault = AxisFault.makeFault(e); + fault.setFaultDetail(new Element[] { e.toErrorResponse() }); + Logger.debug("Anfrage zur Signaturerstellung wurde nicht erfolgreich beendet:" + + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); + throw fault; + } catch (final Throwable t) { + final MOASystemException e = new MOASystemException("2900", null, t); + final AxisFault fault = AxisFault.makeFault(e); + fault.setFaultDetail(new Element[] { e.toErrorResponse() }); + Logger.debug("Anfrage zur Signaturerstellung wurde nicht erfolgreich beendet:" + + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); + throw fault; + } + + } /** * Handle a CreateXMLSignatureRequest. * * @param request The CreateXMLSignatureRequest to work on - * (contained in the 0th element of the array). - * @return A CreateXMLSignatureResponse as the only element of - * the Element array. + * (contained in the 0th element of the array). + * @return A CreateXMLSignatureResponse as the only element of the + * Element array. + * @throws AxisFault An error occurred during handling of the message. + */ + public Element[] CreateCMSSignatureRequest(Element[] request) + throws AxisFault { + Logger.trace("---- Entering SignatureCreationService"); + final CMSSignatureCreationInvoker invoker = + CMSSignatureCreationInvoker.getInstance(); + final Element[] response = new Element[1]; + + // check that we have a CreateXMLSignatureRequest; if not, create an + // AxisFault, just like the org.apache.axis.providers.java.MsgProvider + if (!Constants.MOA_SPSS_CREATE_CMS_REQUEST.equals(request[0].getLocalName()) || + !Constants.MOA_NS_URI.equals(request[0].getNamespaceURI())) { + final QName qname = + new QName(request[0].getNamespaceURI(), request[0].getLocalName()); + throw new AxisFault( + Messages.getMessage("noOperationForQName", qname.toString())); // TODO GK Operation name does not + // make it into the error repsonse + } + + // handle the request + try { + + // create a parser and builder for binding API objects to/from XML + final CreateCMSSignatureRequestParser requestParser = + new CreateCMSSignatureRequestParser(); + final CreateCMSSignatureResponseBuilder responseBuilder = + new CreateCMSSignatureResponseBuilder(); + Element reparsedReq; + CreateCMSSignatureRequest requestObj; + CreateCMSSignatureResponse responseObj; + + // since Axis (1.1 ff) has problem with namespaces we take the raw request + // stored by the Axishandler. + final TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); + + // validate the request + reparsedReq = ServiceUtils.reparseRequest(request[0]);// context.getRequest()); + + // convert to API objects + Logger.trace(">>> preparsing Request"); + requestObj = requestParser.parse(reparsedReq); + Logger.trace("<<< preparsed Request"); + + Logger.trace(">>> creating Signature"); + // invoke the core logic + responseObj = invoker.createCMSSignature(requestObj, Collections.EMPTY_SET); + Logger.trace("<<< created Signature"); + + Logger.trace(">>> building Response"); + // map back to XML + response[0] = responseBuilder.build(responseObj).getDocumentElement(); + Logger.trace("<<< built Response"); + + // save response in transaction + context.setResponse(response[0]); + Logger.trace("---- Leaving SignatureCreationService"); + + } catch (final MOAException e) { + final AxisFault fault = AxisFault.makeFault(e); + fault.setFaultDetail(new Element[] { e.toErrorResponse() }); + Logger.debug("Anfrage zur Signaturerstellung wurde nicht erfolgreich beendet:" + + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); + throw fault; + } catch (final Throwable t) { + final MOASystemException e = new MOASystemException("2900", null, t); + final AxisFault fault = AxisFault.makeFault(e); + fault.setFaultDetail(new Element[] { e.toErrorResponse() }); + Logger.debug("Anfrage zur Signaturerstellung wurde nicht erfolgreich beendet:" + + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); + throw fault; + } + + return response; + } + + /** + * Handle a CreateXMLSignatureRequest. + * + * @param request The CreateXMLSignatureRequest to work on + * (contained in the 0th element of the array). + * @return A CreateXMLSignatureResponse as the only element of the + * Element array. * @throws AxisFault An error occurred during handling of the message. */ public Element[] CreateXMLSignatureRequest(Element[] request) - throws AxisFault { - Logger.trace("---- Entering SignatureCreationService"); - XMLSignatureCreationInvoker invoker = - XMLSignatureCreationInvoker.getInstance(); - Element[] response = new Element[1]; + throws AxisFault { + Logger.trace("---- Entering SignatureCreationService"); + final XMLSignatureCreationInvoker invoker = + XMLSignatureCreationInvoker.getInstance(); + final Element[] response = new Element[1]; // check that we have a CreateXMLSignatureRequest; if not, create an // AxisFault, just like the org.apache.axis.providers.java.MsgProvider if (!Constants.MOA_SPSS_CREATE_XML_REQUEST.equals(request[0].getLocalName()) || - !Constants.MOA_NS_URI.equals(request[0].getNamespaceURI())) - { - QName qname = - new QName(request[0].getNamespaceURI(), request[0].getLocalName()); + !Constants.MOA_NS_URI.equals(request[0].getNamespaceURI())) { + final QName qname = + new QName(request[0].getNamespaceURI(), request[0].getLocalName()); throw new AxisFault( - Messages.getMessage("noOperationForQName", qname.toString())); // TODO GK Operation name does not make it into the error repsonse + Messages.getMessage("noOperationForQName", qname.toString())); // TODO GK Operation name does not + // make it into the error repsonse } // handle the request try { - + // create a parser and builder for binding API objects to/from XML - CreateXMLSignatureRequestParser requestParser = - new CreateXMLSignatureRequestParser(); - CreateXMLSignatureResponseBuilder responseBuilder = - new CreateXMLSignatureResponseBuilder(); + final CreateXMLSignatureRequestParser requestParser = + new CreateXMLSignatureRequestParser(); + final CreateXMLSignatureResponseBuilder responseBuilder = + new CreateXMLSignatureResponseBuilder(); Element reparsedReq; CreateXMLSignatureRequest requestObj; CreateXMLSignatureResponse responseObj; - //since Axis (1.1 ff) has problem with namespaces we take the raw request stored by the Axishandler. - TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); - + // since Axis (1.1 ff) has problem with namespaces we take the raw request + // stored by the Axishandler. + final TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); + // validate the request - reparsedReq = ServiceUtils.reparseRequest(request[0]);//context.getRequest()); + reparsedReq = ServiceUtils.reparseRequest(request[0]);// context.getRequest()); // convert to API objects - Logger.trace(">>> preparsing Request"); + Logger.trace(">>> preparsing Request"); requestObj = requestParser.parse(reparsedReq); - Logger.trace("<<< preparsed Request"); - - Logger.trace(">>> creating Signature"); + Logger.trace("<<< preparsed Request"); + + Logger.trace(">>> creating Signature"); // invoke the core logic responseObj = invoker.createXMLSignature(requestObj, Collections.EMPTY_SET); - Logger.trace("<<< created Signature"); + Logger.trace("<<< created Signature"); - Logger.trace(">>> building Response"); + Logger.trace(">>> building Response"); // map back to XML response[0] = responseBuilder.build(responseObj).getDocumentElement(); - Logger.trace("<<< built Response"); - + Logger.trace("<<< built Response"); + // save response in transaction context.setResponse(response[0]); - Logger.trace("---- Leaving SignatureCreationService"); - - - } catch (MOAException e) { - AxisFault fault = AxisFault.makeFault(e); - fault.setFaultDetail(new Element[] { e.toErrorResponse()}); - Logger.debug("Anfrage zur Signaturerstellung wurde nicht erfolgreich beendet:" - + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); + Logger.trace("---- Leaving SignatureCreationService"); + + } catch (final MOAException e) { + final AxisFault fault = AxisFault.makeFault(e); + fault.setFaultDetail(new Element[] { e.toErrorResponse() }); + Logger.debug("Anfrage zur Signaturerstellung wurde nicht erfolgreich beendet:" + + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); throw fault; - } catch (Throwable t) { - MOASystemException e = new MOASystemException("2900", null, t); - AxisFault fault = AxisFault.makeFault(e); - fault.setFaultDetail(new Element[] { e.toErrorResponse()}); - Logger.debug("Anfrage zur Signaturerstellung wurde nicht erfolgreich beendet:" - + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); + } catch (final Throwable t) { + final MOASystemException e = new MOASystemException("2900", null, t); + final AxisFault fault = AxisFault.makeFault(e); + fault.setFaultDetail(new Element[] { e.toErrorResponse() }); + Logger.debug("Anfrage zur Signaturerstellung wurde nicht erfolgreich beendet:" + + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); throw fault; } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/SignatureVerificationService.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/SignatureVerificationService.java index e4d93a7..55cc5c6 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/SignatureVerificationService.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/SignatureVerificationService.java @@ -21,21 +21,21 @@ * that you distribute must include a readable copy of the "NOTICE" text file. */ - package at.gv.egovernment.moa.spss.server.service; +import java.util.List; + +import org.apache.axis.AxisFault; +import org.w3c.dom.Element; + import at.gv.egiz.asic.api.ASiC; import at.gv.egiz.asic.api.ASiCFactory; -import at.gv.egiz.asic.api.ASiCFormat; import at.gv.egiz.asic.api.ASiCVerificationResult; import at.gv.egiz.asic.impl.ASiCMOAVerifier; import at.gv.egiz.asic.xmlbind.VerifyASICSignatureRequestParser; import at.gv.egiz.asic.xmlbind.VerifyASICSignatureResponseBuilder; import at.gv.egiz.asic.xmlbind.VerifyASiCRequest; import at.gv.egovernment.moa.spss.MOAApplicationException; -import org.apache.axis.AxisFault; -import org.w3c.dom.Element; - import at.gv.egovernment.moa.spss.MOAException; import at.gv.egovernment.moa.spss.MOASystemException; import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureRequest; @@ -54,192 +54,189 @@ import at.gv.egovernment.moa.spss.server.transaction.TransactionContextManager; import at.gv.egovernment.moaspss.logging.Logger; import at.gv.egovernment.moaspss.util.StreamUtils; -import java.io.FileInputStream; -import java.util.List; - /** * The service endpoint for the SignatureVerification web service. - * + * * @author Patrick Peck * @version $Id$ */ public class SignatureVerificationService { - /** - * Handle a VerifyPDFSignatureRequest. - * - * @param request The VerifyPDFSignatureRequest to work on - * (contained in the 0th element of the array). - * @return A VerifyPDFSignatureResponse as the only element of - * the Element array. - * @throws AxisFault An error occurred during handling of the message. - */ - public Element[] VerifyPDFSignatureRequest(Element[] request) - throws AxisFault { - CMSSignatureVerificationInvoker invoker = - CMSSignatureVerificationInvoker.getInstance(); - Element[] response = new Element[1]; - - try { - - // create a parser and builder for binding API objects to/from XML - VerifyCMSSignatureRequestParser requestParser = - new VerifyCMSSignatureRequestParser(); - VerifyPDFSignatureResponseBuilder responseBuilder = - new VerifyPDFSignatureResponseBuilder(); - Element reparsedReq; - VerifyCMSSignatureRequest requestObj; - VerifyCMSSignatureResponse responseObj; - // create a parser and builder for binding API objects to/from XML - /*VerifyPDFRequestParser requestParser = - new VerifyPDFRequestParser(); - VerifyPDFResponseBuilder responseBuilder = - new VerifyPDFResponseBuilder(); - Element reparsedReq; - VerifyPDFRequest requestObj; - VerifyPDFResponse responseObj;*/ - - //since Axis (1.1 ff) has problem with namespaces we take the raw request stored by the Axishandler. - TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); - // validate the request - reparsedReq = ServiceUtils.reparseRequest(request[0]);//context.getRequest()); - - // convert to API objects - requestObj = requestParser.parsePDF(reparsedReq); - - // invoke the core logic - responseObj = invoker.verifyCMSSignature(requestObj); - - // map back to XML - response[0] = responseBuilder.build(responseObj).getDocumentElement(); - - // save response in transaction - context.setResponse(response[0]); - - - } catch (MOAException e) { - AxisFault fault = AxisFault.makeFault(e); - fault.setFaultDetail(new Element[] { e.toErrorResponse()}); - Logger.debug("Anfrage zur Signaturpruefung wurde nicht erfolgreich beendet:" - + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); - throw fault; - } catch (Throwable t) { - MOASystemException e = new MOASystemException("2900", null, t); - AxisFault fault = AxisFault.makeFault(e); - fault.setFaultDetail(new Element[] { e.toErrorResponse()}); - Logger.debug("Anfrage zur Signaturpruefung wurde nicht erfolgreich beendet:" - + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); - throw fault; - } - - return response; - } - - - /** - * Handle a VerifyPDFSignatureRequest. - * - * @param request The VerifyPDFSignatureRequest to work on - * (contained in the 0th element of the array). - * @return A VerifyPDFSignatureResponse as the only element of - * the Element array. - * @throws AxisFault An error occurred during handling of the message. - */ - public Element[] VerifyASICSignatureRequest(Element[] request) - throws AxisFault { - CMSSignatureVerificationInvoker invoker = - CMSSignatureVerificationInvoker.getInstance(); - Element[] response = new Element[1]; - - try { - - // create a parser and builder for binding API objects to/from XML - VerifyASICSignatureRequestParser requestParser = - new VerifyASICSignatureRequestParser(); - VerifyASICSignatureResponseBuilder responseBuilder = - new VerifyASICSignatureResponseBuilder(); - Element reparsedReq; - VerifyASiCRequest requestObj; - VerifyCMSSignatureResponse responseObj; - // create a parser and builder for binding API objects to/from XML - - //since Axis (1.1 ff) has problem with namespaces we take the raw request stored by the Axishandler. - TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); - // validate the request - reparsedReq = ServiceUtils.reparseRequest(request[0]);//context.getRequest()); - - // convert to API objects - requestObj = requestParser.parseASIC(reparsedReq); - - if(requestObj.getFormat() == null) { - throw new MOAApplicationException("asic.0006", null); - } - - ASiC aSiC = ASiCFactory.parseASiC(requestObj.getAsicInput(), - requestObj.getFormat()); - - Logger.debug("Got ASiC " + aSiC); - - // invoke the core logic - ASiCMOAVerifier v = new ASiCMOAVerifier(); - List results = v.verify(aSiC, - requestObj.getTrustProfile(), requestObj.getDate()); - - // map back to XML - response[0] = responseBuilder.build(results).getDocumentElement(); - - // save response in transaction - context.setResponse(response[0]); - - } catch (MOAException e) { - AxisFault fault = AxisFault.makeFault(e); - fault.setFaultDetail(new Element[] { e.toErrorResponse()}); - Logger.debug("Anfrage zur Signaturpruefung wurde nicht erfolgreich beendet:" - + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); - throw fault; - } catch (Throwable t) { - MOASystemException e = new MOASystemException("2900", null, t); - AxisFault fault = AxisFault.makeFault(e); - fault.setFaultDetail(new Element[] { e.toErrorResponse()}); - Logger.debug("Anfrage zur Signaturpruefung wurde nicht erfolgreich beendet:" - + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); - throw fault; - } - - return response; + /** + * Handle a VerifyPDFSignatureRequest. + * + * @param request The VerifyPDFSignatureRequest to work on + * (contained in the 0th element of the array). + * @return A VerifyPDFSignatureResponse as the only element of the + * Element array. + * @throws AxisFault An error occurred during handling of the message. + */ + public Element[] VerifyPDFSignatureRequest(Element[] request) + throws AxisFault { + final CMSSignatureVerificationInvoker invoker = + CMSSignatureVerificationInvoker.getInstance(); + final Element[] response = new Element[1]; + + try { + + // create a parser and builder for binding API objects to/from XML + final VerifyCMSSignatureRequestParser requestParser = + new VerifyCMSSignatureRequestParser(); + final VerifyPDFSignatureResponseBuilder responseBuilder = + new VerifyPDFSignatureResponseBuilder(); + Element reparsedReq; + VerifyCMSSignatureRequest requestObj; + VerifyCMSSignatureResponse responseObj; + // create a parser and builder for binding API objects to/from XML + /* + * VerifyPDFRequestParser requestParser = new VerifyPDFRequestParser(); + * VerifyPDFResponseBuilder responseBuilder = new VerifyPDFResponseBuilder(); + * Element reparsedReq; VerifyPDFRequest requestObj; VerifyPDFResponse + * responseObj; + */ + + // since Axis (1.1 ff) has problem with namespaces we take the raw request + // stored by the Axishandler. + final TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); + // validate the request + reparsedReq = ServiceUtils.reparseRequest(request[0]);// context.getRequest()); + + // convert to API objects + requestObj = requestParser.parsePDF(reparsedReq); + + // invoke the core logic + responseObj = invoker.verifyCMSSignature(requestObj); + + // map back to XML + response[0] = responseBuilder.build(responseObj).getDocumentElement(); + + // save response in transaction + context.setResponse(response[0]); + + } catch (final MOAException e) { + final AxisFault fault = AxisFault.makeFault(e); + fault.setFaultDetail(new Element[] { e.toErrorResponse() }); + Logger.debug("Anfrage zur Signaturpruefung wurde nicht erfolgreich beendet:" + + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); + throw fault; + } catch (final Throwable t) { + final MOASystemException e = new MOASystemException("2900", null, t); + final AxisFault fault = AxisFault.makeFault(e); + fault.setFaultDetail(new Element[] { e.toErrorResponse() }); + Logger.debug("Anfrage zur Signaturpruefung wurde nicht erfolgreich beendet:" + + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); + throw fault; } - + + return response; + } + + /** + * Handle a VerifyPDFSignatureRequest. + * + * @param request The VerifyPDFSignatureRequest to work on + * (contained in the 0th element of the array). + * @return A VerifyPDFSignatureResponse as the only element of the + * Element array. + * @throws AxisFault An error occurred during handling of the message. + */ + public Element[] VerifyASICSignatureRequest(Element[] request) + throws AxisFault { + final CMSSignatureVerificationInvoker invoker = + CMSSignatureVerificationInvoker.getInstance(); + final Element[] response = new Element[1]; + + try { + + // create a parser and builder for binding API objects to/from XML + final VerifyASICSignatureRequestParser requestParser = + new VerifyASICSignatureRequestParser(); + final VerifyASICSignatureResponseBuilder responseBuilder = + new VerifyASICSignatureResponseBuilder(); + Element reparsedReq; + VerifyASiCRequest requestObj; + final VerifyCMSSignatureResponse responseObj; + // create a parser and builder for binding API objects to/from XML + + // since Axis (1.1 ff) has problem with namespaces we take the raw request + // stored by the Axishandler. + final TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); + // validate the request + reparsedReq = ServiceUtils.reparseRequest(request[0]);// context.getRequest()); + + // convert to API objects + requestObj = requestParser.parseASIC(reparsedReq); + + if (requestObj.getFormat() == null) { + throw new MOAApplicationException("asic.0006", null); + } + + final ASiC aSiC = ASiCFactory.parseASiC(requestObj.getAsicInput(), + requestObj.getFormat()); + + Logger.debug("Got ASiC " + aSiC); + + // invoke the core logic + final ASiCMOAVerifier v = new ASiCMOAVerifier(); + final List results = v.verify(aSiC, + requestObj.getTrustProfile(), requestObj.getDate()); + + // map back to XML + response[0] = responseBuilder.build(results).getDocumentElement(); + + // save response in transaction + context.setResponse(response[0]); + + } catch (final MOAException e) { + final AxisFault fault = AxisFault.makeFault(e); + fault.setFaultDetail(new Element[] { e.toErrorResponse() }); + Logger.debug("Anfrage zur Signaturpruefung wurde nicht erfolgreich beendet:" + + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); + throw fault; + } catch (final Throwable t) { + final MOASystemException e = new MOASystemException("2900", null, t); + final AxisFault fault = AxisFault.makeFault(e); + fault.setFaultDetail(new Element[] { e.toErrorResponse() }); + Logger.debug("Anfrage zur Signaturpruefung wurde nicht erfolgreich beendet:" + + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); + throw fault; + } + + return response; + } + /** * Handle a VerifyCMSSignatureRequest. - * + * * @param request The VerifyCMSSignatureRequest to work on - * (contained in the 0th element of the array). - * @return A VerifyCMSSignatureResponse as the only element of - * the Element array. + * (contained in the 0th element of the array). + * @return A VerifyCMSSignatureResponse as the only element of the + * Element array. * @throws AxisFault An error occurred during handling of the message. */ public Element[] VerifyCMSSignatureRequest(Element[] request) - throws AxisFault { - CMSSignatureVerificationInvoker invoker = - CMSSignatureVerificationInvoker.getInstance(); - Element[] response = new Element[1]; - + throws AxisFault { + final CMSSignatureVerificationInvoker invoker = + CMSSignatureVerificationInvoker.getInstance(); + final Element[] response = new Element[1]; + try { - + // create a parser and builder for binding API objects to/from XML - VerifyCMSSignatureRequestParser requestParser = - new VerifyCMSSignatureRequestParser(); - VerifyCMSSignatureResponseBuilder responseBuilder = - new VerifyCMSSignatureResponseBuilder(); + final VerifyCMSSignatureRequestParser requestParser = + new VerifyCMSSignatureRequestParser(); + final VerifyCMSSignatureResponseBuilder responseBuilder = + new VerifyCMSSignatureResponseBuilder(); Element reparsedReq; VerifyCMSSignatureRequest requestObj; VerifyCMSSignatureResponse responseObj; - //since Axis (1.1 ff) has problem with namespaces we take the raw request stored by the Axishandler. - TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); + // since Axis (1.1 ff) has problem with namespaces we take the raw request + // stored by the Axishandler. + final TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); // validate the request - reparsedReq = ServiceUtils.reparseRequest(request[0]);//context.getRequest()); - + reparsedReq = ServiceUtils.reparseRequest(request[0]);// context.getRequest()); + // convert to API objects requestObj = requestParser.parse(reparsedReq); @@ -251,20 +248,19 @@ public class SignatureVerificationService { // save response in transaction context.setResponse(response[0]); - - - } catch (MOAException e) { - AxisFault fault = AxisFault.makeFault(e); - fault.setFaultDetail(new Element[] { e.toErrorResponse()}); - Logger.debug("Anfrage zur Signaturpruefung wurde nicht erfolgreich beendet:" - + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); + + } catch (final MOAException e) { + final AxisFault fault = AxisFault.makeFault(e); + fault.setFaultDetail(new Element[] { e.toErrorResponse() }); + Logger.debug("Anfrage zur Signaturpruefung wurde nicht erfolgreich beendet:" + + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); throw fault; - } catch (Throwable t) { - MOASystemException e = new MOASystemException("2900", null, t); - AxisFault fault = AxisFault.makeFault(e); - fault.setFaultDetail(new Element[] { e.toErrorResponse()}); - Logger.debug("Anfrage zur Signaturpruefung wurde nicht erfolgreich beendet:" - + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); + } catch (final Throwable t) { + final MOASystemException e = new MOASystemException("2900", null, t); + final AxisFault fault = AxisFault.makeFault(e); + fault.setFaultDetail(new Element[] { e.toErrorResponse() }); + Logger.debug("Anfrage zur Signaturpruefung wurde nicht erfolgreich beendet:" + + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); throw fault; } @@ -273,60 +269,60 @@ public class SignatureVerificationService { /** * Handle a VerifyXMLSignatureRequest. - * + * * @param request The VerifyXMLSignatureRequest to work on - * (contained in the 0th element of the array). - * @return A VerifyXMLSignatureResponse as the only element of - * the Element array. + * (contained in the 0th element of the array). + * @return A VerifyXMLSignatureResponse as the only element of the + * Element array. * @throws AxisFault An error occurred during handling of the message. */ public Element[] VerifyXMLSignatureRequest(Element[] request) - throws AxisFault { - XMLSignatureVerificationInvoker invoker = - XMLSignatureVerificationInvoker.getInstance(); - Element[] response = new Element[1]; + throws AxisFault { + final XMLSignatureVerificationInvoker invoker = + XMLSignatureVerificationInvoker.getInstance(); + final Element[] response = new Element[1]; try { - - // create a parser and builder for binding API objects to/from XML - VerifyXMLSignatureRequestParser requestParser = - new VerifyXMLSignatureRequestParser(); - VerifyXMLSignatureResponseBuilder responseBuilder = - new VerifyXMLSignatureResponseBuilder(); + + // create a parser and builder for binding API objects to/from XML + final VerifyXMLSignatureRequestParser requestParser = + new VerifyXMLSignatureRequestParser(); + final VerifyXMLSignatureResponseBuilder responseBuilder = + new VerifyXMLSignatureResponseBuilder(); Element reparsedReq; VerifyXMLSignatureRequest requestObj; VerifyXMLSignatureResponse responseObj; - //since Axis (1.1 ff) has problem with namespaces we take the raw request stored by the Axishandler. - TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); + // since Axis (1.1 ff) has problem with namespaces we take the raw request + // stored by the Axishandler. + final TransactionContext context = TransactionContextManager.getInstance().getTransactionContext(); // validate the request reparsedReq = ServiceUtils.reparseRequest(context.getRequest()); - + // convert to API objects requestObj = requestParser.parse(reparsedReq); - + // invoke the core logic responseObj = invoker.verifyXMLSignature(requestObj); // map back to XML response[0] = responseBuilder.build(responseObj).getDocumentElement(); - + // save response in transaction context.setResponse(response[0]); - - } catch (MOAException e) { - AxisFault fault = AxisFault.makeFault(e); - fault.setFaultDetail(new Element[] { e.toErrorResponse()}); - Logger.debug("Anfrage zur Signaturpruefung wurde nicht erfolgreich beendet:" - + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); + } catch (final MOAException e) { + final AxisFault fault = AxisFault.makeFault(e); + fault.setFaultDetail(new Element[] { e.toErrorResponse() }); + Logger.debug("Anfrage zur Signaturpruefung wurde nicht erfolgreich beendet:" + + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); throw fault; - } catch (Throwable t) { - MOASystemException e = new MOASystemException("2900", null, t); - AxisFault fault = AxisFault.makeFault(e); - fault.setFaultDetail(new Element[] { e.toErrorResponse()}); - Logger.debug("Anfrage zur Signaturpruefung wurde nicht erfolgreich beendet:" - + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); + } catch (final Throwable t) { + final MOASystemException e = new MOASystemException("2900", null, t); + final AxisFault fault = AxisFault.makeFault(e); + fault.setFaultDetail(new Element[] { e.toErrorResponse() }); + Logger.debug("Anfrage zur Signaturpruefung wurde nicht erfolgreich beendet:" + + System.getProperty("line.separator") + StreamUtils.getStackTraceAsString(e)); throw fault; } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/TSLClientStatusServlet.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/TSLClientStatusServlet.java index d763c44..3bf9a37 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/TSLClientStatusServlet.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/service/TSLClientStatusServlet.java @@ -10,72 +10,74 @@ import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import at.gv.egovernment.moa.sig.tsl.TslClientFactory; import at.gv.egovernment.moa.sig.tsl.engine.data.TSLProcessingResultElement; import at.gv.egovernment.moa.spss.server.monitoring.ServiceStatusContainer; -import at.gv.egovernment.moa.spss.tsl.TSLServiceFactory; public class TSLClientStatusServlet extends HttpServlet { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - - public static final String STATUS_RESP = "'{'\"EUTSLStatus\":\"{0}\", \"EUTSLStatusMsg\":\"{1}\"{2}'}'"; - public static final String DETAIL_INFO = ", \"Details\":'{'{0}'}'"; - //public static final String DETAIL_ENTRY = "\"{0}\":'{'\"verified\":\"{1}\", \"processed\":\"{2}\"'}'"; - public static final String DETAIL_ENTRY = "\"{0}\":'{'\"processed\":\"{2}\"'}'"; - - public void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - - if (ServiceStatusContainer.getStatus()) - response.setStatus(200); - else - response.setStatus(500); - - response.setContentType("application/json"); - PrintWriter out = response.getWriter(); - out.println(MessageFormat.format(STATUS_RESP, - new Object[] { - String.valueOf(ServiceStatusContainer.getStatus()), - ServiceStatusContainer.getStatusMsg(), - getTSLClientDetailInfos() - })); - out.flush(); - out.close(); - - } - - private String getTSLClientDetailInfos() { - String detailInfo = ""; - List tslDetailStatus = ServiceStatusContainer.getTslDetailStatus(); - if (tslDetailStatus != null) { - String detailElements = null; - - for (TSLProcessingResultElement el : tslDetailStatus) { - String entry = MessageFormat.format(DETAIL_ENTRY, - new Object[] { - el.getCountryCode(), - String.valueOf(el.isVerified()), - String.valueOf(el.isProcessed()) - }); - if (detailElements == null) - detailElements = entry; - else - detailElements += ", " + entry; - - } - - if (detailElements != null) - detailInfo = MessageFormat.format(DETAIL_INFO, - new Object[] { - detailElements - }); - } - - return detailInfo; - } + public static final String STATUS_RESP = "'{'\"EUTSLStatus\":\"{0}\", \"EUTSLStatusMsg\":\"{1}\"{2}'}'"; + public static final String DETAIL_INFO = ", \"Details\":'{'{0}'}'"; + // public static final String DETAIL_ENTRY = "\"{0}\":'{'\"verified\":\"{1}\", + // \"processed\":\"{2}\"'}'"; + public static final String DETAIL_ENTRY = "\"{0}\":'{'\"processed\":\"{2}\"'}'"; + + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + + if (ServiceStatusContainer.getStatus()) { + response.setStatus(200); + } else { + response.setStatus(500); + } + + response.setContentType("application/json"); + final PrintWriter out = response.getWriter(); + out.println(MessageFormat.format(STATUS_RESP, + new Object[] { + String.valueOf(ServiceStatusContainer.getStatus()), + ServiceStatusContainer.getStatusMsg(), + getTSLClientDetailInfos() + })); + out.flush(); + out.close(); + + } + + private String getTSLClientDetailInfos() { + String detailInfo = ""; + final List tslDetailStatus = ServiceStatusContainer.getTslDetailStatus(); + if (tslDetailStatus != null) { + String detailElements = null; + + for (final TSLProcessingResultElement el : tslDetailStatus) { + final String entry = MessageFormat.format(DETAIL_ENTRY, + new Object[] { + el.getCountryCode(), + String.valueOf(el.isVerified()), + String.valueOf(el.isProcessed()) + }); + if (detailElements == null) { + detailElements = entry; + } else { + detailElements += ", " + entry; + } + + } + + if (detailElements != null) { + detailInfo = MessageFormat.format(DETAIL_INFO, + new Object[] { + detailElements + }); + } + } + + return detailInfo; + } } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/CMSCreateSignatureBinding.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/CMSCreateSignatureBinding.java index c6a1b01..264abd5 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/CMSCreateSignatureBinding.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/CMSCreateSignatureBinding.java @@ -6,9 +6,9 @@ import at.gv.egovernment.moa.spss.MOAApplicationException; import at.gv.egovernment.moa.spss.api.cmssign.CreateCMSSignatureResponse; public interface CMSCreateSignatureBinding { - public at.gv.egovernment.moa.spss.api.cmssign.CreateCMSSignatureRequest buildCMSRequest( - CreateCMSSignatureRequest createCMSSignatureRequest) throws MOAApplicationException; + at.gv.egovernment.moa.spss.api.cmssign.CreateCMSSignatureRequest buildCMSRequest( + CreateCMSSignatureRequest createCMSSignatureRequest) throws MOAApplicationException; - public CreateCMSSignatureResponseType buildCMSResponse(CreateCMSSignatureResponse response) - throws MOAApplicationException; + CreateCMSSignatureResponseType buildCMSResponse(CreateCMSSignatureResponse response) + throws MOAApplicationException; } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/CMSVerifySignatureBinding.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/CMSVerifySignatureBinding.java index d878b26..02a838c 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/CMSVerifySignatureBinding.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/CMSVerifySignatureBinding.java @@ -8,16 +8,16 @@ import at.gv.egovernment.moa.spss.MOAApplicationException; import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureResponse; public interface CMSVerifySignatureBinding { - public at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureRequest buildCMSRequest( - VerifyCMSSignatureRequest verifyCMSSignatureRequest) throws MOAApplicationException; + at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureRequest buildCMSRequest( + VerifyCMSSignatureRequest verifyCMSSignatureRequest) throws MOAApplicationException; + + at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureRequest buildPDFRequest( + VerifyPDFSignatureRequest verifyPDFSignatureRequest) throws MOAApplicationException; + + VerifyCMSSignatureResponseType buildCMSResponse(VerifyCMSSignatureResponse response) + throws MOAApplicationException; + + VerifyPDFSignatureResponseType buildPDFResponse(VerifyCMSSignatureResponse response) + throws MOAApplicationException; - public at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureRequest buildPDFRequest( - VerifyPDFSignatureRequest verifyPDFSignatureRequest) throws MOAApplicationException; - - public VerifyCMSSignatureResponseType buildCMSResponse(VerifyCMSSignatureResponse response) - throws MOAApplicationException; - - public VerifyPDFSignatureResponseType buildPDFResponse(VerifyCMSSignatureResponse response) - throws MOAApplicationException; - } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/PDFCreateSignatureBinding.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/PDFCreateSignatureBinding.java index bb670b7..b5aae78 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/PDFCreateSignatureBinding.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/PDFCreateSignatureBinding.java @@ -7,9 +7,9 @@ import at.gv.egovernment.moa.spss.server.xmlbind.CreatePDFRequest; import at.gv.egovernment.moa.spss.server.xmlbind.CreatePDFRespone; public interface PDFCreateSignatureBinding { - public CreatePDFRequest buildPDFRequest( - CreatePDFSignatureRequest createCMSSignatureRequest) throws MOAApplicationException; + CreatePDFRequest buildPDFRequest( + CreatePDFSignatureRequest createCMSSignatureRequest) throws MOAApplicationException; - public CreatePDFSignatureResponseType buildPDFResponse(CreatePDFRespone response) - throws MOAApplicationException; + CreatePDFSignatureResponseType buildPDFResponse(CreatePDFRespone response) + throws MOAApplicationException; } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/SignatureCreationService.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/SignatureCreationService.java index ccfc3fc..bf06ff6 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/SignatureCreationService.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/SignatureCreationService.java @@ -4,21 +4,29 @@ import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; -@WebService(name = "SignatureCreationService", targetNamespace = "http://reference.e-government.gv.at/namespace/moa/20151109#") +@WebService(name = "SignatureCreationService", + targetNamespace = "http://reference.e-government.gv.at/namespace/moa/20151109#") public interface SignatureCreationService { - @WebMethod(action = "XMLSignatureCreate", operationName = "XMLSignatureCreate") - public at.gv.egiz.moasig.CreateXMLSignatureResponseType createXMLSignature( - @WebParam(name = "CreateXMLSignatureRequest") at.gv.egiz.moasig.CreateXMLSignatureRequest createXMLSignatureRequest) - throws Exception; - - @WebMethod(action = "CMSSignatureCreate", operationName = "CMSSignatureCreate") - public at.gv.egiz.moasig.CreateCMSSignatureResponseType createCMSSignature( - @WebParam(name = "CreateCMSSignatureRequest") at.gv.egiz.moasig.CreateCMSSignatureRequest createCMSSignatureRequest) - throws Exception; - - /*@WebMethod(action = "PDFSignatureCreate", operationName = "PDFSignatureCreate") - public at.gv.egiz.moasig.CreatePDFSignatureResponseType createPDFSignature( - @WebParam(name = "CreatePDFSignatureRequest") at.gv.egiz.moasig.CreatePDFSignatureRequest createPDFSignatureRequest) - throws Exception;*/ + @WebMethod(action = "XMLSignatureCreate", operationName = "XMLSignatureCreate") + at.gv.egiz.moasig.CreateXMLSignatureResponseType createXMLSignature( + @WebParam( + name = "CreateXMLSignatureRequest") at.gv.egiz.moasig.CreateXMLSignatureRequest createXMLSignatureRequest) + throws Exception; + + @WebMethod(action = "CMSSignatureCreate", operationName = "CMSSignatureCreate") + at.gv.egiz.moasig.CreateCMSSignatureResponseType createCMSSignature( + @WebParam( + name = "CreateCMSSignatureRequest") at.gv.egiz.moasig.CreateCMSSignatureRequest createCMSSignatureRequest) + throws Exception; + + /* + * @WebMethod(action = "PDFSignatureCreate", operationName = + * "PDFSignatureCreate") public at.gv.egiz.moasig.CreatePDFSignatureResponseType + * createPDFSignature( + * + * @WebParam(name = "CreatePDFSignatureRequest") + * at.gv.egiz.moasig.CreatePDFSignatureRequest createPDFSignatureRequest) throws + * Exception; + */ } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/SignatureVerificationService.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/SignatureVerificationService.java index 65de3bf..b2ee799 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/SignatureVerificationService.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/SignatureVerificationService.java @@ -4,22 +4,26 @@ import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; -@WebService(name = "SignatureVerificationService", targetNamespace = "http://reference.e-government.gv.at/namespace/moa/20151109#") +@WebService(name = "SignatureVerificationService", + targetNamespace = "http://reference.e-government.gv.at/namespace/moa/20151109#") public interface SignatureVerificationService { - @WebMethod(action = "XMLSignatureVerify", operationName = "XMLSignatureVerify") - public at.gv.egiz.moasig.VerifyXMLSignatureResponseType verifyXMLSignature( - @WebParam(name = "VerifyXMLSignatureRequest") at.gv.egiz.moasig.VerifyXMLSignatureRequest verifyXMLSignatureRequest) - throws Exception; - - @WebMethod(action = "CMSSignatureVerify", operationName = "CMSSignatureVerify") - public at.gv.egiz.moasig.VerifyCMSSignatureResponseType verifyCMSSignature( - @WebParam(name = "VerifyCMSSignatureRequest") at.gv.egiz.moasig.VerifyCMSSignatureRequest verifyCMSSignatureRequest) - throws Exception; - - @WebMethod(action = "PDFSignatureVerify", operationName = "PDFSignatureVerify") - public at.gv.egiz.moasig.VerifyPDFSignatureResponseType verifyPDFSignature( - @WebParam(name = "VerifyPDFSignatureRequest") at.gv.egiz.moasig.VerifyPDFSignatureRequest verifyPDFSignatureRequest) - throws Exception; - + @WebMethod(action = "XMLSignatureVerify", operationName = "XMLSignatureVerify") + at.gv.egiz.moasig.VerifyXMLSignatureResponseType verifyXMLSignature( + @WebParam( + name = "VerifyXMLSignatureRequest") at.gv.egiz.moasig.VerifyXMLSignatureRequest verifyXMLSignatureRequest) + throws Exception; + + @WebMethod(action = "CMSSignatureVerify", operationName = "CMSSignatureVerify") + at.gv.egiz.moasig.VerifyCMSSignatureResponseType verifyCMSSignature( + @WebParam( + name = "VerifyCMSSignatureRequest") at.gv.egiz.moasig.VerifyCMSSignatureRequest verifyCMSSignatureRequest) + throws Exception; + + @WebMethod(action = "PDFSignatureVerify", operationName = "PDFSignatureVerify") + at.gv.egiz.moasig.VerifyPDFSignatureResponseType verifyPDFSignature( + @WebParam( + name = "VerifyPDFSignatureRequest") at.gv.egiz.moasig.VerifyPDFSignatureRequest verifyPDFSignatureRequest) + throws Exception; + } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/XMLCreateSignatureBinding.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/XMLCreateSignatureBinding.java index 149095b..f70f120 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/XMLCreateSignatureBinding.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/XMLCreateSignatureBinding.java @@ -6,9 +6,9 @@ import at.gv.egovernment.moa.spss.MOAApplicationException; import at.gv.egovernment.moa.spss.api.xmlsign.CreateXMLSignatureResponse; public interface XMLCreateSignatureBinding { - public at.gv.egovernment.moa.spss.api.xmlsign.CreateXMLSignatureRequest buildXMLRequest( - CreateXMLSignatureRequest createXMLSignatureRequest) throws MOAApplicationException; + at.gv.egovernment.moa.spss.api.xmlsign.CreateXMLSignatureRequest buildXMLRequest( + CreateXMLSignatureRequest createXMLSignatureRequest) throws MOAApplicationException; - public CreateXMLSignatureResponseType buildXMLResponse(CreateXMLSignatureResponse response) - throws MOAApplicationException; + CreateXMLSignatureResponseType buildXMLResponse(CreateXMLSignatureResponse response) + throws MOAApplicationException; } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/XMLVerifySignatureBinding.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/XMLVerifySignatureBinding.java index 4a6d110..130cf81 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/XMLVerifySignatureBinding.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/webservice/XMLVerifySignatureBinding.java @@ -6,9 +6,9 @@ import at.gv.egovernment.moa.spss.MOAApplicationException; import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureResponse;; public interface XMLVerifySignatureBinding { - public at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureRequest buildXMLRequest( - VerifyXMLSignatureRequest verifyXMLSignatureRequest) throws MOAApplicationException; + at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureRequest buildXMLRequest( + VerifyXMLSignatureRequest verifyXMLSignatureRequest) throws MOAApplicationException; - public VerifyXMLSignatureResponseType buildXMLResponse(VerifyXMLSignatureResponse response) - throws MOAApplicationException; + VerifyXMLSignatureResponseType buildXMLResponse(VerifyXMLSignatureResponse response) + throws MOAApplicationException; } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/CreatePDFRequest.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/CreatePDFRequest.java index 110665c..5628e4b 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/CreatePDFRequest.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/CreatePDFRequest.java @@ -4,18 +4,18 @@ import java.util.ArrayList; import java.util.List; public class CreatePDFRequest { - private String keyIdentifier; - private List signatureInfoList = new ArrayList(); - - public CreatePDFRequest(String keyIdentifier) { - this.keyIdentifier = keyIdentifier; - } + private final String keyIdentifier; + private final List signatureInfoList = new ArrayList<>(); - public synchronized String getKeyIdentifier() { - return keyIdentifier; - } + public CreatePDFRequest(String keyIdentifier) { + this.keyIdentifier = keyIdentifier; + } - public synchronized List getSignatureInfoList() { - return signatureInfoList; - } + public synchronized String getKeyIdentifier() { + return keyIdentifier; + } + + public synchronized List getSignatureInfoList() { + return signatureInfoList; + } } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/CreatePDFRespone.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/CreatePDFRespone.java index ef7e832..8cabc78 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/CreatePDFRespone.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/CreatePDFRespone.java @@ -4,12 +4,12 @@ import java.util.ArrayList; import java.util.List; public class CreatePDFRespone { - private List signatureInfoList = new ArrayList(); - - public CreatePDFRespone() { - } - - public synchronized List getSignatureInfoList() { - return signatureInfoList; - } + private final List signatureInfoList = new ArrayList<>(); + + public CreatePDFRespone() { + } + + public synchronized List getSignatureInfoList() { + return signatureInfoList; + } } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/CreatePDFSignatureRequestParser.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/CreatePDFSignatureRequestParser.java index c6b2126..e483db8 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/CreatePDFSignatureRequestParser.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/CreatePDFSignatureRequestParser.java @@ -37,106 +37,99 @@ import at.gv.egovernment.moaspss.util.XPathUtils; /** * A parser to parse CreateCMSSignatureRequest DOM trees into * CreateCMSSignatureRequest API objects. - * + * * @author Patrick Peck * @version $Id$ */ public class CreatePDFSignatureRequestParser { - // - // XPath expresssions to select elements in the CreateCMSSignatureRequest - // - private static final String MOA = Constants.MOA_PREFIX + ":"; - private static final String KEY_IDENTIFIER_XPATH = "/" + MOA + "CreatePDFSignatureRequest/" + MOA + "KeyIdentifier"; - private static final String SINGLE_SIGNATURE_INFO_XPATH = "/" + MOA + "CreatePDFSignatureRequest/" + MOA - + "SingleSignatureInfo"; - private static final String SIGNATURE_PROFILE_XPATH = MOA + "SignatureProfile"; - private static final String SIGNATURE_POSITION_XPATH = MOA + "SignaturePosition"; - private static final String SIGNATURE_ID_XPATH = MOA + "SignatureID"; - - private static final String PDF_DOCUMENT_XPATH = MOA + "PDFDocument"; - - /** - * Create a new CreateCMSSignatureRequestParser. - */ - public CreatePDFSignatureRequestParser() { - } - - /** - * Parse a CreateCMSSignatureRequest DOM element, as defined by - * the MOA schema. - * - * @param requestElem - * The CreateCMSSignatureRequest to parse. The - * request must have been successfully parsed against the schema - * for this method to succeed. - * @return A CreateCMSSignatureRequest API object containing - * the data from the DOM element. - * @throws MOAApplicationException - * An error occurred parsing the request. - */ - public CreatePDFRequest parse(Element requestElem) throws MOAApplicationException { - - String keyIdentifier = XPathUtils.getElementValue(requestElem, KEY_IDENTIFIER_XPATH, null); - - CreatePDFRequest createPDFRequest = new CreatePDFRequest(keyIdentifier); - parseSingleSignatureInfos(requestElem, createPDFRequest); - - return createPDFRequest; - } - - /** - * Parse all SingleSignatureInfo elements of the - * CreateCMSSignatureRequest. - * - * @param requestElem - * The CreateCMSSignatureRequest to parse. - * @return A List of SingleSignatureInfo API - * objects. - * @throws MOAApplicationException - * An error occurred parsing on of the - * SingleSignatureInfo elements. - */ - private void parseSingleSignatureInfos(Element requestElem, CreatePDFRequest createPDFRequest) - throws MOAApplicationException { - - NodeIterator sigInfoElems = XPathUtils.selectNodeIterator(requestElem, SINGLE_SIGNATURE_INFO_XPATH); - Element sigInfoElem; - - while ((sigInfoElem = (Element) sigInfoElems.nextNode()) != null) { - createPDFRequest.getSignatureInfoList().add(parsePDFSignatureInfo(sigInfoElem)); - } - } - - /** - * Parse a SingleSignatureInfo DOM element. - * - * @param sigInfoElem - * The SingleSignatureInfo DOM element to parse. - * @return A SingleSignatureInfo API object containing the - * information of sigInfoElem. - * @throws MOAApplicationException - * An error occurred parsing the - * SingleSignatureInfo. - */ - private PDFSignatureInfo parsePDFSignatureInfo(Element sigInfoElem) throws MOAApplicationException { - - String signatureProfile = XPathUtils.getElementValue(sigInfoElem, SIGNATURE_PROFILE_XPATH, null); - String signaturePosition = XPathUtils.getElementValue(sigInfoElem, SIGNATURE_POSITION_XPATH, null); - String signatureID = XPathUtils.getElementValue(sigInfoElem, SIGNATURE_ID_XPATH, null); - - - Element base64ContentElem = (Element) XPathUtils.selectSingleNode(sigInfoElem, PDF_DOCUMENT_XPATH); - String base64Str = DOMUtils.getText(base64ContentElem); - try { - byte[] inputPDF = Base64Utils.decode(base64Str, true); - PDFSignatureInfo PDFSignatureInfo = new PDFSignatureInfo(inputPDF, - signatureProfile, signaturePosition, signatureID); - - return PDFSignatureInfo; - } catch (IOException e) { - throw new MOAApplicationException("2244", null, e); - } - - } + // + // XPath expresssions to select elements in the CreateCMSSignatureRequest + // + private static final String MOA = Constants.MOA_PREFIX + ":"; + private static final String KEY_IDENTIFIER_XPATH = "/" + MOA + "CreatePDFSignatureRequest/" + MOA + + "KeyIdentifier"; + private static final String SINGLE_SIGNATURE_INFO_XPATH = "/" + MOA + "CreatePDFSignatureRequest/" + MOA + + "SingleSignatureInfo"; + private static final String SIGNATURE_PROFILE_XPATH = MOA + "SignatureProfile"; + private static final String SIGNATURE_POSITION_XPATH = MOA + "SignaturePosition"; + private static final String SIGNATURE_ID_XPATH = MOA + "SignatureID"; + + private static final String PDF_DOCUMENT_XPATH = MOA + "PDFDocument"; + + /** + * Create a new CreateCMSSignatureRequestParser. + */ + public CreatePDFSignatureRequestParser() { + } + + /** + * Parse a CreateCMSSignatureRequest DOM element, as defined by the + * MOA schema. + * + * @param requestElem The CreateCMSSignatureRequest to parse. The + * request must have been successfully parsed against the + * schema for this method to succeed. + * @return A CreateCMSSignatureRequest API object containing the + * data from the DOM element. + * @throws MOAApplicationException An error occurred parsing the request. + */ + public CreatePDFRequest parse(Element requestElem) throws MOAApplicationException { + + final String keyIdentifier = XPathUtils.getElementValue(requestElem, KEY_IDENTIFIER_XPATH, null); + + final CreatePDFRequest createPDFRequest = new CreatePDFRequest(keyIdentifier); + parseSingleSignatureInfos(requestElem, createPDFRequest); + + return createPDFRequest; + } + + /** + * Parse all SingleSignatureInfo elements of the + * CreateCMSSignatureRequest. + * + * @param requestElem The CreateCMSSignatureRequest to parse. + * @return A List of SingleSignatureInfo API objects. + * @throws MOAApplicationException An error occurred parsing on of the + * SingleSignatureInfo elements. + */ + private void parseSingleSignatureInfos(Element requestElem, CreatePDFRequest createPDFRequest) + throws MOAApplicationException { + + final NodeIterator sigInfoElems = XPathUtils.selectNodeIterator(requestElem, SINGLE_SIGNATURE_INFO_XPATH); + Element sigInfoElem; + + while ((sigInfoElem = (Element) sigInfoElems.nextNode()) != null) { + createPDFRequest.getSignatureInfoList().add(parsePDFSignatureInfo(sigInfoElem)); + } + } + + /** + * Parse a SingleSignatureInfo DOM element. + * + * @param sigInfoElem The SingleSignatureInfo DOM element to parse. + * @return A SingleSignatureInfo API object containing the + * information of sigInfoElem. + * @throws MOAApplicationException An error occurred parsing the + * SingleSignatureInfo. + */ + private PDFSignatureInfo parsePDFSignatureInfo(Element sigInfoElem) throws MOAApplicationException { + + final String signatureProfile = XPathUtils.getElementValue(sigInfoElem, SIGNATURE_PROFILE_XPATH, null); + final String signaturePosition = XPathUtils.getElementValue(sigInfoElem, SIGNATURE_POSITION_XPATH, null); + final String signatureID = XPathUtils.getElementValue(sigInfoElem, SIGNATURE_ID_XPATH, null); + + final Element base64ContentElem = (Element) XPathUtils.selectSingleNode(sigInfoElem, PDF_DOCUMENT_XPATH); + final String base64Str = DOMUtils.getText(base64ContentElem); + try { + final byte[] inputPDF = Base64Utils.decode(base64Str, true); + final PDFSignatureInfo PDFSignatureInfo = new PDFSignatureInfo(inputPDF, + signatureProfile, signaturePosition, signatureID); + + return PDFSignatureInfo; + } catch (final IOException e) { + throw new MOAApplicationException("2244", null, e); + } + + } } \ No newline at end of file diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/CreatePDFSignatureResponseBuilder.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/CreatePDFSignatureResponseBuilder.java index bdb9a71..6f9880f 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/CreatePDFSignatureResponseBuilder.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/CreatePDFSignatureResponseBuilder.java @@ -39,117 +39,114 @@ import at.gv.egovernment.moaspss.util.Constants; /** * Convert a CreateCMSSignatureResponse API object into its XML * representation, according to the MOA XML schema. - * + * * @version $Id$ */ public class CreatePDFSignatureResponseBuilder { - private static final String MOA_NS_URI = Constants.MOA_NS_URI; - - private static final Logger logger = LoggerFactory.getLogger(CreatePDFSignatureResponseBuilder.class); - - /** The XML document containing the response element. */ - private Document responseDoc; - /** The response CreateCMSSignatureResponse DOM element. */ - private Element responseElem; - - /** - * Create a new CreateCMSSignatureResponseBuilder: - * - * @throws MOASystemException - * An error occurred setting up the resulting XML document. - */ - public CreatePDFSignatureResponseBuilder() throws MOASystemException { - responseDoc = ResponseBuilderUtils.createResponse("CreatePDFSignatureResponse"); - responseElem = responseDoc.getDocumentElement(); - } - - /** - * Build a document containing a CreateCMSSignatureResponse DOM - * element being the XML representation of the given - * CreateCMSSignatureResponse API object. - * - * @param response - * The CreateCMSSignatureResponse to convert to XML. - * @return A document containing the CreateCMSSignatureResponse - * DOM element. - */ - public Document build(CreatePDFRespone response) { - Iterator iter = response.getSignatureInfoList().iterator(); - - while (iter.hasNext()) { - SignedPDFInfo signedPDFInfo = iter.next(); - addPDFSignature(signedPDFInfo); - } - - return responseDoc; - } - - /** - * Add a CMSSignature element to the response. - * - * @param cmsSignatureResponse - * The content to put under the CMSSignature - * element. - */ - private void addPDFSignature(SignedPDFInfo signedPDFInfo) { - Element pdfSignature = responseDoc.createElementNS(MOA_NS_URI, "PDFSignature"); - - if(signedPDFInfo.getSignatureID() != null) { - Element signatureID = responseDoc.createElementNS(MOA_NS_URI, "SignatureID"); - signatureID.setTextContent(signedPDFInfo.getSignatureID()); - pdfSignature.appendChild(signatureID); - } - - switch (signedPDFInfo.getResponseType()) { - case SignedPDFInfo.SUCCESS_SIGNATURE: - pdfSignature.appendChild(addSuccessSignature(signedPDFInfo)); - break; - - default: - pdfSignature.appendChild(addErrorResponse(signedPDFInfo)); - break; - } - - responseElem.appendChild(pdfSignature); - } - - private Element addSuccessSignature(SignedPDFInfo signedPDFInfo) { - try { - String base64Value = Base64Utils.encode(signedPDFInfo.getPdfDocument()); - Element cmsSignature = responseDoc.createElementNS(MOA_NS_URI, "PDFSignature"); - cmsSignature.setTextContent(base64Value); - - return cmsSignature; - } catch (IOException e) { - logger.error("Failed to encode pdf signature", e); - signedPDFInfo.setErrorCode(2300); - signedPDFInfo.setErrorInfo("Failed to encode the signed document"); - return addErrorResponse(signedPDFInfo); - } - - - } - - /** - * Add a ErrorResponse element to the response. - * - * @param errorResponse - * The API object containing the information to put into the - * ErrorResponse DOM element. - */ - private Element addErrorResponse(SignedPDFInfo signedPDFInfo) { - Element errorElem = responseDoc.createElementNS(MOA_NS_URI, "ErrorResponse"); - Element errorCodeElem = responseDoc.createElementNS(MOA_NS_URI, "ErrorCode"); - Element infoElem = responseDoc.createElementNS(MOA_NS_URI, "Info"); - String errorCodeStr = Integer.toString(signedPDFInfo.getErrorCode()); - - errorCodeElem.appendChild(responseDoc.createTextNode(errorCodeStr)); - errorElem.appendChild(errorCodeElem); - infoElem.appendChild(responseDoc.createTextNode(signedPDFInfo.getErrorInfo())); - errorElem.appendChild(errorCodeElem); - errorElem.appendChild(infoElem); - - return errorElem; - } + private static final String MOA_NS_URI = Constants.MOA_NS_URI; + + private static final Logger logger = LoggerFactory.getLogger(CreatePDFSignatureResponseBuilder.class); + + /** The XML document containing the response element. */ + private final Document responseDoc; + /** The response CreateCMSSignatureResponse DOM element. */ + private final Element responseElem; + + /** + * Create a new CreateCMSSignatureResponseBuilder: + * + * @throws MOASystemException An error occurred setting up the resulting XML + * document. + */ + public CreatePDFSignatureResponseBuilder() throws MOASystemException { + responseDoc = ResponseBuilderUtils.createResponse("CreatePDFSignatureResponse"); + responseElem = responseDoc.getDocumentElement(); + } + + /** + * Build a document containing a CreateCMSSignatureResponse DOM + * element being the XML representation of the given + * CreateCMSSignatureResponse API object. + * + * @param response The CreateCMSSignatureResponse to convert to + * XML. + * @return A document containing the CreateCMSSignatureResponse DOM + * element. + */ + public Document build(CreatePDFRespone response) { + final Iterator iter = response.getSignatureInfoList().iterator(); + + while (iter.hasNext()) { + final SignedPDFInfo signedPDFInfo = iter.next(); + addPDFSignature(signedPDFInfo); + } + + return responseDoc; + } + + /** + * Add a CMSSignature element to the response. + * + * @param cmsSignatureResponse The content to put under the + * CMSSignature element. + */ + private void addPDFSignature(SignedPDFInfo signedPDFInfo) { + final Element pdfSignature = responseDoc.createElementNS(MOA_NS_URI, "PDFSignature"); + + if (signedPDFInfo.getSignatureID() != null) { + final Element signatureID = responseDoc.createElementNS(MOA_NS_URI, "SignatureID"); + signatureID.setTextContent(signedPDFInfo.getSignatureID()); + pdfSignature.appendChild(signatureID); + } + + switch (signedPDFInfo.getResponseType()) { + case SignedPDFInfo.SUCCESS_SIGNATURE: + pdfSignature.appendChild(addSuccessSignature(signedPDFInfo)); + break; + + default: + pdfSignature.appendChild(addErrorResponse(signedPDFInfo)); + break; + } + + responseElem.appendChild(pdfSignature); + } + + private Element addSuccessSignature(SignedPDFInfo signedPDFInfo) { + try { + final String base64Value = Base64Utils.encode(signedPDFInfo.getPdfDocument()); + final Element cmsSignature = responseDoc.createElementNS(MOA_NS_URI, "PDFSignature"); + cmsSignature.setTextContent(base64Value); + + return cmsSignature; + } catch (final IOException e) { + logger.error("Failed to encode pdf signature", e); + signedPDFInfo.setErrorCode(2300); + signedPDFInfo.setErrorInfo("Failed to encode the signed document"); + return addErrorResponse(signedPDFInfo); + } + + } + + /** + * Add a ErrorResponse element to the response. + * + * @param errorResponse The API object containing the information to put into + * the ErrorResponse DOM element. + */ + private Element addErrorResponse(SignedPDFInfo signedPDFInfo) { + final Element errorElem = responseDoc.createElementNS(MOA_NS_URI, "ErrorResponse"); + final Element errorCodeElem = responseDoc.createElementNS(MOA_NS_URI, "ErrorCode"); + final Element infoElem = responseDoc.createElementNS(MOA_NS_URI, "Info"); + final String errorCodeStr = Integer.toString(signedPDFInfo.getErrorCode()); + + errorCodeElem.appendChild(responseDoc.createTextNode(errorCodeStr)); + errorElem.appendChild(errorCodeElem); + infoElem.appendChild(responseDoc.createTextNode(signedPDFInfo.getErrorInfo())); + errorElem.appendChild(errorCodeElem); + errorElem.appendChild(infoElem); + + return errorElem; + } } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/PDFSignatureInfo.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/PDFSignatureInfo.java index fd2be7c..3fe8e82 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/PDFSignatureInfo.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/PDFSignatureInfo.java @@ -1,33 +1,33 @@ package at.gv.egovernment.moa.spss.server.xmlbind; public class PDFSignatureInfo { - private String signatureProfile = null; - private String signaturePosition = null; - private String signatureID = null; - private byte[] pdfDocument = null; - - public PDFSignatureInfo(byte[] pdfDocument, - String signatureProfile, String signaturePosition, - String signatureID) { - this.pdfDocument = pdfDocument; - this.signatureProfile = signatureProfile; - this.signaturePosition = signaturePosition; - this.signatureID = signatureID; - } + private String signatureProfile = null; + private String signaturePosition = null; + private String signatureID = null; + private byte[] pdfDocument = null; - public synchronized String getSignatureProfile() { - return signatureProfile; - } + public PDFSignatureInfo(byte[] pdfDocument, + String signatureProfile, String signaturePosition, + String signatureID) { + this.pdfDocument = pdfDocument; + this.signatureProfile = signatureProfile; + this.signaturePosition = signaturePosition; + this.signatureID = signatureID; + } - public synchronized String getSignaturePosition() { - return signaturePosition; - } + public synchronized String getSignatureProfile() { + return signatureProfile; + } - public synchronized String getSignatureID() { - return signatureID; - } + public synchronized String getSignaturePosition() { + return signaturePosition; + } - public synchronized byte[] getPdfDocument() { - return pdfDocument; - } + public synchronized String getSignatureID() { + return signatureID; + } + + public synchronized byte[] getPdfDocument() { + return pdfDocument; + } } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/SignedPDFInfo.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/SignedPDFInfo.java index a950006..b6409f1 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/SignedPDFInfo.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/SignedPDFInfo.java @@ -1,53 +1,53 @@ package at.gv.egovernment.moa.spss.server.xmlbind; public class SignedPDFInfo { - - public static final int SUCCESS_SIGNATURE = 0; - public static final int ERROR_RESPONSE = 1; - - private String signatureID = null; - private byte[] pdfDocument = null; - private int responseType = ERROR_RESPONSE; - private int errorCode = 0; - private String errorInfo = null; - - public SignedPDFInfo(String signatureID) { - this.signatureID = signatureID; - } - - public synchronized void setPdfDocument(byte[] pdfDocument) { - this.pdfDocument = pdfDocument; - } - - public synchronized String getSignatureID() { - return signatureID; - } - - public synchronized byte[] getPdfDocument() { - return pdfDocument; - } - - public synchronized void setResponseType(int responseType) { - this.responseType = responseType; - } - - public int getResponseType() { - return this.responseType; - } - - public synchronized int getErrorCode() { - return errorCode; - } - - public synchronized void setErrorCode(int errorCode) { - this.errorCode = errorCode; - } - - public synchronized String getErrorInfo() { - return errorInfo; - } - - public synchronized void setErrorInfo(String errorInfo) { - this.errorInfo = errorInfo; - } + + public static final int SUCCESS_SIGNATURE = 0; + public static final int ERROR_RESPONSE = 1; + + private String signatureID = null; + private byte[] pdfDocument = null; + private int responseType = ERROR_RESPONSE; + private int errorCode = 0; + private String errorInfo = null; + + public SignedPDFInfo(String signatureID) { + this.signatureID = signatureID; + } + + public synchronized void setPdfDocument(byte[] pdfDocument) { + this.pdfDocument = pdfDocument; + } + + public synchronized String getSignatureID() { + return signatureID; + } + + public synchronized byte[] getPdfDocument() { + return pdfDocument; + } + + public synchronized void setResponseType(int responseType) { + this.responseType = responseType; + } + + public int getResponseType() { + return this.responseType; + } + + public synchronized int getErrorCode() { + return errorCode; + } + + public synchronized void setErrorCode(int errorCode) { + this.errorCode = errorCode; + } + + public synchronized String getErrorInfo() { + return errorInfo; + } + + public synchronized void setErrorInfo(String errorInfo) { + this.errorInfo = errorInfo; + } } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/VerifyPDFRequest.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/VerifyPDFRequest.java index c9ca89d..59c8c94 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/VerifyPDFRequest.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/VerifyPDFRequest.java @@ -3,34 +3,34 @@ package at.gv.egovernment.moa.spss.server.xmlbind; import java.util.Date; public class VerifyPDFRequest { - private Date dateTime; - private byte[] signedPDF; - private String trustProfileID; - - public VerifyPDFRequest() { - } - - public synchronized Date getDateTime() { - return dateTime; - } - - public synchronized void setDateTime(Date dateTime) { - this.dateTime = dateTime; - } - - public synchronized byte[] getSignedPDF() { - return signedPDF; - } - - public synchronized void setSignedPDF(byte[] signedPDF) { - this.signedPDF = signedPDF; - } - - public synchronized String getTrustProfileID() { - return trustProfileID; - } - - public synchronized void setTrustProfileID(String trustProfileID) { - this.trustProfileID = trustProfileID; - } + private Date dateTime; + private byte[] signedPDF; + private String trustProfileID; + + public VerifyPDFRequest() { + } + + public synchronized Date getDateTime() { + return dateTime; + } + + public synchronized void setDateTime(Date dateTime) { + this.dateTime = dateTime; + } + + public synchronized byte[] getSignedPDF() { + return signedPDF; + } + + public synchronized void setSignedPDF(byte[] signedPDF) { + this.signedPDF = signedPDF; + } + + public synchronized String getTrustProfileID() { + return trustProfileID; + } + + public synchronized void setTrustProfileID(String trustProfileID) { + this.trustProfileID = trustProfileID; + } } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/VerifyPDFRequestParser.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/VerifyPDFRequestParser.java index 66761e4..0581595 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/VerifyPDFRequestParser.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/VerifyPDFRequestParser.java @@ -14,47 +14,47 @@ import at.gv.egovernment.moaspss.util.XPathUtils; public class VerifyPDFRequestParser { - // - // XPath expressions for selecting parts of the DOM message - // - private static final String MOA = Constants.MOA_PREFIX + ":"; - private static final String DATE_TIME_XPATH = MOA + "DateTime"; - private static final String PDF_SIGNATURE_XPATH = MOA + "PDFSignature"; - private static final String TRUST_PROFILE_ID_XPATH = MOA + "TrustProfileID"; - - public VerifyPDFRequest parse(Element requestElem) throws MOAApplicationException { - - VerifyPDFRequest verifyPDFRequest = new VerifyPDFRequest(); - - Date dateTime = RequestParserUtils.parseDateTime(requestElem, DATE_TIME_XPATH); - byte[] signedPDF = null; - try { - signedPDF = parsePDF(requestElem); - } catch (IOException e) { - throw new MOAApplicationException("Failed to extract signed pdf data", null, e); - } - String trustProfileID = XPathUtils.getElementValue(requestElem, TRUST_PROFILE_ID_XPATH, null); - verifyPDFRequest.setDateTime(dateTime); - verifyPDFRequest.setSignedPDF(signedPDF); - verifyPDFRequest.setTrustProfileID(trustProfileID); - - return verifyPDFRequest; - } - - /** - * Parse the content contained in a CMSContentBaseType kind of - * DOM element. - * - * @param contentElem - * The CMSContentBaseType kind of element to parse. - * @return A CMSDataObject API object containing the data from - * the given DOM element. - * @throws IOException - */ - private byte[] parsePDF(Element contentElem) throws IOException { - Element base64ContentElem = (Element) XPathUtils.selectSingleNode(contentElem, PDF_SIGNATURE_XPATH); - - String base64Str = DOMUtils.getText(base64ContentElem); - return Base64Utils.decode(base64Str, true); - } + // + // XPath expressions for selecting parts of the DOM message + // + private static final String MOA = Constants.MOA_PREFIX + ":"; + private static final String DATE_TIME_XPATH = MOA + "DateTime"; + private static final String PDF_SIGNATURE_XPATH = MOA + "PDFSignature"; + private static final String TRUST_PROFILE_ID_XPATH = MOA + "TrustProfileID"; + + public VerifyPDFRequest parse(Element requestElem) throws MOAApplicationException { + + final VerifyPDFRequest verifyPDFRequest = new VerifyPDFRequest(); + + final Date dateTime = RequestParserUtils.parseDateTime(requestElem, DATE_TIME_XPATH); + byte[] signedPDF = null; + try { + signedPDF = parsePDF(requestElem); + } catch (final IOException e) { + throw new MOAApplicationException("Failed to extract signed pdf data", null, e); + } + final String trustProfileID = XPathUtils.getElementValue(requestElem, TRUST_PROFILE_ID_XPATH, null); + verifyPDFRequest.setDateTime(dateTime); + verifyPDFRequest.setSignedPDF(signedPDF); + verifyPDFRequest.setTrustProfileID(trustProfileID); + + return verifyPDFRequest; + } + + /** + * Parse the content contained in a CMSContentBaseType kind of DOM + * element. + * + * @param contentElem The CMSContentBaseType kind of element to + * parse. + * @return A CMSDataObject API object containing the data from the + * given DOM element. + * @throws IOException + */ + private byte[] parsePDF(Element contentElem) throws IOException { + final Element base64ContentElem = (Element) XPathUtils.selectSingleNode(contentElem, PDF_SIGNATURE_XPATH); + + final String base64Str = DOMUtils.getText(base64ContentElem); + return Base64Utils.decode(base64Str, true); + } } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/VerifyPDFResponse.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/VerifyPDFResponse.java index c162529..61304b0 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/VerifyPDFResponse.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/VerifyPDFResponse.java @@ -1,20 +1,17 @@ package at.gv.egovernment.moa.spss.server.xmlbind; -import java.util.List; - //import at.gv.egiz.pdfas.lib.api.verify.VerifyResult; public class VerifyPDFResponse { - /*private List verificationResults = null; - - public VerifyPDFResponse() { - } - - public synchronized List getVerificationResults() { - return verificationResults; - } - - public synchronized void setVerificationResults(List verificationResults) { - this.verificationResults = verificationResults; - }*/ + /* + * private List verificationResults = null; + * + * public VerifyPDFResponse() { } + * + * public synchronized List getVerificationResults() { return + * verificationResults; } + * + * public synchronized void setVerificationResults(List + * verificationResults) { this.verificationResults = verificationResults; } + */ } diff --git a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/VerifyPDFResponseBuilder.java b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/VerifyPDFResponseBuilder.java index cb3c66b..b9117e9 100644 --- a/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/VerifyPDFResponseBuilder.java +++ b/moaSig/moa-sig/src/main/java/at/gv/egovernment/moa/spss/server/xmlbind/VerifyPDFResponseBuilder.java @@ -1,110 +1,87 @@ package at.gv.egovernment.moa.spss.server.xmlbind; -import java.util.Iterator; - import org.w3c.dom.Document; import org.w3c.dom.Element; -//import at.gv.egiz.pdfas.lib.api.verify.VerifyResult; -import at.gv.egovernment.moa.spss.MOAApplicationException; -import at.gv.egovernment.moa.spss.MOAException; import at.gv.egovernment.moa.spss.MOASystemException; import at.gv.egovernment.moa.spss.api.xmlbind.ResponseBuilderUtils; -import at.gv.egovernment.moa.spss.server.pdfas.ExtendedVerifyResult; import at.gv.egovernment.moaspss.util.Constants; public class VerifyPDFResponseBuilder { - private static final String MOA_NS_URI = Constants.MOA_NS_URI; - - //private static final Logger logger = LoggerFactory.getLogger(VerifyPDFResponseBuilder.class); - - /** The XML document containing the response element. */ - private Document responseDoc; - /** The response CreateCMSSignatureResponse DOM element. */ - private Element responseElem; - - /** - * Create a new CreateCMSSignatureResponseBuilder: - * - * @throws MOASystemException - * An error occurred setting up the resulting XML document. - */ - public VerifyPDFResponseBuilder() throws MOASystemException { - responseDoc = ResponseBuilderUtils.createResponse("VerifyPDFSignatureResponse"); - responseElem = responseDoc.getDocumentElement(); - } - - /** - * Build a document containing a CreateCMSSignatureResponse DOM - * element being the XML representation of the given - * CreateCMSSignatureResponse API object. - * - * @param response - * The CreateCMSSignatureResponse to convert to XML. - * @return A document containing the CreateCMSSignatureResponse - * DOM element. - */ - /*public Document build(VerifyPDFResponse response) throws MOAException { - if(response.getVerificationResults() == null) { - throw new MOAApplicationException("No verification results available", null); - } - Iterator iter = response.getVerificationResults().iterator(); + private static final String MOA_NS_URI = Constants.MOA_NS_URI; - while (iter.hasNext()) { - VerifyResult verifyResult = iter.next(); - addVerifyResult(verifyResult); - } + // private static final Logger logger = + // LoggerFactory.getLogger(VerifyPDFResponseBuilder.class); - return responseDoc; - } - - private void addVerifyResult(VerifyResult verifyResult) throws MOAApplicationException { - Element pdfSignature = responseDoc.createElementNS(MOA_NS_URI, "SignatureResult"); - - - String qcSource = null; - String publicAuthorityID = null; - String sscdSource = null; - boolean isPublicAuthority = false; - boolean isSSCD = false; - String issureCountryCode = null; - - if(verifyResult instanceof ExtendedVerifyResult) { - ExtendedVerifyResult extendedVerifyResult = (ExtendedVerifyResult)verifyResult; - - qcSource = extendedVerifyResult.getQcSource(); - publicAuthorityID = extendedVerifyResult.getPublicAuthorityID(); - sscdSource = extendedVerifyResult.getQcSource(); - issureCountryCode = extendedVerifyResult.getIssureCountryCode(); - - isPublicAuthority = extendedVerifyResult.isPublicAuthority(); - isSSCD = extendedVerifyResult.isSSCD(); - } - - ResponseBuilderUtils.addSignerInfo(responseDoc, pdfSignature, - verifyResult.getSignerCertificate(), - verifyResult.isQualifiedCertificate(), - qcSource, - isPublicAuthority, - publicAuthorityID, - isSSCD, - sscdSource, - issureCountryCode); - - ResponseBuilderUtils.addCodeInfoElement( - responseDoc, - pdfSignature, - "SignatureCheck", - verifyResult.getValueCheckCode().getCode(), - (String)null); + /** The XML document containing the response element. */ + private final Document responseDoc; + /** The response CreateCMSSignatureResponse DOM element. */ + private final Element responseElem; - ResponseBuilderUtils.addCodeInfoElement( - responseDoc, - pdfSignature, - "CertificateCheck", - verifyResult.getCertificateCheck().getCode(), - (String)null); + /** + * Create a new CreateCMSSignatureResponseBuilder: + * + * @throws MOASystemException An error occurred setting up the resulting XML + * document. + */ + public VerifyPDFResponseBuilder() throws MOASystemException { + responseDoc = ResponseBuilderUtils.createResponse("VerifyPDFSignatureResponse"); + responseElem = responseDoc.getDocumentElement(); + } - responseElem.appendChild(pdfSignature); - }*/ + /** + * Build a document containing a CreateCMSSignatureResponse DOM + * element being the XML representation of the given + * CreateCMSSignatureResponse API object. + * + * @param response The CreateCMSSignatureResponse to convert to + * XML. + * @return A document containing the CreateCMSSignatureResponse DOM + * element. + */ + /* + * public Document build(VerifyPDFResponse response) throws MOAException { + * if(response.getVerificationResults() == null) { throw new + * MOAApplicationException("No verification results available", null); } + * Iterator iter = response.getVerificationResults().iterator(); + * + * while (iter.hasNext()) { VerifyResult verifyResult = iter.next(); + * addVerifyResult(verifyResult); } + * + * return responseDoc; } + * + * private void addVerifyResult(VerifyResult verifyResult) throws + * MOAApplicationException { Element pdfSignature = + * responseDoc.createElementNS(MOA_NS_URI, "SignatureResult"); + * + * + * String qcSource = null; String publicAuthorityID = null; String sscdSource = + * null; boolean isPublicAuthority = false; boolean isSSCD = false; String + * issureCountryCode = null; + * + * if(verifyResult instanceof ExtendedVerifyResult) { ExtendedVerifyResult + * extendedVerifyResult = (ExtendedVerifyResult)verifyResult; + * + * qcSource = extendedVerifyResult.getQcSource(); publicAuthorityID = + * extendedVerifyResult.getPublicAuthorityID(); sscdSource = + * extendedVerifyResult.getQcSource(); issureCountryCode = + * extendedVerifyResult.getIssureCountryCode(); + * + * isPublicAuthority = extendedVerifyResult.isPublicAuthority(); isSSCD = + * extendedVerifyResult.isSSCD(); } + * + * ResponseBuilderUtils.addSignerInfo(responseDoc, pdfSignature, + * verifyResult.getSignerCertificate(), verifyResult.isQualifiedCertificate(), + * qcSource, isPublicAuthority, publicAuthorityID, isSSCD, sscdSource, + * issureCountryCode); + * + * ResponseBuilderUtils.addCodeInfoElement( responseDoc, pdfSignature, + * "SignatureCheck", verifyResult.getValueCheckCode().getCode(), (String)null); + * + * ResponseBuilderUtils.addCodeInfoElement( responseDoc, pdfSignature, + * "CertificateCheck", verifyResult.getCertificateCheck().getCode(), + * (String)null); + * + * responseElem.appendChild(pdfSignature); } + */ } -- cgit v1.2.3